From eb2b7d972cee00a1c6b68b4b5f22fa834ca9db54 Mon Sep 17 00:00:00 2001 From: Donald Propst Date: Tue, 29 Oct 2024 16:50:06 -0400 Subject: [PATCH 1/4] ENG-52474 copy all hypertrace config to traceable --- .github/workflows/pr.yaml | 2 +- .gitmodules | 9 +- ENV_VARS.md | 23 + Makefile | 8 +- gen/go/go.mod | 4 +- gen/go/go.sum | 6 +- gen/go/proto/v1/config.proto | 176 + gen/go/v1/config.pb.go | 1471 +- gen/go/v1/config.pbloader.go | 305 + .../ai/traceable/agent/config/v1/config.proto | 176 + tools/env-vars-generator/HEADER.tpl.md | 5 + tools/env-vars-generator/go.sum | 4 + tools/env-vars-generator/protobuf/.gitmodules | 7 + .../datasets/google_message1/proto2/BUILD | 44 + .../google_message2/benchmark_message2.proto | 108 + .../google_message3/benchmark_message3.proto | 566 + .../protobuf/benchmarks/php/PhpBenchmark.php | 170 + .../benchmarks/python/py_benchmark.py | 161 + .../protobuf/benchmarks/util/__init__.py | 0 .../util/data_proto2_to_proto3_util.h | 64 + .../protobuf/cmake/CMakeLists.txt | 318 + .../protobuf/cmake/libprotoc.cmake | 132 + .../protobuf/cmake/protobuf-lite.pc.cmake | 11 + .../protobuf/cmake/version.rc.in | 45 + .../conformance/failure_list_objc.txt | 2 + .../protobuf/conformance/failure_list_php.txt | 30 + .../failure_list_python-post26.txt | 2 + .../conformance/failure_list_ruby.txt | 58 + .../text_format_conformance_suite.cc | 478 + .../conformance/third_party/jsoncpp/json.h | 2075 + .../csharp/Google.Protobuf.Tools.nuspec | 38 + .../csharp/protos/unittest_issues.proto | 126 + .../Google.Protobuf.Test/ByteStringTest.cs | 171 + .../Collections/RepeatedFieldTest.cs | 746 + .../TestProtos/ForeignMessagePartial.cs | 45 + .../protobuf/csharp/generate_protos.sh | 87 + .../csharp/protos/old_extensions2.proto | 50 + .../protobuf/csharp/protos/unittest.proto | 1113 + .../protos/unittest_import_proto3.proto | 56 + .../unittest_import_public_proto3.proto | 41 + .../Google.Protobuf.Benchmarks.csproj | 26 + .../ParseMessagesBenchmark.cs | 258 + .../WriteMessagesBenchmark.cs | 198 + .../OldExtensions2.cs | 40 + .../Unittest.cs | 31821 ++++++++++++++++ .../UnittestIssue6936A.cs | 46 + .../Buffers/ArrayBufferWriter.cs | 225 + .../Collections/MapFieldTest.cs | 661 + .../Compatibility/StreamExtensionsTest.cs | 67 + .../Google.Protobuf.Test.csproj | 31 + .../Google.Protobuf.Test/JsonFormatterTest.cs | 698 + .../Proto3OptionalTest.cs | 153 + .../Google.Protobuf.Test/SampleMessages.cs | 207 + .../WellKnownTypes/WrappersTest.cs | 546 + .../Collections/RepeatedField.cs | 698 + .../UnconditionalSuppressMessageAttribute.cs | 117 + .../src/Google.Protobuf/LimitedInputStream.cs | 110 + .../Google.Protobuf/ParserInternalState.cs | 115 + .../Google.Protobuf/Reflection/Descriptor.cs | 11020 ++++++ .../Reflection/DescriptorPool.cs | 334 + .../Reflection/ExtensionAccessor.cs | 69 + .../Google.Protobuf/Reflection/IDescriptor.cs | 55 + .../Reflection/IFieldAccessor.cs | 77 + .../Reflection/MessageDescriptor.cs | 430 + .../Google.Protobuf/SegmentedBufferHelper.cs | 296 + .../src/Google.Protobuf/UnknownField.cs | 290 + .../src/Google.Protobuf/WellKnownTypes/Any.cs | 387 + .../WellKnownTypes/AnyPartial.cs | 147 + .../WellKnownTypes/Duration.cs | 346 + .../WellKnownTypes/FieldMask.cs | 427 + .../WellKnownTypes/TimeExtensions.cs | 76 + .../protobuf/examples/ListPeople.java | 53 + .../protobuf/examples/list_people.cc | 79 + .../protobuf/fix_permissions.sh | 8 + tools/env-vars-generator/protobuf/global.json | 6 + .../protobuf/java/core/pom.xml | 158 + .../com/google/protobuf/BinaryReader.java | 1729 + .../google/protobuf/BlockingRpcChannel.java | 51 + .../protobuf/CodedOutputStreamWriter.java | 691 + .../protobuf/DiscardUnknownFieldsParser.java | 70 + .../com/google/protobuf/ExtensionLite.java | 60 + .../com/google/protobuf/GeneratedMessage.java | 3051 ++ .../protobuf/GeneratedMessageInfoFactory.java | 65 + .../google/protobuf/GeneratedMessageV3.java | 3240 ++ .../java/com/google/protobuf/LazyField.java | 154 + .../google/protobuf/MapFieldSchemaLite.java | 107 + .../main/java/com/google/protobuf/Reader.java | 379 + .../com/google/protobuf/SchemaFactory.java | 38 + .../protobuf/TextFormatParseLocation.java | 101 + .../protobuf/UnknownFieldSetLiteSchema.java | 140 + .../google/protobuf/UnsafeByteOperations.java | 121 + .../java/com/google/protobuf/UnsafeUtil.java | 1036 + .../google/protobuf/DeprecatedFieldTest.java | 84 + .../google/protobuf/FloatArrayListTest.java | 586 + .../com/google/protobuf/IntArrayListTest.java | 584 + .../com/google/protobuf/ParserLiteTest.java | 203 + .../java/com/google/protobuf/ParserTest.java | 334 + .../com/google/protobuf/Proto3SchemaTest.java | 48 + .../protobuf/RepeatedFieldBuilderV3Test.java | 191 + .../java/com/google/protobuf/TestUtil.java | 3900 ++ .../com/google/protobuf/WireFormatTest.java | 548 + .../protobuf/map_for_proto2_lite_test.proto | 130 + .../google/protobuf/map_for_proto2_test.proto | 129 + .../google/protobuf/nested_extension.proto | 48 + .../protobuf/test_check_utf8_size.proto | 52 + .../protobuf/java/internal/BUILD | 1 + .../protobuf/java/kotlin-lite/lite.awk | 25 + .../ExtendableMessageLiteExtensions.kt | 58 + .../ExtendableMessageLiteExtensionsTest.kt | 90 + .../protobuf/java/kotlin/BUILD | 284 + .../kotlin/generate-test-sources-build.xml | 34 + .../protobuf/java/kotlin/pom_template.xml | 23 + .../com/google/protobuf/ExtensionList.kt | 57 + .../com/google/protobuf/ExtensionListTest.kt | 155 + .../protobuf/example_extensible_message.proto | 46 + .../java/lite/generate-sources-build.xml | 19 + .../google/protobuf/util/JsonFormatTest.java | 1898 + .../protobuf/js/binary/arith_test.js | 354 + .../protobuf/js/binary/encoder.js | 510 + .../protobuf/js/binary/proto_test.js | 665 + .../protobuf/js/commonjs/export.js | 31 + .../commonjs/rewrite_tests_for_commonjs.js | 97 + .../v3.0.0/commonjs/test7/test7.proto | 42 + .../js/compatibility_tests/v3.1.0/data.proto | 51 + .../v3.1.0/message_test.js | 1060 + .../compatibility_tests/v3.1.0/proto3_test.js | 329 + .../js/compatibility_tests/v3.1.0/test.proto | 262 + .../v3.1.0/testempty.proto | 34 + .../protobuf/js/debug_test.js | 188 + .../code_size/apps_jspb/all_types_proto3.js | 312 + .../apps_jspb/popular_types_proto3.js | 53 + .../benchmarks/code_size/code_size_base.js | 57 + .../code_size/kernel/popular_types.js | 68 + .../js/experimental/runtime/bytestring.js | 183 + .../protobuf/js/experimental/runtime/int64.js | 403 + .../experimental/runtime/internal/checks.js | 708 + .../runtime/kernel/bool_test_pairs.js | 79 + .../conformance/test_all_types_proto2.js | 309 + .../runtime/kernel/indexer_test.js | 334 + .../runtime/kernel/internal_message.js | 24 + .../runtime/kernel/message_set_test.js | 262 + .../kernel/packed_sint32_test_pairs.js | 33 + .../js/experimental/runtime/kernel/storage.js | 67 + .../runtime/kernel/textencoding.js | 116 + .../runtime/kernel/textencoding_test.js | 113 + .../runtime/kernel/typed_arrays_test.js | 191 + .../runtime/kernel/uint8arrays.js | 28 + .../protobuf/js/gulpfile.js | 273 + .../protobuf/js/maps_test.js | 439 + .../protobuf/js/message_test.js | 1111 + .../protobuf/js/package.json | 27 + .../protobuf/js/proto3_test.js | 478 + .../protobuf/js/test10.proto | 39 + .../protobuf/js/test12.proto | 119 + .../protobuf/kokoro/docs/python.cfg | 7 + .../protobuf/kokoro/linux/32-bit/Dockerfile | 143 + .../protobuf/kokoro/linux/32-bit/build.sh | 18 + .../aarch64/protoc_crosscompile_aarch64.sh | 9 + .../kokoro/linux/aarch64/test_cpp_aarch64.sh | 14 + .../kokoro/linux/aarch64/test_ruby_aarch64.sh | 27 + .../testimage_protobuf_php_arm64v8/Dockerfile | 3 + .../protobuf/kokoro/linux/benchmark/run.sh | 99 + .../kokoro/linux/cpp_distcheck/continuous.cfg | 5 + .../kokoro/linux/cpp_tcmalloc/continuous.cfg | 5 + .../kokoro/linux/cpp_tcmalloc/presubmit.cfg | 5 + .../kokoro/linux/csharp/continuous.cfg | 5 + .../linux/dockerfile/test/python38/Dockerfile | 31 + .../linux/dockerfile/test/python39/Dockerfile | 31 + .../linux/java_linkage_monitor/continuous.cfg | 11 + .../kokoro/linux/jruby92/continuous.cfg | 11 + .../kokoro/linux/python27/continuous.cfg | 11 + .../kokoro/linux/python27_cpp/build.sh | 18 + .../kokoro/linux/python27_cpp/presubmit.cfg | 11 + .../protobuf/kokoro/linux/python35/build.sh | 18 + .../kokoro/linux/python35/presubmit.cfg | 11 + .../kokoro/linux/python35_cpp/build.sh | 18 + .../protobuf/kokoro/linux/python38/build.sh | 18 + .../kokoro/linux/python38_cpp/build.sh | 18 + .../kokoro/linux/python39_cpp/presubmit.cfg | 11 + .../kokoro/linux/python_cpp/continuous.cfg | 11 + .../protobuf/kokoro/linux/ruby26/build.sh | 18 + .../objectivec_cocoapods_integration/build.sh | 11 + .../macos/objectivec_ios_debug/continuous.cfg | 5 + .../protobuf/kokoro/macos/php7.0_mac/build.sh | 11 + .../kokoro/macos/php7.0_mac/presubmit.cfg | 5 + .../kokoro/macos/php7.3_mac/continuous.cfg | 5 + .../kokoro/macos/php7.3_mac/presubmit.cfg | 5 + .../kokoro/macos/prepare_build_macos_rc | 40 + .../protobuf/kokoro/macos/python/build.sh | 12 + .../kokoro/macos/python/presubmit.cfg | 5 + .../kokoro/macos/ruby26/continuous.cfg | 5 + .../protobuf/kokoro/macos/ruby27/build.sh | 12 + .../kokoro/macos/ruby30/continuous.cfg | 5 + .../release/csharp/windows/build_nuget.bat | 17 + .../release/python/linux/continuous.cfg | 8 + .../kokoro/release/python/macos/config.sh | 67 + .../release/python/windows/continuous.cfg | 8 + .../ruby/linux/ruby/ruby_build_environment.sh | 9 + .../protobuf/m4/acx_check_suncc.m4 | 73 + .../protobuf/m4/ax_prog_cxx_for_build.m4 | 110 + .../protobuf/m4/ax_pthread.m4 | 507 + .../protobuf/objectivec/.gitignore | 23 + .../protobuf/objectivec/DevTools/pddm.py | 690 + .../protobuf/objectivec/GPBAny.pbobjc.h | 186 + .../protobuf/objectivec/GPBCodedInputStream.h | 253 + .../protobuf/objectivec/GPBDuration.pbobjc.h | 145 + .../protobuf/objectivec/GPBEmpty.pbobjc.m | 85 + .../objectivec/GPBMessage_PackagePrivate.h | 124 + .../protobuf/objectivec/GPBRootObject.m | 245 + .../protobuf/objectivec/GPBRuntimeTypes.h | 151 + .../protobuf/objectivec/GPBWellKnownTypes.h | 245 + .../protobuf/objectivec/GPBWrappers.pbobjc.m | 457 + .../contents.xcworkspacedata | 7 + .../xcschemes/ProtocolBuffers.xcscheme | 133 + .../project.pbxproj | 1134 + .../xcshareddata/WorkspaceSettings.xcsettings | 8 + .../project.pbxproj | 290 + .../OSXCocoaPodsTester/AppDelegate.h | 37 + .../OSXCocoaPodsTester/AppDelegate.m | 48 + .../iOSCocoaPodsTester/Podfile-static | 8 + .../project.pbxproj | 309 + .../objectivec/Tests/GPBCompileTest07.m | 40 + .../Tests/GPBMessageTests+ClassNames.m | 164 + .../objectivec/Tests/GPBSwiftTests.swift | 460 + .../objectivec/Tests/GPBWellKnownTypesTest.m | 214 + .../protobuf/objectivec/Tests/golden_message | Bin 0 -> 493 bytes .../text_format_extensions_unittest_data.txt | 140 + .../Tests/text_format_map_unittest_data.txt | 70 + .../Tests/unittest_extension_chain_d.proto | 49 + .../Tests/unittest_extension_chain_f.proto | 44 + .../Tests/unittest_objc_options.proto | 61 + .../Tests/unittest_runtime_proto2.proto | 128 + .../protobuf/php/ext/google/protobuf/arena.c | 95 + .../php/ext/google/protobuf/protobuf.h | 180 + .../src/GPBMetadata/Google/Protobuf/Any.php | 30 + .../GPBMetadata/Google/Protobuf/Struct.php | Bin 0 -> 1162 bytes .../php/src/Google/Protobuf/GPBEmpty.php | 39 + .../php/src/Google/Protobuf/Int32Value.php | 68 + .../DescriptorProto/ReservedRange.php | 128 + .../Protobuf/Internal/EnumValueOptions.php | 123 + .../Internal/ExtensionRangeOptions.php | 67 + .../Internal/FieldDescriptorProto/Type.php | 153 + .../Internal/FieldDescriptorProto_Type.php | 16 + .../Protobuf/Internal/FileDescriptorSet.php | 63 + .../Internal/FileOptions/OptimizeMode.php | 64 + .../Internal/FileOptions_OptimizeMode.php | 16 + .../Internal/GetPublicDescriptorTrait.php | 41 + .../Internal/HasPublicDescriptorTrait.php | 43 + .../Protobuf/Internal/OneofDescriptor.php | 78 + .../Google/Protobuf/Internal/OneofField.php | 77 + .../Protobuf/Internal/RepeatedFieldIter.php | 122 + .../Internal/SourceCodeInfo_Location.php | 16 + .../Internal/UninterpretedOption/NamePart.php | 116 + .../php/src/Google/Protobuf/Syntax.php | 54 + .../protobuf/php/src/phpdoc.dist.xml | 15 + .../php/tests/GeneratedServiceTest.php | 127 + .../protobuf/php/tests/proto/empty/echo.proto | 17 + .../test_reserved_enum_value_lower.proto | 83 + .../proto/test_wrapper_type_setters.proto | 26 + .../protobuf/php/tests/test_base.php | 367 + .../protobuf/php/tests/valgrind.supp | 33 + .../env-vars-generator/protobuf/protobuf.bzl | 523 + .../protobuf/protobuf_version.bzl | 1 + .../protobuf/protoc-artifacts/README.md | 161 + .../protobuf/protoc-artifacts/build-protoc.sh | 294 + .../protobuf/protoc-artifacts/pom.xml | 148 + .../protobuf/python/docs/conf.py | 254 + .../docs/google/protobuf/descriptor_pb2.rst | 21 + .../docs/google/protobuf/field_mask_pb2.rst | 21 + .../docs/google/protobuf/proto_builder.rst | 21 + .../docs/google/protobuf/struct_pb2.rst | 21 + .../google/protobuf/internal/decoder.py | 1029 + .../protobuf/internal/factory_test1.proto | 70 + .../protobuf/internal/python_protobuf.cc | 59 + .../protobuf/internal/text_encoding_test.py | 67 + .../protobuf/pyext/descriptor_database.cc | 187 + .../google/protobuf/pyext/descriptor_pool.h | 149 + .../google/protobuf/pyext/extension_dict.cc | 475 + .../google/protobuf/pyext/extension_dict.h | 72 + .../google/protobuf/pyext/map_container.cc | 926 + .../google/protobuf/pyext/map_container.h | 90 + .../google/protobuf/pyext/message_factory.h | 104 + .../google/protobuf/pyext/message_module.cc | 134 + .../pyext/repeated_composite_container.cc | 601 + .../pyext/repeated_scalar_container.cc | 769 + .../google/protobuf/pyext/unknown_fields.h | 91 + .../python/google/protobuf/symbol_database.py | 194 + .../python/google/protobuf/text_format.py | 1795 + .../protobuf/python/stubout.py | 143 + .../v3.0.0/tests/repeated_field_test.rb | 630 + .../protobuf/ruby/ext/google/protobuf_c/map.c | 702 + .../protobuf/ruby/ext/google/protobuf_c/map.h | 66 + .../ruby/ext/google/protobuf_c/protobuf.h | 120 + .../protobuf/ruby/tests/common_tests.rb | 1810 + .../protobuf/src/google/protobuf/any_test.cc | 184 + .../protobuf/src/google/protobuf/api.pb.h | 1448 + .../google/protobuf/arenastring_unittest.cc | 157 + .../compiler/command_line_interface.cc | 2618 ++ .../protobuf/compiler/cpp/cpp_message_field.h | 144 + .../compiler/cpp/cpp_padding_optimizer.h | 65 + .../protobuf/compiler/cpp/cpp_string_field.h | 127 + .../protobuf/compiler/csharp/csharp_enum.cc | 99 + .../compiler/csharp/csharp_field_base.h | 111 + .../compiler/csharp/csharp_generator.cc | 112 + .../compiler/csharp/csharp_generator.h | 70 + .../compiler/csharp/csharp_message_field.h | 93 + .../csharp/csharp_repeated_message_field.h | 79 + .../csharp/csharp_source_generator_base.h | 71 + .../protobuf/compiler/java/java_extension.h | 115 + .../compiler/java/java_generator_factory.cc | 86 + .../compiler/java/java_message_builder_lite.h | 86 + .../java/java_primitive_field_lite.cc | 779 + .../compiler/java/java_string_field_lite.cc | 864 + .../objectivec/objectivec_extension.h | 67 + .../objectivec/objectivec_generator.h | 79 + .../compiler/objectivec/objectivec_helpers.h | 351 + .../src/google/protobuf/compiler/plugin.h | 95 + .../src/google/protobuf/compiler/plugin.pb.h | 1909 + .../compiler/python/python_plugin_unittest.cc | 161 + .../ruby/ruby_generated_code_proto2_pb.rb | 80 + .../ruby/ruby_generated_pkg_explicit_pb.rb | 20 + .../google/protobuf/generated_enum_util.cc | 95 + .../src/google/protobuf/generated_enum_util.h | 83 + .../protobuf/generated_message_tctable_impl.h | 302 + .../protobuf/src/google/protobuf/has_bits.h | 116 + .../src/google/protobuf/io/package_info.h | 53 + .../protobuf/src/google/protobuf/io/strtod.cc | 82 + .../google/protobuf/io/zero_copy_stream.cc | 55 + .../protobuf/io/zero_copy_stream_impl_lite.cc | 467 + .../protobuf/io/zero_copy_stream_impl_lite.h | 408 + .../google/protobuf/lite_arena_unittest.cc | 90 + .../src/google/protobuf/map_lite_test_util.cc | 93 + .../google/protobuf/map_lite_unittest.proto | 127 + .../src/google/protobuf/map_test_util.inc | 271 + .../src/google/protobuf/message_unittest.inc | 897 + .../protobuf/src/google/protobuf/metadata.h | 36 + .../protobuf/reflection_ops_unittest.cc | 546 + .../repeated_field_reflection_unittest.cc | 708 + .../src/google/protobuf/repeated_ptr_field.cc | 157 + .../src/google/protobuf/stubs/common.h | 197 + .../google/protobuf/stubs/int128_unittest.cc | 511 + .../src/google/protobuf/stubs/map_util.h | 769 + .../google/protobuf/stubs/platform_macros.h | 138 + .../src/google/protobuf/stubs/status_test.cc | 278 + .../src/google/protobuf/stubs/stringprintf.cc | 175 + .../src/google/protobuf/stubs/substitute.cc | 136 + .../google/protobuf/testdata/bad_utf8_string | 1 + ...format_unittest_data_oneof_implemented.txt | 129 + .../protobuf/unittest_custom_options.proto | 464 + .../src/google/protobuf/unittest_import.proto | 73 + ...test_lazy_dependencies_custom_option.proto | 67 + .../unittest_lazy_dependencies_enum.proto | 61 + .../internal/default_value_objectwriter.cc | 642 + .../util/internal/field_mask_utility.cc | 218 + .../util/internal/json_stream_parser.cc | 995 + .../protobuf/util/internal/location_tracker.h | 69 + .../util/internal/structured_objectwriter.h | 120 + .../testdata/default_value_test.proto | 53 + .../google/protobuf/util/internal/utility.cc | 416 + .../src/google/protobuf/util/time_util.h | 313 + .../google/protobuf/util/type_resolver_util.h | 57 + .../src/google/protobuf/wire_format_lite.cc | 784 + tools/env-vars-generator/protobuf/tests.sh | 650 + .../third_party/benchmark/CONTRIBUTORS | 59 + .../benchmark/cmake/CXXFeatureCheck.cmake | 46 + .../include/benchmark/benchmark_api.h | 27 + .../third_party/benchmark/src/complexity.h | 60 + .../protobuf/third_party/benchmark/src/log.h | 73 + .../third_party/benchmark/src/timers.cc | 212 + .../third_party/benchmark/test/cxx03_test.cc | 48 + .../third_party/benchmark/test/filter_test.cc | 104 + .../benchmark/test/register_benchmark_test.cc | 182 + .../third_party/googletest/ci/env-linux.sh | 41 + .../googletest/ci/install-platformio.sh | 5 + .../third_party/googletest/configure.ac | 16 + .../googletest/googlemock/configure.ac | 146 + .../googletest/googlemock/docs/CookBook.md | 3660 ++ .../gmock-generated-function-mockers.h.pump | 227 + .../googlemock/msvc/2005/gmock.vcproj | 191 + .../googlemock/msvc/2010/gmock_config.props | 19 + .../googlemock/scripts/fuse_gmock_files.py | 240 + .../googlemock/scripts/gmock_doctor.py | 640 + .../googlemock/src/gmock-matchers.cc | 462 + .../googlemock/src/gmock-spec-builders.cc | 887 + .../googletest/googlemock/src/gmock.cc | 213 + .../test/gmock-cardinalities_test.cc | 427 + .../test/gmock-function-mocker_nc_test.py | 43 + .../test/gmock-more-actions_test.cc | 699 + .../googlemock/test/gmock-port_test.cc | 42 + .../googlemock/test/gmock_link_test.h | 690 + .../googlemock/test/gmock_output_test_.cc | 309 + .../googletest/codegear/gtest_main.cbproj | 82 + .../googletest/include/gtest/gtest-matchers.h | 809 + .../include/gtest/internal/gtest-param-util.h | 762 + .../include/gtest/internal/gtest-type-util.h | 3347 ++ .../googletest/googletest/m4/gtest.m4 | 74 + .../2010/gtest_prod_test-md.vcxproj.filters | 26 + .../msvc/2010/gtest_unittest-md.vcxproj | 188 + .../googletest/samples/prime_tables.h | 126 + .../googletest/googletest/samples/sample2.h | 81 + .../googletest/samples/sample3_unittest.cc | 149 + .../googletest/samples/sample7_unittest.cc | 117 + .../googletest/scripts/fuse_gtest_files.py | 253 + .../googletest/googletest/scripts/pump.py | 855 + .../googletest/scripts/release_docs.py | 158 + .../googletest/src/gtest-death-test.cc | 1636 + .../googletest/src/gtest-internal-inl.h | 1206 + .../googletest/test/gtest-typed-test2_test.cc | 44 + .../test/gtest_list_output_unittest.py | 141 + .../googletest/test/gtest_sole_header_test.cc | 56 + .../googletest/test/gtest_test_utils.py | 313 + .../test/gtest_throw_on_failure_ex_test.cc | 90 + .../test/gtest_xml_outfiles_test.py | 135 + .../xcode/Samples/FrameworkSample/widget.h | 59 + .../protobuf/third_party/utf8_range/BUILD | 13 + .../protobuf/util/python/BUILD | 20 + .../cmd/generator/_protobuf/.bazelignore | 4 + .../cmd/generator/_protobuf/WORKSPACE | 68 + .../cmd/generator/_protobuf/appveyor.yml | 47 + .../cmd/generator/_protobuf/benchmarks/BUILD | 65 + .../_protobuf/benchmarks/Makefile.am | 664 + .../generator/_protobuf/benchmarks/cpp/BUILD | 15 + .../datasets/google_message1/proto2/BUILD | 44 + .../proto2/dataset.google_message1_proto2.pb | Bin 0 -> 289 bytes .../benchmark_message3_6.proto | 483 + .../benchmark_message4_2.proto | 316 + .../benchmarks/python/py_benchmark.py | 161 + .../benchmarks/util/protoc-gen-gogoproto.cc | 103 + .../util/protoc-gen-proto2_to_proto3.cc | 115 + .../_protobuf/cmake/extract_includes.bat.in | 143 + .../_protobuf/cmake/protobuf.pc.cmake | 11 + .../cmd/generator/_protobuf/configure.ac | 247 + .../_protobuf/conformance/conformance_cpp.cc | 268 + .../conformance/conformance_test_main.cc | 40 + .../conformance/failure_list_python_cpp.txt | 8 + .../conformance/third_party/jsoncpp/json.h | 2075 + .../csharp/protos/unittest_issues.proto | 126 + .../protobuf/unittest_well_known_types.proto | 114 + .../Compatibility/TypeExtensionsTest.cs | 117 + .../Google.Protobuf.Test.csproj | 25 + .../Google.Protobuf.Test/JsonParserTest.cs | 939 + .../Reflection/FieldAccessTest.cs | 218 + .../WellKnownTypes/DurationTest.cs | 132 + .../csharp/compatibility_tests/v3.0.0/test.sh | 80 + .../_protobuf/csharp/install_dotnet_sdk.ps1 | 20 + .../csharp/keys/Google.Protobuf.public.snk | Bin 0 -> 160 bytes .../_protobuf/csharp/keys/Google.Protobuf.snk | Bin 0 -> 596 bytes .../protos/unittest_import_proto3.proto | 56 + .../BenchmarkDatasetConfig.cs | 89 + .../WriteRawPrimitivesBenchmark.cs | 519 + .../MapUnittestProto3.cs | 2277 ++ .../OldExtensions1.cs | 148 + .../UnittestIssue6936C.cs | 244 + .../UnittestIssues.cs | 3832 ++ .../UnittestSelfreferentialOptions.cs | 379 + .../Google.Protobuf.Test/ByteStringTest.cs | 439 + .../DeprecatedMemberTest.cs | 55 + .../Google.Protobuf.Test/FieldMaskTreeTest.cs | 436 + .../GeneratedMessageTest.Proto2.cs | 397 + .../src/Google.Protobuf.Test/SampleNaNs.cs | 53 + .../Google.Protobuf.Test/TestCornerCases.cs | 62 + .../WellKnownTypes/DurationTest.cs | 132 + .../WellKnownTypes/FieldMaskTest.cs | 245 + .../csharp/src/Google.Protobuf/ByteArray.cs | 79 + .../Collections/ProtobufEqualityComparers.cs | 130 + .../Compatibility/MethodInfoExtensions.cs | 47 + .../csharp/src/Google.Protobuf/Extension.cs | 119 + .../csharp/src/Google.Protobuf/FieldCodec.cs | 887 + .../InvalidProtocolBufferException.cs | 140 + .../Reflection/DescriptorPool.cs | 334 + .../Reflection/DescriptorUtil.cs | 64 + .../Reflection/IFieldAccessor.cs | 77 + .../Reflection/MessageDescriptor.cs | 430 + .../src/Google.Protobuf/UnknownField.cs | 290 + .../WellKnownTypes/Timestamp.cs | 375 + .../Google.Protobuf/WriterInternalState.cs | 62 + .../cmd/generator/_protobuf/docs/jvm_aot.md | 18 + .../cmd/generator/_protobuf/docs/options.md | 302 + .../java/core/generate-test-sources-build.xml | 60 + .../com/google/protobuf/BinaryReader.java | 1729 + .../com/google/protobuf/ByteBufferWriter.java | 181 + .../DescriptorMessageInfoFactory.java | 793 + .../protobuf/DiscardUnknownFieldsParser.java | 70 + .../com/google/protobuf/ExtensionLite.java | 60 + .../java/com/google/protobuf/FieldSet.java | 1303 + .../com/google/protobuf/LongArrayList.java | 297 + .../com/google/protobuf/MessageSetSchema.java | 392 + .../protobuf/NewInstanceSchemaFull.java | 39 + .../com/google/protobuf/NioByteString.java | 293 + .../main/java/com/google/protobuf/Parser.java | 242 + .../java/com/google/protobuf/Protobuf.java | 149 + .../com/google/protobuf/RawMessageInfo.java | 221 + .../com/google/protobuf/SchemaFactory.java | 38 + .../protobuf/TextFormatParseLocation.java | 101 + .../com/google/protobuf/TypeRegistry.java | 159 + .../main/java/com/google/protobuf/Utf8.java | 1996 + .../java/com/google/protobuf/AnyTest.java | 136 + .../google/protobuf/BooleanArrayListTest.java | 586 + .../ExperimentalTestDataProvider.java | 189 + .../google/protobuf/IsValidUtf8TestUtil.java | 322 + .../google/protobuf/LazyFieldLiteTest.java | 266 + .../com/google/protobuf/PackedFieldTest.java | 242 + .../Proto2ExtensionLookupSchemaTest.java | 168 + .../com/google/protobuf/Proto3SchemaTest.java | 48 + .../protobuf/RepeatedFieldBuilderV3Test.java | 191 + .../protobuf/TestBadIdentifiersLite.java | 93 + .../java/com/google/protobuf/TestSchemas.java | 94 + .../com/google/protobuf/TypeRegistryTest.java | 69 + .../protobuf/map_for_proto2_lite_test.proto | 130 + .../google/protobuf/nested_extension.proto | 48 + .../protobuf/nested_extension_lite.proto | 50 + .../protobuf/non_nested_extension.proto | 49 + .../google/protobuf/proto3_message_lite.proto | 320 + .../_protobuf/java/kotlin-lite/lite.awk | 25 + .../OnlyForUseByGeneratedProtoCode.kt | 48 + .../kotlin/com/google/protobuf/DslMapTest.kt | 194 + .../cmd/generator/_protobuf/java/pom.xml | 287 + .../com/google/protobuf/util/Structs.java | 65 + .../_protobuf/js/commonjs/jasmine.json | 9 + .../_protobuf/js/commonjs/test6/test6.proto | 40 + .../v3.0.0/commonjs/import_test.js | 52 + .../v3.0.0/message_test.js | 1081 + .../v3.0.0/proto3_test.proto | 89 + .../v3.1.0/binary/proto_test.js | 628 + .../v3.1.0/message_test.js | 1060 + .../js/compatibility_tests/v3.1.0/test3.proto | 53 + .../cmd/generator/_protobuf/js/data.proto | 50 + .../apps_jspb/popular_types_proto3.js | 53 + .../js/experimental/runtime/bytestring.js | 183 + .../runtime/kernel/binary_storage_test.js | 165 + .../js/experimental/runtime/kernel/indexer.js | 55 + .../kernel/packed_double_test_pairs.js | 52 + .../runtime/kernel/packed_float_test_pairs.js | 34 + .../runtime/kernel/packed_int32_test_pairs.js | 33 + .../runtime/kernel/packed_int64_test_pairs.js | 34 + .../kernel/packed_sfixed64_test_pairs.js | 53 + .../js/experimental/runtime/kernel/tag.js | 144 + .../cmd/generator/_protobuf/js/package.json | 27 + .../cmd/generator/_protobuf/js/test13.proto | 70 + .../cmd/generator/_protobuf/js/test2.proto | 60 + .../cmd/generator/_protobuf/js/test9.proto | 39 + .../cmd/generator/_protobuf/kokoro/README.md | 12 + .../run_dockcross_manylinux2014_aarch64.sh | 36 + .../kokoro/linux/aarch64/test_php_aarch64.sh | 31 + .../kokoro/linux/bazel/continuous.cfg | 5 + .../kokoro/linux/cpp_aarch64/continuous.cfg | 5 + .../kokoro/linux/cpp_distcheck/continuous.cfg | 5 + .../kokoro/linux/csharp/continuous.cfg | 5 + .../kokoro/linux/dist_install/continuous.cfg | 5 + .../linux/dockerfile/test/csharp/Dockerfile | 41 + .../dockerfile/test/javascript/Dockerfile | 37 + .../kokoro/linux/java_aarch64/presubmit.cfg | 11 + .../kokoro/linux/java_jdk7/presubmit.cfg | 11 + .../kokoro/linux/javascript/continuous.cfg | 11 + .../kokoro/linux/jruby92/presubmit.cfg | 11 + .../kokoro/linux/make_test_output.py | 94 + .../kokoro/linux/php80/presubmit.cfg | 5 + .../kokoro/linux/python27_cpp/presubmit.cfg | 11 + .../kokoro/linux/python310_cpp/build.sh | 18 + .../_protobuf/kokoro/linux/python35/build.sh | 18 + .../kokoro/linux/python35/presubmit.cfg | 11 + .../kokoro/linux/python36_cpp/presubmit.cfg | 11 + .../_protobuf/kokoro/linux/python37/build.sh | 18 + .../kokoro/linux/python37_cpp/presubmit.cfg | 11 + .../kokoro/linux/python38/presubmit.cfg | 11 + .../kokoro/linux/python38_cpp/build.sh | 18 + .../_protobuf/kokoro/linux/python39/build.sh | 18 + .../kokoro/linux/python39_cpp/build.sh | 18 + .../linux/python_compatibility/build.sh | 17 + .../kokoro/linux/ruby27/continuous.cfg | 11 + .../_protobuf/kokoro/macos/cpp/build.sh | 11 + .../objectivec_cocoapods_integration/build.sh | 11 + .../macos/objectivec_osx/continuous.cfg | 5 + .../kokoro/macos/php7.0_mac/presubmit.cfg | 5 + .../release/csharp/windows/continuous.cfg | 11 + .../kokoro/release/protoc/macos/build.sh | 15 + .../kokoro/release/protoc/macos/release.cfg | 8 + .../release/python/linux/build_artifacts.sh | 90 + .../kokoro/release/python/linux/config.sh | 93 + .../release/python/windows/presubmit.cfg | 8 + .../_protobuf/m4/ax_prog_cxx_for_build.m4 | 110 + .../_protobuf/objectivec/GPBEmpty.pbobjc.m | 85 + .../_protobuf/objectivec/GPBProtocolBuffers.m | 66 + .../GPBProtocolBuffers_RuntimeSupport.h | 40 + .../objectivec/GPBSourceContext.pbobjc.h | 77 + .../_protobuf/objectivec/GPBType.pbobjc.m | 727 + .../_protobuf/objectivec/GPBUnknownField.h | 99 + .../_protobuf/objectivec/GPBUnknownFieldSet.m | 395 + .../GPBUnknownField_PackagePrivate.h | 47 + .../_protobuf/objectivec/GPBWrappers.pbobjc.h | 219 + .../xcshareddata/IDEWorkspaceChecks.plist | 8 + .../contents.xcworkspacedata | 7 + .../xcschemes/ProtocolBuffers.xcscheme | 133 + .../project.pbxproj | 290 + .../Base.lproj/Main.storyboard | 26 + .../iOSCocoaPodsTester/main.m | 39 + .../objectivec/Tests/GPBArrayTests.m | 3731 ++ .../objectivec/Tests/GPBCompileTest15.m | 40 + .../objectivec/Tests/GPBCompileTest21.m | 40 + .../Tests/GPBDictionaryTests+UInt32.m | 3678 ++ .../objectivec/Tests/GPBDictionaryTests.pddm | 1048 + .../Tests/UnitTests-Bridging-Header.h | 6 + .../text_format_extensions_unittest_data.txt | 140 + .../Tests/text_format_unittest_data.txt | 116 + .../Tests/unittest_extension_chain_d.proto | 49 + .../google/protobuf/Timestamp.pbobjc.h | 2 + .../_protobuf/php/ext/google/protobuf/array.h | 67 + .../php/ext/google/protobuf/config.m4 | 10 + .../_protobuf/php/ext/google/protobuf/names.c | 227 + .../_protobuf/php/ext/google/protobuf/wkt.inc | 3245 ++ .../src/GPBMetadata/Google/Protobuf/Any.php | 30 + .../GPBMetadata/Google/Protobuf/Duration.php | 30 + .../GPBMetadata/Google/Protobuf/GPBEmpty.php | 29 + .../Google/Protobuf/Internal/Descriptor.php | 278 + .../php/src/Google/Protobuf/BytesValue.php | 68 + .../php/src/Google/Protobuf/DoubleValue.php | 68 + .../php/src/Google/Protobuf/Enum.php | 213 + .../php/src/Google/Protobuf/EnumValue.php | 135 + .../Google/Protobuf/EnumValueDescriptor.php | 64 + .../DescriptorProto/ExtensionRange.php | 161 + .../DescriptorProto/ReservedRange.php | 128 + .../Protobuf/Internal/EnumBuilderContext.php | 63 + .../Internal/EnumValueDescriptorProto.php | 146 + .../Internal/FieldDescriptorProto_Label.php | 16 + .../Protobuf/Internal/FieldOptions/CType.php | 58 + .../Protobuf/Internal/FieldOptions/JSType.php | 62 + .../src/Google/Protobuf/Internal/GPBType.php | 55 + .../Internal/HasPublicDescriptorTrait.php | 43 + .../src/Google/Protobuf/Internal/Message.php | 2034 + .../Internal/MessageBuilderContext.php | 120 + .../Google/Protobuf/Internal/OneofField.php | 77 + .../Internal/SourceCodeInfo/Location.php | 448 + .../php/src/Google/Protobuf/Syntax.php | 54 + .../php/tests/WrapperTypeSettersTest.php | 317 + .../proto/test_import_descriptor_proto.proto | 16 + .../php/tests/proto/test_php_namespace.proto | 31 + .../proto/test_reserved_message_upper.proto | 81 + .../_protobuf/php/tests/test_base.php | 367 + .../cmd/generator/_protobuf/protobuf.pc.in | 13 + .../cmd/generator/_protobuf/protobuf_deps.bzl | 93 + .../generator/_protobuf/python/docs/conf.py | 254 + .../_protobuf/python/docs/generate_docs.py | 192 + .../protobuf/internal/factory_test2.proto | 104 + .../internal/import_test_package/__init__.py | 33 + .../protobuf/internal/json_format_test.py | 1276 + .../internal/service_reflection_test.py | 139 + .../protobuf/internal/symbol_database_test.py | 133 + .../google/protobuf/pyext/cpp_message.py | 65 + .../protobuf/pyext/descriptor_database.h | 82 + .../google/protobuf/pyext/descriptor_pool.cc | 812 + .../google/protobuf/pyext/message_factory.h | 104 + .../pyext/repeated_composite_container.cc | 601 + .../protobuf/pyext/scoped_pyobject_ptr.h | 101 + .../generate_py_protobufs.py | 147 + .../cmd/generator/_protobuf/python/setup.py | 327 + .../cmd/generator/_protobuf/python/stubout.py | 143 + .../cmd/generator/_protobuf/python/tox.ini | 21 + .../ruby/compatibility_tests/v3.0.0/README.md | 5 + .../compatibility_tests/v3.0.0/tests/basic.rb | 1276 + .../v3.0.0/tests/repeated_field_test.rb | 630 + .../v3.0.0/tests/stress.rb | 38 + .../ruby/ext/google/protobuf_c/message.h | 104 + .../lib/google/protobuf/repeated_field.rb | 188 + .../lib/google/protobuf/well_known_types.rb | 240 + .../protobuf/jruby/RubyFieldDescriptor.java | 270 + .../com/google/protobuf/jruby/RubyMap.java | 474 + .../ruby/tests/encode_decode_test.rb | 104 + .../_protobuf/ruby/tests/test_import.proto | 5 + .../ruby/tests/test_ruby_package.proto | 7 + .../cmd/generator/_protobuf/src/Makefile.am | 914 + .../_protobuf/src/google/protobuf/any.pb.cc | 352 + .../_protobuf/src/google/protobuf/any.proto | 158 + .../_protobuf/src/google/protobuf/arena.h | 818 + .../compiler/command_line_interface.cc | 2618 ++ .../protobuf/compiler/cpp/cpp_message.cc | 4584 +++ .../protobuf/compiler/cpp/cpp_message_field.h | 144 + .../google/protobuf/compiler/cpp/cpp_names.h | 96 + .../compiler/cpp/cpp_primitive_field.cc | 505 + .../protobuf/compiler/cpp/cpp_string_field.cc | 915 + .../protobuf/compiler/cpp/cpp_string_field.h | 127 + .../cpp/cpp_test_large_enum_value.proto | 43 + .../compiler/csharp/csharp_field_base.h | 111 + .../compiler/csharp/csharp_message_field.cc | 293 + .../protobuf/compiler/csharp/csharp_options.h | 81 + .../compiler/csharp/csharp_primitive_field.cc | 349 + .../csharp/csharp_reflection_class.cc | 330 + .../csharp/csharp_repeated_enum_field.h | 79 + .../compiler/csharp/csharp_wrapper_field.cc | 308 + .../protobuf/compiler/java/java_context.h | 113 + .../protobuf/compiler/java/java_extension.h | 115 + .../protobuf/compiler/java/java_generator.h | 76 + .../protobuf/compiler/java/java_helpers.cc | 1111 + .../protobuf/compiler/java/java_helpers.h | 459 + .../compiler/java/java_kotlin_generator.cc | 162 + .../compiler/java/java_message_lite.h | 86 + .../compiler/java/java_string_field.h | 160 + .../ruby/ruby_generated_code_proto2_pb.rb | 80 + .../ruby_generated_pkg_explicit_legacy.proto | 9 + .../google/protobuf/compiler/subprocess.cc | 475 + .../google/protobuf/inlined_string_field.h | 384 + .../src/google/protobuf/io/io_win32.cc | 470 + .../src/google/protobuf/io/tokenizer.h | 440 + .../google/protobuf/io/zero_copy_stream.cc | 55 + .../src/google/protobuf/io/zero_copy_stream.h | 253 + .../google/protobuf/lite_arena_unittest.cc | 90 + .../_protobuf/src/google/protobuf/map_field.h | 923 + .../src/google/protobuf/map_lite_test_util.h | 80 + .../_protobuf/src/google/protobuf/map_test.cc | 63 + .../google/protobuf/proto3_arena_unittest.cc | 632 + .../src/google/protobuf/reflection_ops.cc | 454 + .../src/google/protobuf/repeated_ptr_field.cc | 157 + .../src/google/protobuf/repeated_ptr_field.h | 2022 + .../src/google/protobuf/source_context.pb.h | 290 + .../_protobuf/src/google/protobuf/struct.pb.h | 1182 + .../src/google/protobuf/stubs/bytestream.cc | 194 + .../src/google/protobuf/stubs/bytestream.h | 351 + .../google/protobuf/stubs/common_unittest.cc | 358 + .../src/google/protobuf/stubs/hash.h | 114 + .../src/google/protobuf/stubs/map_util.h | 769 + .../src/google/protobuf/stubs/mathutil.h | 162 + .../src/google/protobuf/stubs/status_macros.h | 89 + .../src/google/protobuf/stubs/status_test.cc | 278 + .../src/google/protobuf/stubs/template_util.h | 138 + .../src/google/protobuf/testing/file.cc | 215 + .../src/google/protobuf/testing/googletest.h | 104 + .../src/google/protobuf/testing/zcgunzip.cc | 84 + .../_protobuf/src/google/protobuf/type.pb.h | 2581 ++ .../src/google/protobuf/unittest.proto | 1158 + .../unittest_enormous_descriptor.proto | 1048 + .../protobuf/unittest_mset_wire_format.proto | 52 + .../unittest_no_generic_services.proto | 54 + .../protobuf/util/internal/json_escaping.cc | 372 + .../util/internal/json_stream_parser_test.cc | 979 + .../util/internal/protostream_objectsource.cc | 1112 + .../util/internal/testdata/field_mask.proto | 71 + .../protobuf/util/message_differencer.h | 976 + .../util/message_differencer_unittest.cc | 3812 ++ .../src/google/protobuf/util/time_util.cc | 511 + .../src/google/protobuf/wrappers.pb.cc | 1955 + .../src/google/protobuf/wrappers.pb.h | 1734 + .../third_party/benchmark/appveyor.yml | 56 + .../benchmark/cmake/AddCXXCompilerFlag.cmake | 64 + .../benchmark/cmake/GetGitVersion.cmake | 51 + .../benchmark/include/benchmark/reporter.h | 27 + .../third_party/benchmark/src/CMakeLists.txt | 78 + .../benchmark/src/commandlineflags.h | 79 + .../third_party/benchmark/src/counter.cc | 68 + .../_protobuf/third_party/benchmark/src/log.h | 73 + .../benchmark/test/complexity_test.cc | 167 + .../test/user_counters_tabular_test.cc | 250 + .../benchmark/tools/compare_bench.py | 68 + .../third_party/googletest/.travis.yml | 78 + .../third_party/googletest/Makefile.am | 14 + .../third_party/googletest/README.md | 132 + .../googletest/ci/install-platformio.sh | 5 + .../googletest/googlemock/cmake/gmock.pc.in | 11 + .../gmock/gmock-generated-matchers.h.pump | 349 + .../internal/custom/gmock-generated-actions.h | 10 + .../googletest/googlemock/msvc/2005/gmock.sln | 32 + .../googlemock/msvc/2015/gmock_config.props | 19 + .../googlemock/scripts/fuse_gmock_files.py | 240 + .../scripts/generator/cpp/__init__.py | 0 .../googlemock/src/gmock-cardinalities.cc | 155 + .../googlemock/src/gmock-spec-builders.cc | 887 + .../googlemock/test/gmock-pp_test.cc | 73 + .../googlemock/test/gmock_leak_test_.cc | 99 + .../googletest/googletest/README.md | 327 + .../googletest/cmake/gtest_main.pc.in | 11 + .../googletest/codegear/gtest.cbproj | 138 + .../googletest/codegear/gtest_all.cc | 38 + .../googletest/codegear/gtest_unittest.cbproj | 88 + .../googletest/googletest/docs/XcodeGuide.md | 93 + .../googletest/include/gtest/gtest-message.h | 224 + .../googletest/include/gtest/gtest-spi.h | 238 + .../include/gtest/gtest-typed-test.h | 326 + .../googletest/googletest/m4/acx_pthread.m4 | 363 + .../googletest/msvc/2010/gtest.vcxproj | 149 + .../2010/gtest_prod_test-md.vcxproj.filters | 26 + .../msvc/2010/gtest_prod_test.vcxproj | 191 + .../msvc/2010/gtest_unittest.vcxproj | 180 + .../msvc/2010/gtest_unittest.vcxproj.filters | 18 + .../googletest/samples/sample4_unittest.cc | 53 + .../googletest/samples/sample8_unittest.cc | 154 + .../googletest/scripts/upload_gtest.py | 78 + .../googletest/src/gtest-death-test.cc | 1636 + .../googletest/src/gtest-matchers.cc | 152 + .../googletest/src/gtest-typed-test.cc | 118 + .../googletest/googletest/src/gtest_main.cc | 47 + .../test/googletest-env-var-test.py | 117 + .../test/googletest-json-output-unittest.py | 634 + ...oogletest-param-test-invalid-name1-test.py | 63 + .../test/googletest-shuffle-test.py | 323 + .../test/googletest-throw-on-failure-test.py | 168 + .../test/gtest_list_output_unittest_.cc | 51 + .../WidgetFramework.xcodeproj/project.pbxproj | 457 + .../third_party/utf8_range/utf8_range.c | 395 + .../_protobuf/third_party/zlib.BUILD | 63 + .../cmd/generator/_templates/options.go.tmpl | 40 + .../generator/_templates/testdata/config.yaml | 6 + 799 files changed, 269242 insertions(+), 287 deletions(-) create mode 100644 tools/env-vars-generator/HEADER.tpl.md create mode 100644 tools/env-vars-generator/go.sum create mode 100644 tools/env-vars-generator/protobuf/.gitmodules create mode 100644 tools/env-vars-generator/protobuf/benchmarks/datasets/google_message1/proto2/BUILD create mode 100644 tools/env-vars-generator/protobuf/benchmarks/datasets/google_message2/benchmark_message2.proto create mode 100644 tools/env-vars-generator/protobuf/benchmarks/datasets/google_message3/benchmark_message3.proto create mode 100644 tools/env-vars-generator/protobuf/benchmarks/php/PhpBenchmark.php create mode 100644 tools/env-vars-generator/protobuf/benchmarks/python/py_benchmark.py create mode 100644 tools/env-vars-generator/protobuf/benchmarks/util/__init__.py create mode 100644 tools/env-vars-generator/protobuf/benchmarks/util/data_proto2_to_proto3_util.h create mode 100644 tools/env-vars-generator/protobuf/cmake/CMakeLists.txt create mode 100644 tools/env-vars-generator/protobuf/cmake/libprotoc.cmake create mode 100644 tools/env-vars-generator/protobuf/cmake/protobuf-lite.pc.cmake create mode 100644 tools/env-vars-generator/protobuf/cmake/version.rc.in create mode 100644 tools/env-vars-generator/protobuf/conformance/failure_list_objc.txt create mode 100644 tools/env-vars-generator/protobuf/conformance/failure_list_php.txt create mode 100644 tools/env-vars-generator/protobuf/conformance/failure_list_python-post26.txt create mode 100644 tools/env-vars-generator/protobuf/conformance/failure_list_ruby.txt create mode 100644 tools/env-vars-generator/protobuf/conformance/text_format_conformance_suite.cc create mode 100644 tools/env-vars-generator/protobuf/conformance/third_party/jsoncpp/json.h create mode 100644 tools/env-vars-generator/protobuf/csharp/Google.Protobuf.Tools.nuspec create mode 100644 tools/env-vars-generator/protobuf/csharp/compatibility_tests/v3.0.0/protos/csharp/protos/unittest_issues.proto create mode 100644 tools/env-vars-generator/protobuf/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/ByteStringTest.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Collections/RepeatedFieldTest.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/TestProtos/ForeignMessagePartial.cs create mode 100755 tools/env-vars-generator/protobuf/csharp/generate_protos.sh create mode 100644 tools/env-vars-generator/protobuf/csharp/protos/old_extensions2.proto create mode 100644 tools/env-vars-generator/protobuf/csharp/protos/unittest.proto create mode 100644 tools/env-vars-generator/protobuf/csharp/protos/unittest_import_proto3.proto create mode 100644 tools/env-vars-generator/protobuf/csharp/protos/unittest_import_public_proto3.proto create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Benchmarks/Google.Protobuf.Benchmarks.csproj create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Benchmarks/ParseMessagesBenchmark.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Benchmarks/WriteMessagesBenchmark.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test.TestProtos/OldExtensions2.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test.TestProtos/Unittest.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssue6936A.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/Buffers/ArrayBufferWriter.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/Compatibility/StreamExtensionsTest.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/Proto3OptionalTest.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/SampleMessages.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Collections/RepeatedField.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Compatibility/UnconditionalSuppressMessageAttribute.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/LimitedInputStream.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/ParserInternalState.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/Descriptor.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/DescriptorPool.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/ExtensionAccessor.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/IDescriptor.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/IFieldAccessor.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/SegmentedBufferHelper.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/UnknownField.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/WellKnownTypes/AnyPartial.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs create mode 100644 tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/WellKnownTypes/TimeExtensions.cs create mode 100644 tools/env-vars-generator/protobuf/examples/ListPeople.java create mode 100644 tools/env-vars-generator/protobuf/examples/list_people.cc create mode 100755 tools/env-vars-generator/protobuf/fix_permissions.sh create mode 100644 tools/env-vars-generator/protobuf/global.json create mode 100644 tools/env-vars-generator/protobuf/java/core/pom.xml create mode 100644 tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/BinaryReader.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/BlockingRpcChannel.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/CodedOutputStreamWriter.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/ExtensionLite.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/GeneratedMessage.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/GeneratedMessageInfoFactory.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/LazyField.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/MapFieldSchemaLite.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/Reader.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/SchemaFactory.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/TextFormatParseLocation.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLiteSchema.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/UnsafeByteOperations.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/ParserLiteTest.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/ParserTest.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/Proto3SchemaTest.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/TestUtil.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/WireFormatTest.java create mode 100644 tools/env-vars-generator/protobuf/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto create mode 100644 tools/env-vars-generator/protobuf/java/core/src/test/proto/com/google/protobuf/map_for_proto2_test.proto create mode 100644 tools/env-vars-generator/protobuf/java/core/src/test/proto/com/google/protobuf/nested_extension.proto create mode 100644 tools/env-vars-generator/protobuf/java/core/src/test/proto/com/google/protobuf/test_check_utf8_size.proto create mode 100644 tools/env-vars-generator/protobuf/java/internal/BUILD create mode 100644 tools/env-vars-generator/protobuf/java/kotlin-lite/lite.awk create mode 100644 tools/env-vars-generator/protobuf/java/kotlin-lite/src/main/kotlin/com/google/protobuf/ExtendableMessageLiteExtensions.kt create mode 100644 tools/env-vars-generator/protobuf/java/kotlin-lite/src/test/kotlin/com/google/protobuf/ExtendableMessageLiteExtensionsTest.kt create mode 100644 tools/env-vars-generator/protobuf/java/kotlin/BUILD create mode 100644 tools/env-vars-generator/protobuf/java/kotlin/generate-test-sources-build.xml create mode 100644 tools/env-vars-generator/protobuf/java/kotlin/pom_template.xml create mode 100644 tools/env-vars-generator/protobuf/java/kotlin/src/main/kotlin/com/google/protobuf/ExtensionList.kt create mode 100644 tools/env-vars-generator/protobuf/java/kotlin/src/test/kotlin/com/google/protobuf/ExtensionListTest.kt create mode 100644 tools/env-vars-generator/protobuf/java/kotlin/src/test/proto/com/google/protobuf/example_extensible_message.proto create mode 100644 tools/env-vars-generator/protobuf/java/lite/generate-sources-build.xml create mode 100644 tools/env-vars-generator/protobuf/java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java create mode 100644 tools/env-vars-generator/protobuf/js/binary/arith_test.js create mode 100644 tools/env-vars-generator/protobuf/js/binary/encoder.js create mode 100644 tools/env-vars-generator/protobuf/js/binary/proto_test.js create mode 100644 tools/env-vars-generator/protobuf/js/commonjs/export.js create mode 100644 tools/env-vars-generator/protobuf/js/compatibility_tests/v3.0.0/commonjs/rewrite_tests_for_commonjs.js create mode 100644 tools/env-vars-generator/protobuf/js/compatibility_tests/v3.0.0/commonjs/test7/test7.proto create mode 100644 tools/env-vars-generator/protobuf/js/compatibility_tests/v3.1.0/data.proto create mode 100644 tools/env-vars-generator/protobuf/js/compatibility_tests/v3.1.0/message_test.js create mode 100644 tools/env-vars-generator/protobuf/js/compatibility_tests/v3.1.0/proto3_test.js create mode 100644 tools/env-vars-generator/protobuf/js/compatibility_tests/v3.1.0/test.proto create mode 100644 tools/env-vars-generator/protobuf/js/compatibility_tests/v3.1.0/testempty.proto create mode 100644 tools/env-vars-generator/protobuf/js/debug_test.js create mode 100644 tools/env-vars-generator/protobuf/js/experimental/benchmarks/code_size/apps_jspb/all_types_proto3.js create mode 100644 tools/env-vars-generator/protobuf/js/experimental/benchmarks/code_size/apps_jspb/popular_types_proto3.js create mode 100644 tools/env-vars-generator/protobuf/js/experimental/benchmarks/code_size/code_size_base.js create mode 100644 tools/env-vars-generator/protobuf/js/experimental/benchmarks/code_size/kernel/popular_types.js create mode 100644 tools/env-vars-generator/protobuf/js/experimental/runtime/bytestring.js create mode 100644 tools/env-vars-generator/protobuf/js/experimental/runtime/int64.js create mode 100644 tools/env-vars-generator/protobuf/js/experimental/runtime/internal/checks.js create mode 100644 tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/bool_test_pairs.js create mode 100644 tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/conformance/test_all_types_proto2.js create mode 100644 tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/indexer_test.js create mode 100644 tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/internal_message.js create mode 100644 tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/message_set_test.js create mode 100644 tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/packed_sint32_test_pairs.js create mode 100644 tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/storage.js create mode 100644 tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/textencoding.js create mode 100644 tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/textencoding_test.js create mode 100644 tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/typed_arrays_test.js create mode 100644 tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/uint8arrays.js create mode 100644 tools/env-vars-generator/protobuf/js/gulpfile.js create mode 100644 tools/env-vars-generator/protobuf/js/maps_test.js create mode 100644 tools/env-vars-generator/protobuf/js/message_test.js create mode 100644 tools/env-vars-generator/protobuf/js/package.json create mode 100644 tools/env-vars-generator/protobuf/js/proto3_test.js create mode 100644 tools/env-vars-generator/protobuf/js/test10.proto create mode 100644 tools/env-vars-generator/protobuf/js/test12.proto create mode 100644 tools/env-vars-generator/protobuf/kokoro/docs/python.cfg create mode 100644 tools/env-vars-generator/protobuf/kokoro/linux/32-bit/Dockerfile create mode 100755 tools/env-vars-generator/protobuf/kokoro/linux/32-bit/build.sh create mode 100755 tools/env-vars-generator/protobuf/kokoro/linux/aarch64/protoc_crosscompile_aarch64.sh create mode 100755 tools/env-vars-generator/protobuf/kokoro/linux/aarch64/test_cpp_aarch64.sh create mode 100755 tools/env-vars-generator/protobuf/kokoro/linux/aarch64/test_ruby_aarch64.sh create mode 100644 tools/env-vars-generator/protobuf/kokoro/linux/aarch64/testimage_protobuf_php_arm64v8/Dockerfile create mode 100755 tools/env-vars-generator/protobuf/kokoro/linux/benchmark/run.sh create mode 100644 tools/env-vars-generator/protobuf/kokoro/linux/cpp_distcheck/continuous.cfg create mode 100644 tools/env-vars-generator/protobuf/kokoro/linux/cpp_tcmalloc/continuous.cfg create mode 100644 tools/env-vars-generator/protobuf/kokoro/linux/cpp_tcmalloc/presubmit.cfg create mode 100644 tools/env-vars-generator/protobuf/kokoro/linux/csharp/continuous.cfg create mode 100644 tools/env-vars-generator/protobuf/kokoro/linux/dockerfile/test/python38/Dockerfile create mode 100644 tools/env-vars-generator/protobuf/kokoro/linux/dockerfile/test/python39/Dockerfile create mode 100644 tools/env-vars-generator/protobuf/kokoro/linux/java_linkage_monitor/continuous.cfg create mode 100644 tools/env-vars-generator/protobuf/kokoro/linux/jruby92/continuous.cfg create mode 100644 tools/env-vars-generator/protobuf/kokoro/linux/python27/continuous.cfg create mode 100755 tools/env-vars-generator/protobuf/kokoro/linux/python27_cpp/build.sh create mode 100644 tools/env-vars-generator/protobuf/kokoro/linux/python27_cpp/presubmit.cfg create mode 100755 tools/env-vars-generator/protobuf/kokoro/linux/python35/build.sh create mode 100644 tools/env-vars-generator/protobuf/kokoro/linux/python35/presubmit.cfg create mode 100755 tools/env-vars-generator/protobuf/kokoro/linux/python35_cpp/build.sh create mode 100755 tools/env-vars-generator/protobuf/kokoro/linux/python38/build.sh create mode 100755 tools/env-vars-generator/protobuf/kokoro/linux/python38_cpp/build.sh create mode 100644 tools/env-vars-generator/protobuf/kokoro/linux/python39_cpp/presubmit.cfg create mode 100644 tools/env-vars-generator/protobuf/kokoro/linux/python_cpp/continuous.cfg create mode 100755 tools/env-vars-generator/protobuf/kokoro/linux/ruby26/build.sh create mode 100755 tools/env-vars-generator/protobuf/kokoro/macos/objectivec_cocoapods_integration/build.sh create mode 100644 tools/env-vars-generator/protobuf/kokoro/macos/objectivec_ios_debug/continuous.cfg create mode 100755 tools/env-vars-generator/protobuf/kokoro/macos/php7.0_mac/build.sh create mode 100644 tools/env-vars-generator/protobuf/kokoro/macos/php7.0_mac/presubmit.cfg create mode 100644 tools/env-vars-generator/protobuf/kokoro/macos/php7.3_mac/continuous.cfg create mode 100644 tools/env-vars-generator/protobuf/kokoro/macos/php7.3_mac/presubmit.cfg create mode 100755 tools/env-vars-generator/protobuf/kokoro/macos/prepare_build_macos_rc create mode 100755 tools/env-vars-generator/protobuf/kokoro/macos/python/build.sh create mode 100644 tools/env-vars-generator/protobuf/kokoro/macos/python/presubmit.cfg create mode 100644 tools/env-vars-generator/protobuf/kokoro/macos/ruby26/continuous.cfg create mode 100755 tools/env-vars-generator/protobuf/kokoro/macos/ruby27/build.sh create mode 100644 tools/env-vars-generator/protobuf/kokoro/macos/ruby30/continuous.cfg create mode 100644 tools/env-vars-generator/protobuf/kokoro/release/csharp/windows/build_nuget.bat create mode 100644 tools/env-vars-generator/protobuf/kokoro/release/python/linux/continuous.cfg create mode 100644 tools/env-vars-generator/protobuf/kokoro/release/python/macos/config.sh create mode 100644 tools/env-vars-generator/protobuf/kokoro/release/python/windows/continuous.cfg create mode 100755 tools/env-vars-generator/protobuf/kokoro/release/ruby/linux/ruby/ruby_build_environment.sh create mode 100644 tools/env-vars-generator/protobuf/m4/acx_check_suncc.m4 create mode 100644 tools/env-vars-generator/protobuf/m4/ax_prog_cxx_for_build.m4 create mode 100644 tools/env-vars-generator/protobuf/m4/ax_pthread.m4 create mode 100644 tools/env-vars-generator/protobuf/objectivec/.gitignore create mode 100755 tools/env-vars-generator/protobuf/objectivec/DevTools/pddm.py create mode 100644 tools/env-vars-generator/protobuf/objectivec/GPBAny.pbobjc.h create mode 100644 tools/env-vars-generator/protobuf/objectivec/GPBCodedInputStream.h create mode 100644 tools/env-vars-generator/protobuf/objectivec/GPBDuration.pbobjc.h create mode 100644 tools/env-vars-generator/protobuf/objectivec/GPBEmpty.pbobjc.m create mode 100644 tools/env-vars-generator/protobuf/objectivec/GPBMessage_PackagePrivate.h create mode 100644 tools/env-vars-generator/protobuf/objectivec/GPBRootObject.m create mode 100644 tools/env-vars-generator/protobuf/objectivec/GPBRuntimeTypes.h create mode 100644 tools/env-vars-generator/protobuf/objectivec/GPBWellKnownTypes.h create mode 100644 tools/env-vars-generator/protobuf/objectivec/GPBWrappers.pbobjc.m create mode 100644 tools/env-vars-generator/protobuf/objectivec/ProtocolBuffers_OSX.xcodeproj/project.xcworkspace/contents.xcworkspacedata create mode 100644 tools/env-vars-generator/protobuf/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme create mode 100644 tools/env-vars-generator/protobuf/objectivec/ProtocolBuffers_tvOS.xcodeproj/project.pbxproj create mode 100644 tools/env-vars-generator/protobuf/objectivec/ProtocolBuffers_tvOS.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings create mode 100644 tools/env-vars-generator/protobuf/objectivec/Tests/CocoaPods/OSXCocoaPodsTester/OSXCocoaPodsTester.xcodeproj/project.pbxproj create mode 100644 tools/env-vars-generator/protobuf/objectivec/Tests/CocoaPods/OSXCocoaPodsTester/OSXCocoaPodsTester/AppDelegate.h create mode 100644 tools/env-vars-generator/protobuf/objectivec/Tests/CocoaPods/OSXCocoaPodsTester/OSXCocoaPodsTester/AppDelegate.m create mode 100644 tools/env-vars-generator/protobuf/objectivec/Tests/CocoaPods/iOSCocoaPodsTester/Podfile-static create mode 100644 tools/env-vars-generator/protobuf/objectivec/Tests/CocoaPods/iOSCocoaPodsTester/iOSCocoaPodsTester.xcodeproj/project.pbxproj create mode 100644 tools/env-vars-generator/protobuf/objectivec/Tests/GPBCompileTest07.m create mode 100644 tools/env-vars-generator/protobuf/objectivec/Tests/GPBMessageTests+ClassNames.m create mode 100644 tools/env-vars-generator/protobuf/objectivec/Tests/GPBSwiftTests.swift create mode 100644 tools/env-vars-generator/protobuf/objectivec/Tests/GPBWellKnownTypesTest.m create mode 100644 tools/env-vars-generator/protobuf/objectivec/Tests/golden_message create mode 100644 tools/env-vars-generator/protobuf/objectivec/Tests/text_format_extensions_unittest_data.txt create mode 100644 tools/env-vars-generator/protobuf/objectivec/Tests/text_format_map_unittest_data.txt create mode 100644 tools/env-vars-generator/protobuf/objectivec/Tests/unittest_extension_chain_d.proto create mode 100644 tools/env-vars-generator/protobuf/objectivec/Tests/unittest_extension_chain_f.proto create mode 100644 tools/env-vars-generator/protobuf/objectivec/Tests/unittest_objc_options.proto create mode 100644 tools/env-vars-generator/protobuf/objectivec/Tests/unittest_runtime_proto2.proto create mode 100644 tools/env-vars-generator/protobuf/php/ext/google/protobuf/arena.c create mode 100644 tools/env-vars-generator/protobuf/php/ext/google/protobuf/protobuf.h create mode 100644 tools/env-vars-generator/protobuf/php/src/GPBMetadata/Google/Protobuf/Any.php create mode 100644 tools/env-vars-generator/protobuf/php/src/GPBMetadata/Google/Protobuf/Struct.php create mode 100644 tools/env-vars-generator/protobuf/php/src/Google/Protobuf/GPBEmpty.php create mode 100644 tools/env-vars-generator/protobuf/php/src/Google/Protobuf/Int32Value.php create mode 100644 tools/env-vars-generator/protobuf/php/src/Google/Protobuf/Internal/DescriptorProto/ReservedRange.php create mode 100644 tools/env-vars-generator/protobuf/php/src/Google/Protobuf/Internal/EnumValueOptions.php create mode 100644 tools/env-vars-generator/protobuf/php/src/Google/Protobuf/Internal/ExtensionRangeOptions.php create mode 100644 tools/env-vars-generator/protobuf/php/src/Google/Protobuf/Internal/FieldDescriptorProto/Type.php create mode 100644 tools/env-vars-generator/protobuf/php/src/Google/Protobuf/Internal/FieldDescriptorProto_Type.php create mode 100644 tools/env-vars-generator/protobuf/php/src/Google/Protobuf/Internal/FileDescriptorSet.php create mode 100644 tools/env-vars-generator/protobuf/php/src/Google/Protobuf/Internal/FileOptions/OptimizeMode.php create mode 100644 tools/env-vars-generator/protobuf/php/src/Google/Protobuf/Internal/FileOptions_OptimizeMode.php create mode 100644 tools/env-vars-generator/protobuf/php/src/Google/Protobuf/Internal/GetPublicDescriptorTrait.php create mode 100644 tools/env-vars-generator/protobuf/php/src/Google/Protobuf/Internal/HasPublicDescriptorTrait.php create mode 100644 tools/env-vars-generator/protobuf/php/src/Google/Protobuf/Internal/OneofDescriptor.php create mode 100644 tools/env-vars-generator/protobuf/php/src/Google/Protobuf/Internal/OneofField.php create mode 100644 tools/env-vars-generator/protobuf/php/src/Google/Protobuf/Internal/RepeatedFieldIter.php create mode 100644 tools/env-vars-generator/protobuf/php/src/Google/Protobuf/Internal/SourceCodeInfo_Location.php create mode 100644 tools/env-vars-generator/protobuf/php/src/Google/Protobuf/Internal/UninterpretedOption/NamePart.php create mode 100644 tools/env-vars-generator/protobuf/php/src/Google/Protobuf/Syntax.php create mode 100644 tools/env-vars-generator/protobuf/php/src/phpdoc.dist.xml create mode 100644 tools/env-vars-generator/protobuf/php/tests/GeneratedServiceTest.php create mode 100644 tools/env-vars-generator/protobuf/php/tests/proto/empty/echo.proto create mode 100644 tools/env-vars-generator/protobuf/php/tests/proto/test_reserved_enum_value_lower.proto create mode 100644 tools/env-vars-generator/protobuf/php/tests/proto/test_wrapper_type_setters.proto create mode 100644 tools/env-vars-generator/protobuf/php/tests/test_base.php create mode 100644 tools/env-vars-generator/protobuf/php/tests/valgrind.supp create mode 100644 tools/env-vars-generator/protobuf/protobuf.bzl create mode 100644 tools/env-vars-generator/protobuf/protobuf_version.bzl create mode 100644 tools/env-vars-generator/protobuf/protoc-artifacts/README.md create mode 100755 tools/env-vars-generator/protobuf/protoc-artifacts/build-protoc.sh create mode 100644 tools/env-vars-generator/protobuf/protoc-artifacts/pom.xml create mode 100644 tools/env-vars-generator/protobuf/python/docs/conf.py create mode 100644 tools/env-vars-generator/protobuf/python/docs/google/protobuf/descriptor_pb2.rst create mode 100644 tools/env-vars-generator/protobuf/python/docs/google/protobuf/field_mask_pb2.rst create mode 100644 tools/env-vars-generator/protobuf/python/docs/google/protobuf/proto_builder.rst create mode 100644 tools/env-vars-generator/protobuf/python/docs/google/protobuf/struct_pb2.rst create mode 100644 tools/env-vars-generator/protobuf/python/google/protobuf/internal/decoder.py create mode 100644 tools/env-vars-generator/protobuf/python/google/protobuf/internal/factory_test1.proto create mode 100644 tools/env-vars-generator/protobuf/python/google/protobuf/internal/python_protobuf.cc create mode 100644 tools/env-vars-generator/protobuf/python/google/protobuf/internal/text_encoding_test.py create mode 100644 tools/env-vars-generator/protobuf/python/google/protobuf/pyext/descriptor_database.cc create mode 100644 tools/env-vars-generator/protobuf/python/google/protobuf/pyext/descriptor_pool.h create mode 100644 tools/env-vars-generator/protobuf/python/google/protobuf/pyext/extension_dict.cc create mode 100644 tools/env-vars-generator/protobuf/python/google/protobuf/pyext/extension_dict.h create mode 100644 tools/env-vars-generator/protobuf/python/google/protobuf/pyext/map_container.cc create mode 100644 tools/env-vars-generator/protobuf/python/google/protobuf/pyext/map_container.h create mode 100644 tools/env-vars-generator/protobuf/python/google/protobuf/pyext/message_factory.h create mode 100644 tools/env-vars-generator/protobuf/python/google/protobuf/pyext/message_module.cc create mode 100644 tools/env-vars-generator/protobuf/python/google/protobuf/pyext/repeated_composite_container.cc create mode 100644 tools/env-vars-generator/protobuf/python/google/protobuf/pyext/repeated_scalar_container.cc create mode 100644 tools/env-vars-generator/protobuf/python/google/protobuf/pyext/unknown_fields.h create mode 100644 tools/env-vars-generator/protobuf/python/google/protobuf/symbol_database.py create mode 100644 tools/env-vars-generator/protobuf/python/google/protobuf/text_format.py create mode 100755 tools/env-vars-generator/protobuf/python/stubout.py create mode 100755 tools/env-vars-generator/protobuf/ruby/compatibility_tests/v3.0.0/tests/repeated_field_test.rb create mode 100644 tools/env-vars-generator/protobuf/ruby/ext/google/protobuf_c/map.c create mode 100644 tools/env-vars-generator/protobuf/ruby/ext/google/protobuf_c/map.h create mode 100644 tools/env-vars-generator/protobuf/ruby/ext/google/protobuf_c/protobuf.h create mode 100644 tools/env-vars-generator/protobuf/ruby/tests/common_tests.rb create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/any_test.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/api.pb.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/arenastring_unittest.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/command_line_interface.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/cpp/cpp_message_field.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/cpp/cpp_string_field.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/csharp/csharp_enum.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/csharp/csharp_field_base.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/csharp/csharp_generator.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/csharp/csharp_generator.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/csharp/csharp_message_field.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/csharp/csharp_source_generator_base.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/java/java_extension.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/java/java_generator_factory.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/java/java_message_builder_lite.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/java/java_primitive_field_lite.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/java/java_string_field_lite.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/objectivec/objectivec_extension.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/objectivec/objectivec_generator.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/objectivec/objectivec_helpers.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/plugin.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/plugin.pb.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/python/python_plugin_unittest.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_code_proto2_pb.rb create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_pb.rb create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/generated_enum_util.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/generated_enum_util.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/generated_message_tctable_impl.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/has_bits.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/io/package_info.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/io/strtod.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/io/zero_copy_stream.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/io/zero_copy_stream_impl_lite.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/io/zero_copy_stream_impl_lite.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/lite_arena_unittest.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/map_lite_test_util.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/map_lite_unittest.proto create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/map_test_util.inc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/message_unittest.inc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/metadata.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/reflection_ops_unittest.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/repeated_field_reflection_unittest.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/repeated_ptr_field.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/stubs/common.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/stubs/int128_unittest.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/stubs/map_util.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/stubs/platform_macros.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/stubs/status_test.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/stubs/stringprintf.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/stubs/substitute.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/testdata/bad_utf8_string create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/testdata/text_format_unittest_data_oneof_implemented.txt create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/unittest_custom_options.proto create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/unittest_import.proto create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/unittest_lazy_dependencies_custom_option.proto create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/unittest_lazy_dependencies_enum.proto create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/util/internal/default_value_objectwriter.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/util/internal/field_mask_utility.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/util/internal/json_stream_parser.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/util/internal/location_tracker.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/util/internal/structured_objectwriter.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/util/internal/testdata/default_value_test.proto create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/util/internal/utility.cc create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/util/time_util.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/util/type_resolver_util.h create mode 100644 tools/env-vars-generator/protobuf/src/google/protobuf/wire_format_lite.cc create mode 100755 tools/env-vars-generator/protobuf/tests.sh create mode 100644 tools/env-vars-generator/protobuf/third_party/benchmark/CONTRIBUTORS create mode 100644 tools/env-vars-generator/protobuf/third_party/benchmark/cmake/CXXFeatureCheck.cmake create mode 100644 tools/env-vars-generator/protobuf/third_party/benchmark/include/benchmark/benchmark_api.h create mode 100644 tools/env-vars-generator/protobuf/third_party/benchmark/src/complexity.h create mode 100644 tools/env-vars-generator/protobuf/third_party/benchmark/src/log.h create mode 100644 tools/env-vars-generator/protobuf/third_party/benchmark/src/timers.cc create mode 100644 tools/env-vars-generator/protobuf/third_party/benchmark/test/cxx03_test.cc create mode 100644 tools/env-vars-generator/protobuf/third_party/benchmark/test/filter_test.cc create mode 100644 tools/env-vars-generator/protobuf/third_party/benchmark/test/register_benchmark_test.cc create mode 100755 tools/env-vars-generator/protobuf/third_party/googletest/ci/env-linux.sh create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/ci/install-platformio.sh create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/configure.ac create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googlemock/configure.ac create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googlemock/docs/CookBook.md create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googlemock/include/gmock/gmock-generated-function-mockers.h.pump create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googlemock/msvc/2005/gmock.vcproj create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googlemock/msvc/2010/gmock_config.props create mode 100755 tools/env-vars-generator/protobuf/third_party/googletest/googlemock/scripts/fuse_gmock_files.py create mode 100755 tools/env-vars-generator/protobuf/third_party/googletest/googlemock/scripts/gmock_doctor.py create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googlemock/src/gmock-matchers.cc create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googlemock/src/gmock-spec-builders.cc create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googlemock/src/gmock.cc create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googlemock/test/gmock-cardinalities_test.cc create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googlemock/test/gmock-function-mocker_nc_test.py create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googlemock/test/gmock-more-actions_test.cc create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googlemock/test/gmock-port_test.cc create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googlemock/test/gmock_link_test.h create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googlemock/test/gmock_output_test_.cc create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googletest/codegear/gtest_main.cbproj create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googletest/include/gtest/gtest-matchers.h create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googletest/include/gtest/internal/gtest-param-util.h create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googletest/include/gtest/internal/gtest-type-util.h create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googletest/m4/gtest.m4 create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googletest/msvc/2010/gtest_prod_test-md.vcxproj.filters create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googletest/msvc/2010/gtest_unittest-md.vcxproj create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googletest/samples/prime_tables.h create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googletest/samples/sample2.h create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googletest/samples/sample3_unittest.cc create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googletest/samples/sample7_unittest.cc create mode 100755 tools/env-vars-generator/protobuf/third_party/googletest/googletest/scripts/fuse_gtest_files.py create mode 100755 tools/env-vars-generator/protobuf/third_party/googletest/googletest/scripts/pump.py create mode 100755 tools/env-vars-generator/protobuf/third_party/googletest/googletest/scripts/release_docs.py create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googletest/src/gtest-death-test.cc create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googletest/src/gtest-internal-inl.h create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googletest/test/gtest-typed-test2_test.cc create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googletest/test/gtest_list_output_unittest.py create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googletest/test/gtest_sole_header_test.cc create mode 100755 tools/env-vars-generator/protobuf/third_party/googletest/googletest/test/gtest_test_utils.py create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googletest/test/gtest_throw_on_failure_ex_test.cc create mode 100755 tools/env-vars-generator/protobuf/third_party/googletest/googletest/test/gtest_xml_outfiles_test.py create mode 100644 tools/env-vars-generator/protobuf/third_party/googletest/googletest/xcode/Samples/FrameworkSample/widget.h create mode 100644 tools/env-vars-generator/protobuf/third_party/utf8_range/BUILD create mode 100644 tools/env-vars-generator/protobuf/util/python/BUILD create mode 100644 tools/go-generator/cmd/generator/_protobuf/.bazelignore create mode 100644 tools/go-generator/cmd/generator/_protobuf/WORKSPACE create mode 100644 tools/go-generator/cmd/generator/_protobuf/appveyor.yml create mode 100644 tools/go-generator/cmd/generator/_protobuf/benchmarks/BUILD create mode 100644 tools/go-generator/cmd/generator/_protobuf/benchmarks/Makefile.am create mode 100644 tools/go-generator/cmd/generator/_protobuf/benchmarks/cpp/BUILD create mode 100644 tools/go-generator/cmd/generator/_protobuf/benchmarks/datasets/google_message1/proto2/BUILD create mode 100644 tools/go-generator/cmd/generator/_protobuf/benchmarks/datasets/google_message1/proto2/dataset.google_message1_proto2.pb create mode 100644 tools/go-generator/cmd/generator/_protobuf/benchmarks/datasets/google_message3/benchmark_message3_6.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/benchmarks/datasets/google_message4/benchmark_message4_2.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/benchmarks/python/py_benchmark.py create mode 100644 tools/go-generator/cmd/generator/_protobuf/benchmarks/util/protoc-gen-gogoproto.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/benchmarks/util/protoc-gen-proto2_to_proto3.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/cmake/extract_includes.bat.in create mode 100644 tools/go-generator/cmd/generator/_protobuf/cmake/protobuf.pc.cmake create mode 100644 tools/go-generator/cmd/generator/_protobuf/configure.ac create mode 100644 tools/go-generator/cmd/generator/_protobuf/conformance/conformance_cpp.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/conformance/conformance_test_main.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/conformance/failure_list_python_cpp.txt create mode 100644 tools/go-generator/cmd/generator/_protobuf/conformance/third_party/jsoncpp/json.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/compatibility_tests/v3.0.0/protos/csharp/protos/unittest_issues.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/compatibility_tests/v3.0.0/protos/src/google/protobuf/unittest_well_known_types.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Compatibility/TypeExtensionsTest.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/JsonParserTest.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Reflection/FieldAccessTest.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/DurationTest.cs create mode 100755 tools/go-generator/cmd/generator/_protobuf/csharp/compatibility_tests/v3.0.0/test.sh create mode 100755 tools/go-generator/cmd/generator/_protobuf/csharp/install_dotnet_sdk.ps1 create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/keys/Google.Protobuf.public.snk create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/keys/Google.Protobuf.snk create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/protos/unittest_import_proto3.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Benchmarks/BenchmarkDatasetConfig.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Benchmarks/WriteRawPrimitivesBenchmark.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test.TestProtos/MapUnittestProto3.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test.TestProtos/OldExtensions1.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssue6936C.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssues.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test.TestProtos/UnittestSelfreferentialOptions.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/ByteStringTest.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/DeprecatedMemberTest.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/FieldMaskTreeTest.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.Proto2.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/SampleNaNs.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/TestCornerCases.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/WellKnownTypes/DurationTest.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/WellKnownTypes/FieldMaskTest.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/ByteArray.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Collections/ProtobufEqualityComparers.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Compatibility/MethodInfoExtensions.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Extension.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/FieldCodec.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/InvalidProtocolBufferException.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Reflection/DescriptorPool.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Reflection/DescriptorUtil.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Reflection/IFieldAccessor.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/UnknownField.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/WriterInternalState.cs create mode 100644 tools/go-generator/cmd/generator/_protobuf/docs/jvm_aot.md create mode 100644 tools/go-generator/cmd/generator/_protobuf/docs/options.md create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/generate-test-sources-build.xml create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/BinaryReader.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/ByteBufferWriter.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/DescriptorMessageInfoFactory.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/ExtensionLite.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/FieldSet.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/LongArrayList.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/MessageSetSchema.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/NewInstanceSchemaFull.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/NioByteString.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/Parser.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/Protobuf.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/RawMessageInfo.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/SchemaFactory.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/TextFormatParseLocation.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/TypeRegistry.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/Utf8.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/AnyTest.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/ExperimentalTestDataProvider.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/LazyFieldLiteTest.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/PackedFieldTest.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/Proto2ExtensionLookupSchemaTest.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/Proto3SchemaTest.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/TestSchemas.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/TypeRegistryTest.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/test/proto/com/google/protobuf/nested_extension.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/test/proto/com/google/protobuf/nested_extension_lite.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/test/proto/com/google/protobuf/non_nested_extension.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/core/src/test/proto/com/google/protobuf/proto3_message_lite.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/kotlin-lite/lite.awk create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/kotlin/src/main/kotlin/com/google/protobuf/OnlyForUseByGeneratedProtoCode.kt create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/kotlin/src/test/kotlin/com/google/protobuf/DslMapTest.kt create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/pom.xml create mode 100644 tools/go-generator/cmd/generator/_protobuf/java/util/src/main/java/com/google/protobuf/util/Structs.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/js/commonjs/jasmine.json create mode 100644 tools/go-generator/cmd/generator/_protobuf/js/commonjs/test6/test6.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.0.0/commonjs/import_test.js create mode 100644 tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.0.0/message_test.js create mode 100644 tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.0.0/proto3_test.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.1.0/binary/proto_test.js create mode 100644 tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.1.0/message_test.js create mode 100644 tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.1.0/test3.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/js/data.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/js/experimental/benchmarks/code_size/apps_jspb/popular_types_proto3.js create mode 100644 tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/bytestring.js create mode 100644 tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/binary_storage_test.js create mode 100644 tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/indexer.js create mode 100644 tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/packed_double_test_pairs.js create mode 100644 tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/packed_float_test_pairs.js create mode 100644 tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/packed_int32_test_pairs.js create mode 100644 tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/packed_int64_test_pairs.js create mode 100644 tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/packed_sfixed64_test_pairs.js create mode 100644 tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/tag.js create mode 100644 tools/go-generator/cmd/generator/_protobuf/js/package.json create mode 100644 tools/go-generator/cmd/generator/_protobuf/js/test13.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/js/test2.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/js/test9.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/README.md create mode 100755 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/aarch64/dockcross_helpers/run_dockcross_manylinux2014_aarch64.sh create mode 100755 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/aarch64/test_php_aarch64.sh create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/bazel/continuous.cfg create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/cpp_aarch64/continuous.cfg create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/cpp_distcheck/continuous.cfg create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/csharp/continuous.cfg create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/dist_install/continuous.cfg create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/dockerfile/test/csharp/Dockerfile create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/dockerfile/test/javascript/Dockerfile create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/java_aarch64/presubmit.cfg create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/java_jdk7/presubmit.cfg create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/javascript/continuous.cfg create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/jruby92/presubmit.cfg create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/make_test_output.py create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/php80/presubmit.cfg create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python27_cpp/presubmit.cfg create mode 100755 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python310_cpp/build.sh create mode 100755 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python35/build.sh create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python35/presubmit.cfg create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python36_cpp/presubmit.cfg create mode 100755 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python37/build.sh create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python37_cpp/presubmit.cfg create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python38/presubmit.cfg create mode 100755 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python38_cpp/build.sh create mode 100755 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python39/build.sh create mode 100755 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python39_cpp/build.sh create mode 100755 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python_compatibility/build.sh create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/linux/ruby27/continuous.cfg create mode 100755 tools/go-generator/cmd/generator/_protobuf/kokoro/macos/cpp/build.sh create mode 100755 tools/go-generator/cmd/generator/_protobuf/kokoro/macos/objectivec_cocoapods_integration/build.sh create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/macos/objectivec_osx/continuous.cfg create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/macos/php7.0_mac/presubmit.cfg create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/release/csharp/windows/continuous.cfg create mode 100755 tools/go-generator/cmd/generator/_protobuf/kokoro/release/protoc/macos/build.sh create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/release/protoc/macos/release.cfg create mode 100755 tools/go-generator/cmd/generator/_protobuf/kokoro/release/python/linux/build_artifacts.sh create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/release/python/linux/config.sh create mode 100644 tools/go-generator/cmd/generator/_protobuf/kokoro/release/python/windows/presubmit.cfg create mode 100644 tools/go-generator/cmd/generator/_protobuf/m4/ax_prog_cxx_for_build.m4 create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/GPBEmpty.pbobjc.m create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/GPBProtocolBuffers.m create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/GPBProtocolBuffers_RuntimeSupport.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/GPBSourceContext.pbobjc.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/GPBType.pbobjc.m create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/GPBUnknownField.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/GPBUnknownFieldSet.m create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/GPBUnknownField_PackagePrivate.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/GPBWrappers.pbobjc.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/ProtocolBuffers_OSX.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/ProtocolBuffers_iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/ProtocolBuffers_tvOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/CocoaPods/OSXCocoaPodsTester/OSXCocoaPodsTester.xcodeproj/project.pbxproj create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/CocoaPods/iOSCocoaPodsTester/iOSCocoaPodsTester/Base.lproj/Main.storyboard create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/CocoaPods/iOSCocoaPodsTester/iOSCocoaPodsTester/main.m create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/GPBArrayTests.m create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/GPBCompileTest15.m create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/GPBCompileTest21.m create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/GPBDictionaryTests+UInt32.m create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/GPBDictionaryTests.pddm create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/UnitTests-Bridging-Header.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/text_format_extensions_unittest_data.txt create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/text_format_unittest_data.txt create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/unittest_extension_chain_d.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/objectivec/google/protobuf/Timestamp.pbobjc.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/ext/google/protobuf/array.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/ext/google/protobuf/config.m4 create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/ext/google/protobuf/names.c create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/ext/google/protobuf/wkt.inc create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/src/GPBMetadata/Google/Protobuf/Any.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/src/GPBMetadata/Google/Protobuf/Duration.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/src/GPBMetadata/Google/Protobuf/GPBEmpty.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/src/GPBMetadata/Google/Protobuf/Internal/Descriptor.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/BytesValue.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/DoubleValue.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Enum.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/EnumValue.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/EnumValueDescriptor.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/DescriptorProto/ExtensionRange.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/DescriptorProto/ReservedRange.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/EnumBuilderContext.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/EnumValueDescriptorProto.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/FieldDescriptorProto_Label.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/FieldOptions/CType.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/FieldOptions/JSType.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/GPBType.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/HasPublicDescriptorTrait.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/Message.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/MessageBuilderContext.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/OneofField.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/SourceCodeInfo/Location.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Syntax.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/tests/WrapperTypeSettersTest.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/tests/proto/test_import_descriptor_proto.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/tests/proto/test_php_namespace.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/tests/proto/test_reserved_message_upper.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/php/tests/test_base.php create mode 100644 tools/go-generator/cmd/generator/_protobuf/protobuf.pc.in create mode 100644 tools/go-generator/cmd/generator/_protobuf/protobuf_deps.bzl create mode 100644 tools/go-generator/cmd/generator/_protobuf/python/docs/conf.py create mode 100755 tools/go-generator/cmd/generator/_protobuf/python/docs/generate_docs.py create mode 100644 tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/internal/factory_test2.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/internal/import_test_package/__init__.py create mode 100644 tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/internal/json_format_test.py create mode 100644 tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/internal/service_reflection_test.py create mode 100644 tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/internal/symbol_database_test.py create mode 100644 tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/cpp_message.py create mode 100644 tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/descriptor_database.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/descriptor_pool.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/message_factory.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/repeated_composite_container.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/scoped_pyobject_ptr.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/python/protobuf_distutils/protobuf_distutils/generate_py_protobufs.py create mode 100755 tools/go-generator/cmd/generator/_protobuf/python/setup.py create mode 100755 tools/go-generator/cmd/generator/_protobuf/python/stubout.py create mode 100644 tools/go-generator/cmd/generator/_protobuf/python/tox.ini create mode 100644 tools/go-generator/cmd/generator/_protobuf/ruby/compatibility_tests/v3.0.0/README.md create mode 100755 tools/go-generator/cmd/generator/_protobuf/ruby/compatibility_tests/v3.0.0/tests/basic.rb create mode 100755 tools/go-generator/cmd/generator/_protobuf/ruby/compatibility_tests/v3.0.0/tests/repeated_field_test.rb create mode 100755 tools/go-generator/cmd/generator/_protobuf/ruby/compatibility_tests/v3.0.0/tests/stress.rb create mode 100644 tools/go-generator/cmd/generator/_protobuf/ruby/ext/google/protobuf_c/message.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/ruby/lib/google/protobuf/repeated_field.rb create mode 100755 tools/go-generator/cmd/generator/_protobuf/ruby/lib/google/protobuf/well_known_types.rb create mode 100644 tools/go-generator/cmd/generator/_protobuf/ruby/src/main/java/com/google/protobuf/jruby/RubyFieldDescriptor.java create mode 100644 tools/go-generator/cmd/generator/_protobuf/ruby/src/main/java/com/google/protobuf/jruby/RubyMap.java create mode 100755 tools/go-generator/cmd/generator/_protobuf/ruby/tests/encode_decode_test.rb create mode 100644 tools/go-generator/cmd/generator/_protobuf/ruby/tests/test_import.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/ruby/tests/test_ruby_package.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/Makefile.am create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/any.pb.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/any.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/arena.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/command_line_interface.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_message.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_message_field.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_names.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_string_field.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_string_field.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_test_large_enum_value.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_field_base.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_message_field.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_options.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_reflection_class.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_context.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_extension.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_generator.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_helpers.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_helpers.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_kotlin_generator.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_message_lite.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_string_field.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/ruby/ruby_generated_code_proto2_pb.rb create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_legacy.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/subprocess.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/inlined_string_field.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/io/io_win32.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/io/tokenizer.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/io/zero_copy_stream.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/io/zero_copy_stream.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/lite_arena_unittest.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/map_field.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/map_lite_test_util.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/map_test.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/proto3_arena_unittest.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/reflection_ops.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/repeated_ptr_field.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/repeated_ptr_field.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/source_context.pb.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/struct.pb.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/bytestream.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/bytestream.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/common_unittest.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/hash.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/map_util.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/mathutil.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/status_macros.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/status_test.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/template_util.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/testing/file.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/testing/googletest.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/testing/zcgunzip.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/type.pb.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/unittest.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/unittest_enormous_descriptor.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/unittest_mset_wire_format.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/unittest_no_generic_services.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/util/internal/json_escaping.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/util/internal/json_stream_parser_test.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/util/internal/protostream_objectsource.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/util/internal/testdata/field_mask.proto create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/util/message_differencer.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/util/message_differencer_unittest.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/util/time_util.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/wrappers.pb.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/wrappers.pb.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/benchmark/appveyor.yml create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/benchmark/cmake/AddCXXCompilerFlag.cmake create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/benchmark/cmake/GetGitVersion.cmake create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/benchmark/include/benchmark/reporter.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/benchmark/src/CMakeLists.txt create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/benchmark/src/commandlineflags.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/benchmark/src/counter.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/benchmark/src/log.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/benchmark/test/complexity_test.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/benchmark/test/user_counters_tabular_test.cc create mode 100755 tools/go-generator/cmd/generator/_protobuf/third_party/benchmark/tools/compare_bench.py create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/.travis.yml create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/Makefile.am create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/README.md create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/ci/install-platformio.sh create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googlemock/cmake/gmock.pc.in create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googlemock/include/gmock/gmock-generated-matchers.h.pump create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googlemock/include/gmock/internal/custom/gmock-generated-actions.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googlemock/msvc/2005/gmock.sln create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googlemock/msvc/2015/gmock_config.props create mode 100755 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googlemock/scripts/fuse_gmock_files.py create mode 100755 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googlemock/scripts/generator/cpp/__init__.py create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googlemock/src/gmock-cardinalities.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googlemock/src/gmock-spec-builders.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googlemock/test/gmock-pp_test.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googlemock/test/gmock_leak_test_.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/README.md create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/cmake/gtest_main.pc.in create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/codegear/gtest.cbproj create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/codegear/gtest_all.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/codegear/gtest_unittest.cbproj create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/docs/XcodeGuide.md create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/include/gtest/gtest-message.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/include/gtest/gtest-spi.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/include/gtest/gtest-typed-test.h create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/m4/acx_pthread.m4 create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/msvc/2010/gtest.vcxproj create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/msvc/2010/gtest_prod_test-md.vcxproj.filters create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/msvc/2010/gtest_prod_test.vcxproj create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/msvc/2010/gtest_unittest.vcxproj create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/msvc/2010/gtest_unittest.vcxproj.filters create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/samples/sample4_unittest.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/samples/sample8_unittest.cc create mode 100755 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/scripts/upload_gtest.py create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/src/gtest-death-test.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/src/gtest-matchers.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/src/gtest-typed-test.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/src/gtest_main.cc create mode 100755 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/test/googletest-env-var-test.py create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/test/googletest-json-output-unittest.py create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/test/googletest-param-test-invalid-name1-test.py create mode 100755 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/test/googletest-shuffle-test.py create mode 100755 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/test/googletest-throw-on-failure-test.py create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/test/gtest_list_output_unittest_.cc create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/googletest/googletest/xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/utf8_range/utf8_range.c create mode 100644 tools/go-generator/cmd/generator/_protobuf/third_party/zlib.BUILD create mode 100644 tools/go-generator/cmd/generator/_templates/options.go.tmpl create mode 100644 tools/go-generator/cmd/generator/_templates/testdata/config.yaml diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index 483fb63..d139d01 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -10,7 +10,7 @@ jobs: runs-on: ubuntu-20.04 steps: - name: Checkout repo - uses: actions/checkout@v2 + uses: actions/checkout@v4 - uses: bufbuild/buf-setup-action@v0.7.0 diff --git a/.gitmodules b/.gitmodules index 6d987bc..96d18f4 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,6 @@ -[submodule "tools/hypertrace/agent-config"] - path = tools/hypertrace/agent-config - url = git@github.com:hypertrace/agent-config.git +[submodule "tools/env-vars-generator/protobuf"] + path = tools/env-vars-generator/protobuf + url = https://github.com/protocolbuffers/protobuf.git +[submodule "tools/go-generator/cmd/generator/_protobuf"] + path = tools/go-generator/cmd/generator/_protobuf + url = https://github.com/protocolbuffers/protobuf.git diff --git a/ENV_VARS.md b/ENV_VARS.md index 0a0a621..89abf21 100644 --- a/ENV_VARS.md +++ b/ENV_VARS.md @@ -53,3 +53,26 @@ Agents can be configured using environment variables: | TA_METRICS_CONFIG_LOGGING_ENABLED | Set this flag to print metrics in logs | | TA_METRICS_CONFIG_LOGGING_FREQUENCY | Set the frequency at which metrics should be printed. Examples are '1s', '2m', '3h'. Default value is 30m | | TA_ENVIRONMENT | Represents the environment name of agent | +| TA_SERVICE_NAME | From HT config | +| TA_REPORTING_ENDPOINT | Represents the endpoint for reporting the traces For ZIPKIN reporter type use http://api.traceable.ai:9411/api/v2/spans For OTLP reporter type use http://api.traceable.ai:4317 | +| TA_REPORTING_SECURE | When `true`, connects to endpoints over TLS. | +| TA_REPORTING_TOKEN | User specific token to access Traceable API | +| TA_REPORTING_CERT_FILE | Certificate file containing the CA to verify the server's certificate. This is for private certificates. If this is set then `secure` above should also be set to `true`. | +| TA_REPORTING_METRIC_ENDPOINT | Represents the endpoint for reporting the metrics. For OTLP metric reporter type use http://api.traceable.ai:4317 | +| TA_REPORTING_ENABLE_GRPC_LOADBALANCING | When `true`, modifies grpc resolver to use dns instead of passthrough and configure round robin client side loadbalancing | +| TA_DATA_CAPTURE_HTTP_HEADERS_REQUEST | When `false` it disables the capture for the request in a client/request operation | +| TA_DATA_CAPTURE_HTTP_HEADERS_RESPONSE | When `false` it disables the capture for the response in a client/request operation | +| TA_DATA_CAPTURE_HTTP_BODY_REQUEST | When `false` it disables the capture for the request in a client/request operation | +| TA_DATA_CAPTURE_HTTP_BODY_RESPONSE | When `false` it disables the capture for the response in a client/request operation | +| TA_DATA_CAPTURE_RPC_METADATA_REQUEST | When `false` it disables the capture for the request in a client/request operation | +| TA_DATA_CAPTURE_RPC_METADATA_RESPONSE | When `false` it disables the capture for the response in a client/request operation | +| TA_DATA_CAPTURE_RPC_BODY_REQUEST | When `false` it disables the capture for the request in a client/request operation | +| TA_DATA_CAPTURE_RPC_BODY_RESPONSE | When `false` it disables the capture for the response in a client/request operation | +| TA_DATA_CAPTURE_BODY_MAX_SIZE_BYTES | Is the maximum size of captured body in bytes. Default should be 131_072 (128 KiB). | +| TA_DATA_CAPTURE_BODY_MAX_PROCESSING_SIZE_BYTES | Is maximum size of body being processed by filters in bytes. Default should be 1_048_576 (1MB). For uncompressed bodies we capture all bytes up to `body_max_processing_size_bytes` in memory and pass that through the filter. For compressed and GRPC bodies, if the size of the body is larger than this, we ignore it entirely, otherwise we decompress/decode the body and then pass it to the filter. | +| TA_DATA_CAPTURE_ALLOWED_CONTENT_TYPES | Array of allowed content type substrings to record default should be json, x-www-form-urlencoded ex: ["json"] will record any request bodies that have a content-type header that includes "json". The values should be separated by `,`. | +| TA_PROPAGATION_FORMATS | List the supported propagation formats e.g. `TA_PROPAGATION_FORMATS="B3,TRACECONTEXT"`. | +| TA_ENABLED | When `false`, disables the agent | +| TA_TELEMETRY_STARTUP_SPAN_ENABLED | When `true`, an internal span is created and exported when the agent is initialized and started. It's useful to denote when the application the agent is in started. | +| TA_TELEMETRY_METRICS_ENABLED | Whether to capture metrics or not. The metrics will be otel go metrics. See https://github.com/open-telemetry/opentelemetry-go/tree/main/metric | +| TA_GOAGENT_USE_CUSTOM_BSP | Use the custom batch_span_processor adapted from the one in opentelemetry go and supports some additional metrics | diff --git a/Makefile b/Makefile index 656c077..d6dc637 100644 --- a/Makefile +++ b/Makefile @@ -15,21 +15,21 @@ generate-proto: OUT_DIR="$(PWD)/gen/go" \ OPT_MODULE="github.com/Traceableai/agent-config/gen/go" \ ENV_PREFIX="TA_" \ - $(MAKE) -C ./tools/hypertrace/agent-config/tools/go-generator + $(MAKE) -C ./tools/go-generator @echo "Tidy generated modules." - @find $(PWD)/gen/go \( -name vendor -o -name '[._].*' -o -name node_modules \) -prune -o -name go.mod -print | sed 's:/go.mod::' | xargs -I {} bash -c 'cd {}; go mod tidy -go=1.19' + @find $(PWD)/gen/go \( -name vendor -o -name '[._].*' -o -name node_modules \) -prune -o -name go.mod -print | sed 's:/go.mod::' | xargs -I {} bash -c 'cd {}; go mod tidy -go=1.21' @# Run gen/go load sanity tests cd $(PWD)/gen/go && go test ./... generate-env-vars: ## Generates the ENV_VARS.md with all environment variables. - docker build -t hypertrace/agent-config/env-vars-generator tools/hypertrace/agent-config/tools/env-vars-generator + docker build -t tools/env-vars-generator tools/env-vars-generator touch $(PWD)/ENV_VARS.md # makes sure this is created as a file and not as a directory docker run \ -v $(PWD)/ENV_VARS.md:/usr/local/ENV_VARS.md \ -v $(PWD)/proto/ai/traceable/agent/config/v1/config.proto:/usr/local/config.proto \ - hypertrace/agent-config/env-vars-generator \ + tools/env-vars-generator \ -o "/usr/local/ENV_VARS.md" -p "TA_" \ /usr/local/config.proto diff --git a/gen/go/go.mod b/gen/go/go.mod index 87bb876..4f441ac 100644 --- a/gen/go/go.mod +++ b/gen/go/go.mod @@ -1,11 +1,11 @@ module github.com/Traceableai/agent-config/gen/go -go 1.19 +go 1.21 require ( github.com/ghodss/yaml v1.0.0 github.com/stretchr/testify v1.9.0 - google.golang.org/protobuf v1.34.2 + google.golang.org/protobuf v1.35.1 ) require ( diff --git a/gen/go/go.sum b/gen/go/go.sum index 540d8ec..6b29beb 100644 --- a/gen/go/go.sum +++ b/gen/go/go.sum @@ -3,13 +3,15 @@ github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= -google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= -google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v1.35.1 h1:m3LfL6/Ca+fqnjnlqQXNpFPABW1UD7mjh8KO2mKFytA= +google.golang.org/protobuf v1.35.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= diff --git a/gen/go/proto/v1/config.proto b/gen/go/proto/v1/config.proto index e3c9b87..ef42343 100644 --- a/gen/go/proto/v1/config.proto +++ b/gen/go/proto/v1/config.proto @@ -20,6 +20,64 @@ message AgentConfig { MetricsConfig metrics_config = 9; // represents the environment name of agent google.protobuf.StringValue environment = 10; + + // From HT config + google.protobuf.StringValue service_name = 11; + + // reporting holds the reporting settings for the agent + Reporting reporting = 12; + + // data_capture describes the data being captured by instrumentation + DataCapture data_capture = 13; + + // propagation_formats list the supported propagation formats + repeated PropagationFormat propagation_formats = 14; + + // when `false`, disables the agent + google.protobuf.BoolValue enabled = 15; + + // resource_attributes map define the static list of resources which is configured on the tracer + map resource_attributes = 16; + + // telemetry + Telemetry telemetry = 17; + + // Goagent specific config + GoAgent goagent = 18; + +} + +// Reporting covers the options related to the mechanics for sending data to the +// tracing server o collector. +message Reporting { + // endpoint represents the endpoint for reporting the traces + // For ZIPKIN reporter type use http://api.traceable.ai:9411/api/v2/spans + // For OTLP reporter type use http://api.traceable.ai:4317 + google.protobuf.StringValue endpoint = 1; + + // when `true`, connects to endpoints over TLS. + google.protobuf.BoolValue secure = 2; + + // user specific token to access Traceable API + google.protobuf.StringValue token = 3; + + // reporter type for traces. + TraceReporterType trace_reporter_type = 5; + + // Certificate file containing the CA to verify the server's certificate. + // This is for private certificates. + // If this is set then `secure` above should also be set to `true`. + google.protobuf.StringValue cert_file = 6; + + // metric_endpoint represents the endpoint for reporting the metrics. + // For OTLP metric reporter type use http://api.traceable.ai:4317 + google.protobuf.StringValue metric_endpoint = 7; + + // reporter type for metrics. + MetricReporterType metric_reporter_type = 8; + + // When `true`, modifies grpc resolver to use dns instead of passthrough and configure round robin client side loadbalancing + google.protobuf.BoolValue enable_grpc_loadbalancing = 9; } // Opa covers the options related to the mechanics for getting Open Policy Agent configuration file. @@ -101,6 +159,7 @@ message SamplingConfig { message Javaagent { // set this flag to export certificates configured in JKS to libtraceable for making HTTPS connection to TPA. google.protobuf.BoolValue import_jks_certs = 1; + repeated google.protobuf.StringValue filter_jar_paths = 2; } enum LogMode { @@ -182,3 +241,120 @@ message RateLimitConfig { // set the span type for rate limited spans SpanType span_type = 6; } + +// Message describes what message should be considered for certain DataCapture option +message Message { + // when `false` it disables the capture for the request in a client/request operation + google.protobuf.BoolValue request = 1; + + // when `false` it disables the capture for the response in a client/request operation + google.protobuf.BoolValue response = 2; +} + +// DataCapture describes the elements to be captured by the agent instrumentation +message DataCapture { + // http_headers enables/disables the capture of the request/response headers in HTTP + Message http_headers = 1; + + // http_body enables/disables the capture of the request/response body in HTTP + Message http_body = 2; + + // rpc_metadata enables/disables the capture of the request/response metadata in RPC + Message rpc_metadata = 3; + + // rpc_body enables/disables the capture of the request/response body in RPC + Message rpc_body = 4; + + // body_max_size_bytes is the maximum size of captured body in bytes. + // Default should be 131_072 (128 KiB). + google.protobuf.Int32Value body_max_size_bytes = 5; + + // body_max_processing_size_bytes is maximum size of body being processed by filters in bytes. + // Default should be 1_048_576 (1MB). + // + // For uncompressed bodies we capture all bytes up to `body_max_processing_size_bytes` + // in memory and pass that through the filter. + // For compressed and GRPC bodies, if the size of the body is larger than this, we ignore + // it entirely, otherwise we decompress/decode the body and then pass it to the filter. + google.protobuf.Int32Value body_max_processing_size_bytes = 6; + + // Array of allowed content type substrings to record + // default should be json, x-www-form-urlencoded + // ex: ["json"] will record any request bodies that have a content-type header that includes "json" + repeated google.protobuf.StringValue allowed_content_types = 10; +} + +// PropagationFormat represents the propagation formats supported by agents +enum PropagationFormat { + // B3 propagation format, agents should support both multi and single value formats + // see https://github.com/openzipkin/b3-propagation + B3 = 0; + + // W3C Propagation format + // see https://www.w3.org/TR/trace-context/ + TRACECONTEXT = 1; +} + +// TraceReporterType represents the reporting format for trace data. +enum TraceReporterType { + + // Default to none. Agent will use it's default reporting type + UNSPECIFIED = 0; + + // Zipkin protobuf reporting format. + // see https://github.com/openzipkin/zipkin-api + ZIPKIN = 1; + + // OpenTelemetry protobuf reporting format. + // see https://github.com/open-telemetry/opentelemetry-proto + OTLP = 2; + + // Logging reporting format + LOGGING = 3; + + // Disable trace reporting + NONE = 4; + + // OTLP over http + OTLP_HTTP = 5; +} + +// MetricReporterType represents the reporting format for metric data. +enum MetricReporterType { + + // Default to none. Agent will use it's default reporting type + METRIC_REPORTER_TYPE_UNSPECIFIED = 0; + + // OpenTelemetry protobuf reporting format. + // see https://github.com/open-telemetry/opentelemetry-proto + METRIC_REPORTER_TYPE_OTLP = 1; + + // Prometheus exposition format. + // see https://github.com/prometheus/docs/blob/main/content/docs/instrumenting/exposition_formats.md + METRIC_REPORTER_TYPE_PROMETHEUS = 2; + + // Logging reporting format + METRIC_REPORTER_TYPE_LOGGING = 3; + + // Disable metric reporting + METRIC_REPORTER_TYPE_NONE = 4; +} + +// GoAgent has the configs specific to goagent +message GoAgent { + // use the custom batch_span_processor adapted from the one in opentelemetry go + // and supports some additional metrics + google.protobuf.BoolValue use_custom_bsp = 1; +} + +// Telemetry has config for agent telemetry: traces and metrics on agent's +// performance and events. +message Telemetry { + // when `true`, an internal span is created and exported when the agent is initialized and started. + // It's useful to denote when the application the agent is in started. + google.protobuf.BoolValue startup_span_enabled = 1; + + // Whether to capture metrics or not. The metrics will be otel go metrics. + // See https://github.com/open-telemetry/opentelemetry-go/tree/main/metric + google.protobuf.BoolValue metrics_enabled = 2; +} diff --git a/gen/go/v1/config.pb.go b/gen/go/v1/config.pb.go index 30c077f..14ffea1 100644 --- a/gen/go/v1/config.pb.go +++ b/gen/go/v1/config.pb.go @@ -1,6 +1,6 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.34.1 +// protoc-gen-go v1.28.1 // protoc (unknown) // source: ai/traceable/agent/config/v1/config.proto @@ -186,18 +186,199 @@ func (SpanType) EnumDescriptor() ([]byte, []int) { return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{2} } +// PropagationFormat represents the propagation formats supported by agents +type PropagationFormat int32 + +const ( + // B3 propagation format, agents should support both multi and single value formats + // see https://github.com/openzipkin/b3-propagation + PropagationFormat_B3 PropagationFormat = 0 + // W3C Propagation format + // see https://www.w3.org/TR/trace-context/ + PropagationFormat_TRACECONTEXT PropagationFormat = 1 +) + +// Enum value maps for PropagationFormat. +var ( + PropagationFormat_name = map[int32]string{ + 0: "B3", + 1: "TRACECONTEXT", + } + PropagationFormat_value = map[string]int32{ + "B3": 0, + "TRACECONTEXT": 1, + } +) + +func (x PropagationFormat) Enum() *PropagationFormat { + p := new(PropagationFormat) + *p = x + return p +} + +func (x PropagationFormat) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (PropagationFormat) Descriptor() protoreflect.EnumDescriptor { + return file_ai_traceable_agent_config_v1_config_proto_enumTypes[3].Descriptor() +} + +func (PropagationFormat) Type() protoreflect.EnumType { + return &file_ai_traceable_agent_config_v1_config_proto_enumTypes[3] +} + +func (x PropagationFormat) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use PropagationFormat.Descriptor instead. +func (PropagationFormat) EnumDescriptor() ([]byte, []int) { + return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{3} +} + +// TraceReporterType represents the reporting format for trace data. +type TraceReporterType int32 + +const ( + // Default to none. Agent will use it's default reporting type + TraceReporterType_UNSPECIFIED TraceReporterType = 0 + // Zipkin protobuf reporting format. + // see https://github.com/openzipkin/zipkin-api + TraceReporterType_ZIPKIN TraceReporterType = 1 + // OpenTelemetry protobuf reporting format. + // see https://github.com/open-telemetry/opentelemetry-proto + TraceReporterType_OTLP TraceReporterType = 2 + // Logging reporting format + TraceReporterType_LOGGING TraceReporterType = 3 + // Disable trace reporting + TraceReporterType_NONE TraceReporterType = 4 + // OTLP over http + TraceReporterType_OTLP_HTTP TraceReporterType = 5 +) + +// Enum value maps for TraceReporterType. +var ( + TraceReporterType_name = map[int32]string{ + 0: "UNSPECIFIED", + 1: "ZIPKIN", + 2: "OTLP", + 3: "LOGGING", + 4: "NONE", + 5: "OTLP_HTTP", + } + TraceReporterType_value = map[string]int32{ + "UNSPECIFIED": 0, + "ZIPKIN": 1, + "OTLP": 2, + "LOGGING": 3, + "NONE": 4, + "OTLP_HTTP": 5, + } +) + +func (x TraceReporterType) Enum() *TraceReporterType { + p := new(TraceReporterType) + *p = x + return p +} + +func (x TraceReporterType) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (TraceReporterType) Descriptor() protoreflect.EnumDescriptor { + return file_ai_traceable_agent_config_v1_config_proto_enumTypes[4].Descriptor() +} + +func (TraceReporterType) Type() protoreflect.EnumType { + return &file_ai_traceable_agent_config_v1_config_proto_enumTypes[4] +} + +func (x TraceReporterType) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use TraceReporterType.Descriptor instead. +func (TraceReporterType) EnumDescriptor() ([]byte, []int) { + return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{4} +} + +// MetricReporterType represents the reporting format for metric data. +type MetricReporterType int32 + +const ( + // Default to none. Agent will use it's default reporting type + MetricReporterType_METRIC_REPORTER_TYPE_UNSPECIFIED MetricReporterType = 0 + // OpenTelemetry protobuf reporting format. + // see https://github.com/open-telemetry/opentelemetry-proto + MetricReporterType_METRIC_REPORTER_TYPE_OTLP MetricReporterType = 1 + // Prometheus exposition format. + // see https://github.com/prometheus/docs/blob/main/content/docs/instrumenting/exposition_formats.md + MetricReporterType_METRIC_REPORTER_TYPE_PROMETHEUS MetricReporterType = 2 + // Logging reporting format + MetricReporterType_METRIC_REPORTER_TYPE_LOGGING MetricReporterType = 3 + // Disable metric reporting + MetricReporterType_METRIC_REPORTER_TYPE_NONE MetricReporterType = 4 +) + +// Enum value maps for MetricReporterType. +var ( + MetricReporterType_name = map[int32]string{ + 0: "METRIC_REPORTER_TYPE_UNSPECIFIED", + 1: "METRIC_REPORTER_TYPE_OTLP", + 2: "METRIC_REPORTER_TYPE_PROMETHEUS", + 3: "METRIC_REPORTER_TYPE_LOGGING", + 4: "METRIC_REPORTER_TYPE_NONE", + } + MetricReporterType_value = map[string]int32{ + "METRIC_REPORTER_TYPE_UNSPECIFIED": 0, + "METRIC_REPORTER_TYPE_OTLP": 1, + "METRIC_REPORTER_TYPE_PROMETHEUS": 2, + "METRIC_REPORTER_TYPE_LOGGING": 3, + "METRIC_REPORTER_TYPE_NONE": 4, + } +) + +func (x MetricReporterType) Enum() *MetricReporterType { + p := new(MetricReporterType) + *p = x + return p +} + +func (x MetricReporterType) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (MetricReporterType) Descriptor() protoreflect.EnumDescriptor { + return file_ai_traceable_agent_config_v1_config_proto_enumTypes[5].Descriptor() +} + +func (MetricReporterType) Type() protoreflect.EnumType { + return &file_ai_traceable_agent_config_v1_config_proto_enumTypes[5] +} + +func (x MetricReporterType) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use MetricReporterType.Descriptor instead. +func (MetricReporterType) EnumDescriptor() ([]byte, []int) { + return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{5} +} + type AgentConfig struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - // Deprecated: Marked as deprecated in ai/traceable/agent/config/v1/config.proto. + // Deprecated: Do not use. Opa *Opa `protobuf:"bytes,1,opt,name=opa,proto3" json:"opa,omitempty"` BlockingConfig *BlockingConfig `protobuf:"bytes,2,opt,name=blocking_config,json=blockingConfig,proto3" json:"blocking_config,omitempty"` - // Deprecated: Marked as deprecated in ai/traceable/agent/config/v1/config.proto. + // Deprecated: Do not use. DebugLog *wrapperspb.BoolValue `protobuf:"bytes,3,opt,name=debug_log,json=debugLog,proto3" json:"debug_log,omitempty"` RemoteConfig *RemoteConfig `protobuf:"bytes,4,opt,name=remote_config,json=remoteConfig,proto3" json:"remote_config,omitempty"` - // Deprecated: Marked as deprecated in ai/traceable/agent/config/v1/config.proto. + // Deprecated: Do not use. ApiDiscovery *ApiDiscoveryConfig `protobuf:"bytes,5,opt,name=api_discovery,json=apiDiscovery,proto3" json:"api_discovery,omitempty"` Sampling *SamplingConfig `protobuf:"bytes,6,opt,name=sampling,proto3" json:"sampling,omitempty"` // javaagent has the configs specific to javaagent @@ -206,6 +387,22 @@ type AgentConfig struct { MetricsConfig *MetricsConfig `protobuf:"bytes,9,opt,name=metrics_config,json=metricsConfig,proto3" json:"metrics_config,omitempty"` // represents the environment name of agent Environment *wrapperspb.StringValue `protobuf:"bytes,10,opt,name=environment,proto3" json:"environment,omitempty"` + // From HT config + ServiceName *wrapperspb.StringValue `protobuf:"bytes,11,opt,name=service_name,json=serviceName,proto3" json:"service_name,omitempty"` + // reporting holds the reporting settings for the agent + Reporting *Reporting `protobuf:"bytes,12,opt,name=reporting,proto3" json:"reporting,omitempty"` + // data_capture describes the data being captured by instrumentation + DataCapture *DataCapture `protobuf:"bytes,13,opt,name=data_capture,json=dataCapture,proto3" json:"data_capture,omitempty"` + // propagation_formats list the supported propagation formats + PropagationFormats []PropagationFormat `protobuf:"varint,14,rep,packed,name=propagation_formats,json=propagationFormats,proto3,enum=ai.traceable.agent.config.v1.PropagationFormat" json:"propagation_formats,omitempty"` + // when `false`, disables the agent + Enabled *wrapperspb.BoolValue `protobuf:"bytes,15,opt,name=enabled,proto3" json:"enabled,omitempty"` + // resource_attributes map define the static list of resources which is configured on the tracer + ResourceAttributes map[string]string `protobuf:"bytes,16,rep,name=resource_attributes,json=resourceAttributes,proto3" json:"resource_attributes,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` + // telemetry + Telemetry *Telemetry `protobuf:"bytes,17,opt,name=telemetry,proto3" json:"telemetry,omitempty"` + // Goagent specific config + Goagent *GoAgent `protobuf:"bytes,18,opt,name=goagent,proto3" json:"goagent,omitempty"` } func (x *AgentConfig) Reset() { @@ -240,7 +437,7 @@ func (*AgentConfig) Descriptor() ([]byte, []int) { return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{0} } -// Deprecated: Marked as deprecated in ai/traceable/agent/config/v1/config.proto. +// Deprecated: Do not use. func (x *AgentConfig) GetOpa() *Opa { if x != nil { return x.Opa @@ -255,7 +452,7 @@ func (x *AgentConfig) GetBlockingConfig() *BlockingConfig { return nil } -// Deprecated: Marked as deprecated in ai/traceable/agent/config/v1/config.proto. +// Deprecated: Do not use. func (x *AgentConfig) GetDebugLog() *wrapperspb.BoolValue { if x != nil { return x.DebugLog @@ -270,7 +467,7 @@ func (x *AgentConfig) GetRemoteConfig() *RemoteConfig { return nil } -// Deprecated: Marked as deprecated in ai/traceable/agent/config/v1/config.proto. +// Deprecated: Do not use. func (x *AgentConfig) GetApiDiscovery() *ApiDiscoveryConfig { if x != nil { return x.ApiDiscovery @@ -313,6 +510,180 @@ func (x *AgentConfig) GetEnvironment() *wrapperspb.StringValue { return nil } +func (x *AgentConfig) GetServiceName() *wrapperspb.StringValue { + if x != nil { + return x.ServiceName + } + return nil +} + +func (x *AgentConfig) GetReporting() *Reporting { + if x != nil { + return x.Reporting + } + return nil +} + +func (x *AgentConfig) GetDataCapture() *DataCapture { + if x != nil { + return x.DataCapture + } + return nil +} + +func (x *AgentConfig) GetPropagationFormats() []PropagationFormat { + if x != nil { + return x.PropagationFormats + } + return nil +} + +func (x *AgentConfig) GetEnabled() *wrapperspb.BoolValue { + if x != nil { + return x.Enabled + } + return nil +} + +func (x *AgentConfig) GetResourceAttributes() map[string]string { + if x != nil { + return x.ResourceAttributes + } + return nil +} + +func (x *AgentConfig) GetTelemetry() *Telemetry { + if x != nil { + return x.Telemetry + } + return nil +} + +func (x *AgentConfig) GetGoagent() *GoAgent { + if x != nil { + return x.Goagent + } + return nil +} + +// Reporting covers the options related to the mechanics for sending data to the +// tracing server o collector. +type Reporting struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // endpoint represents the endpoint for reporting the traces + // For ZIPKIN reporter type use http://api.traceable.ai:9411/api/v2/spans + // For OTLP reporter type use http://api.traceable.ai:4317 + Endpoint *wrapperspb.StringValue `protobuf:"bytes,1,opt,name=endpoint,proto3" json:"endpoint,omitempty"` + // when `true`, connects to endpoints over TLS. + Secure *wrapperspb.BoolValue `protobuf:"bytes,2,opt,name=secure,proto3" json:"secure,omitempty"` + // user specific token to access Traceable API + Token *wrapperspb.StringValue `protobuf:"bytes,3,opt,name=token,proto3" json:"token,omitempty"` + // reporter type for traces. + TraceReporterType TraceReporterType `protobuf:"varint,5,opt,name=trace_reporter_type,json=traceReporterType,proto3,enum=ai.traceable.agent.config.v1.TraceReporterType" json:"trace_reporter_type,omitempty"` + // Certificate file containing the CA to verify the server's certificate. + // This is for private certificates. + // If this is set then `secure` above should also be set to `true`. + CertFile *wrapperspb.StringValue `protobuf:"bytes,6,opt,name=cert_file,json=certFile,proto3" json:"cert_file,omitempty"` + // metric_endpoint represents the endpoint for reporting the metrics. + // For OTLP metric reporter type use http://api.traceable.ai:4317 + MetricEndpoint *wrapperspb.StringValue `protobuf:"bytes,7,opt,name=metric_endpoint,json=metricEndpoint,proto3" json:"metric_endpoint,omitempty"` + // reporter type for metrics. + MetricReporterType MetricReporterType `protobuf:"varint,8,opt,name=metric_reporter_type,json=metricReporterType,proto3,enum=ai.traceable.agent.config.v1.MetricReporterType" json:"metric_reporter_type,omitempty"` + // When `true`, modifies grpc resolver to use dns instead of passthrough and configure round robin client side loadbalancing + EnableGrpcLoadbalancing *wrapperspb.BoolValue `protobuf:"bytes,9,opt,name=enable_grpc_loadbalancing,json=enableGrpcLoadbalancing,proto3" json:"enable_grpc_loadbalancing,omitempty"` +} + +func (x *Reporting) Reset() { + *x = Reporting{} + if protoimpl.UnsafeEnabled { + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Reporting) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Reporting) ProtoMessage() {} + +func (x *Reporting) ProtoReflect() protoreflect.Message { + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Reporting.ProtoReflect.Descriptor instead. +func (*Reporting) Descriptor() ([]byte, []int) { + return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{1} +} + +func (x *Reporting) GetEndpoint() *wrapperspb.StringValue { + if x != nil { + return x.Endpoint + } + return nil +} + +func (x *Reporting) GetSecure() *wrapperspb.BoolValue { + if x != nil { + return x.Secure + } + return nil +} + +func (x *Reporting) GetToken() *wrapperspb.StringValue { + if x != nil { + return x.Token + } + return nil +} + +func (x *Reporting) GetTraceReporterType() TraceReporterType { + if x != nil { + return x.TraceReporterType + } + return TraceReporterType_UNSPECIFIED +} + +func (x *Reporting) GetCertFile() *wrapperspb.StringValue { + if x != nil { + return x.CertFile + } + return nil +} + +func (x *Reporting) GetMetricEndpoint() *wrapperspb.StringValue { + if x != nil { + return x.MetricEndpoint + } + return nil +} + +func (x *Reporting) GetMetricReporterType() MetricReporterType { + if x != nil { + return x.MetricReporterType + } + return MetricReporterType_METRIC_REPORTER_TYPE_UNSPECIFIED +} + +func (x *Reporting) GetEnableGrpcLoadbalancing() *wrapperspb.BoolValue { + if x != nil { + return x.EnableGrpcLoadbalancing + } + return nil +} + // Opa covers the options related to the mechanics for getting Open Policy Agent configuration file. // The client should use secure and token option from reporting settings. type Opa struct { @@ -336,7 +707,7 @@ type Opa struct { func (x *Opa) Reset() { *x = Opa{} if protoimpl.UnsafeEnabled { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[1] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -349,7 +720,7 @@ func (x *Opa) String() string { func (*Opa) ProtoMessage() {} func (x *Opa) ProtoReflect() protoreflect.Message { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[1] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -362,7 +733,7 @@ func (x *Opa) ProtoReflect() protoreflect.Message { // Deprecated: Use Opa.ProtoReflect.Descriptor instead. func (*Opa) Descriptor() ([]byte, []int) { - return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{1} + return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{2} } func (x *Opa) GetEnabled() *wrapperspb.BoolValue { @@ -409,14 +780,14 @@ type BlockingConfig struct { Enabled *wrapperspb.BoolValue `protobuf:"bytes,1,opt,name=enabled,proto3" json:"enabled,omitempty"` // debug_log has moved to top level // - // Deprecated: Marked as deprecated in ai/traceable/agent/config/v1/config.proto. + // Deprecated: Do not use. DebugLog *wrapperspb.BoolValue `protobuf:"bytes,2,opt,name=debug_log,json=debugLog,proto3" json:"debug_log,omitempty"` Modsecurity *ModsecurityConfig `protobuf:"bytes,3,opt,name=modsecurity,proto3" json:"modsecurity,omitempty"` EvaluateBody *wrapperspb.BoolValue `protobuf:"bytes,4,opt,name=evaluate_body,json=evaluateBody,proto3" json:"evaluate_body,omitempty"` RegionBlocking *RegionBlockingConfig `protobuf:"bytes,5,opt,name=region_blocking,json=regionBlocking,proto3" json:"region_blocking,omitempty"` // remote_config has moved to top level // - // Deprecated: Marked as deprecated in ai/traceable/agent/config/v1/config.proto. + // Deprecated: Do not use. RemoteConfig *RemoteConfig `protobuf:"bytes,6,opt,name=remote_config,json=remoteConfig,proto3" json:"remote_config,omitempty"` // when `true`, blocking evaluation will be skipped for internal requests i.e. requests coming // from private IPs @@ -432,7 +803,7 @@ type BlockingConfig struct { func (x *BlockingConfig) Reset() { *x = BlockingConfig{} if protoimpl.UnsafeEnabled { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[2] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -445,7 +816,7 @@ func (x *BlockingConfig) String() string { func (*BlockingConfig) ProtoMessage() {} func (x *BlockingConfig) ProtoReflect() protoreflect.Message { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[2] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -458,7 +829,7 @@ func (x *BlockingConfig) ProtoReflect() protoreflect.Message { // Deprecated: Use BlockingConfig.ProtoReflect.Descriptor instead. func (*BlockingConfig) Descriptor() ([]byte, []int) { - return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{2} + return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{3} } func (x *BlockingConfig) GetEnabled() *wrapperspb.BoolValue { @@ -468,7 +839,7 @@ func (x *BlockingConfig) GetEnabled() *wrapperspb.BoolValue { return nil } -// Deprecated: Marked as deprecated in ai/traceable/agent/config/v1/config.proto. +// Deprecated: Do not use. func (x *BlockingConfig) GetDebugLog() *wrapperspb.BoolValue { if x != nil { return x.DebugLog @@ -497,7 +868,7 @@ func (x *BlockingConfig) GetRegionBlocking() *RegionBlockingConfig { return nil } -// Deprecated: Marked as deprecated in ai/traceable/agent/config/v1/config.proto. +// Deprecated: Do not use. func (x *BlockingConfig) GetRemoteConfig() *RemoteConfig { if x != nil { return x.RemoteConfig @@ -544,7 +915,7 @@ type ModsecurityConfig struct { func (x *ModsecurityConfig) Reset() { *x = ModsecurityConfig{} if protoimpl.UnsafeEnabled { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[3] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -557,7 +928,7 @@ func (x *ModsecurityConfig) String() string { func (*ModsecurityConfig) ProtoMessage() {} func (x *ModsecurityConfig) ProtoReflect() protoreflect.Message { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[3] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -570,7 +941,7 @@ func (x *ModsecurityConfig) ProtoReflect() protoreflect.Message { // Deprecated: Use ModsecurityConfig.ProtoReflect.Descriptor instead. func (*ModsecurityConfig) Descriptor() ([]byte, []int) { - return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{3} + return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{4} } func (x *ModsecurityConfig) GetEnabled() *wrapperspb.BoolValue { @@ -591,7 +962,7 @@ type RegionBlockingConfig struct { func (x *RegionBlockingConfig) Reset() { *x = RegionBlockingConfig{} if protoimpl.UnsafeEnabled { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[4] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -604,7 +975,7 @@ func (x *RegionBlockingConfig) String() string { func (*RegionBlockingConfig) ProtoMessage() {} func (x *RegionBlockingConfig) ProtoReflect() protoreflect.Message { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[4] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[5] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -617,7 +988,7 @@ func (x *RegionBlockingConfig) ProtoReflect() protoreflect.Message { // Deprecated: Use RegionBlockingConfig.ProtoReflect.Descriptor instead. func (*RegionBlockingConfig) Descriptor() ([]byte, []int) { - return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{4} + return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{5} } func (x *RegionBlockingConfig) GetEnabled() *wrapperspb.BoolValue { @@ -649,7 +1020,7 @@ type RemoteConfig struct { func (x *RemoteConfig) Reset() { *x = RemoteConfig{} if protoimpl.UnsafeEnabled { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[5] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -662,7 +1033,7 @@ func (x *RemoteConfig) String() string { func (*RemoteConfig) ProtoMessage() {} func (x *RemoteConfig) ProtoReflect() protoreflect.Message { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[5] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[6] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -675,7 +1046,7 @@ func (x *RemoteConfig) ProtoReflect() protoreflect.Message { // Deprecated: Use RemoteConfig.ProtoReflect.Descriptor instead. func (*RemoteConfig) Descriptor() ([]byte, []int) { - return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{5} + return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{6} } func (x *RemoteConfig) GetEnabled() *wrapperspb.BoolValue { @@ -731,7 +1102,7 @@ type ApiDiscoveryConfig struct { func (x *ApiDiscoveryConfig) Reset() { *x = ApiDiscoveryConfig{} if protoimpl.UnsafeEnabled { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[6] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -744,7 +1115,7 @@ func (x *ApiDiscoveryConfig) String() string { func (*ApiDiscoveryConfig) ProtoMessage() {} func (x *ApiDiscoveryConfig) ProtoReflect() protoreflect.Message { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[6] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[7] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -757,7 +1128,7 @@ func (x *ApiDiscoveryConfig) ProtoReflect() protoreflect.Message { // Deprecated: Use ApiDiscoveryConfig.ProtoReflect.Descriptor instead. func (*ApiDiscoveryConfig) Descriptor() ([]byte, []int) { - return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{6} + return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{7} } func (x *ApiDiscoveryConfig) GetEnabled() *wrapperspb.BoolValue { @@ -779,7 +1150,7 @@ type SamplingConfig struct { func (x *SamplingConfig) Reset() { *x = SamplingConfig{} if protoimpl.UnsafeEnabled { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[7] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -792,7 +1163,7 @@ func (x *SamplingConfig) String() string { func (*SamplingConfig) ProtoMessage() {} func (x *SamplingConfig) ProtoReflect() protoreflect.Message { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[7] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[8] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -805,7 +1176,7 @@ func (x *SamplingConfig) ProtoReflect() protoreflect.Message { // Deprecated: Use SamplingConfig.ProtoReflect.Descriptor instead. func (*SamplingConfig) Descriptor() ([]byte, []int) { - return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{7} + return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{8} } func (x *SamplingConfig) GetEnabled() *wrapperspb.BoolValue { @@ -828,13 +1199,14 @@ type Javaagent struct { unknownFields protoimpl.UnknownFields // set this flag to export certificates configured in JKS to libtraceable for making HTTPS connection to TPA. - ImportJksCerts *wrapperspb.BoolValue `protobuf:"bytes,1,opt,name=import_jks_certs,json=importJksCerts,proto3" json:"import_jks_certs,omitempty"` + ImportJksCerts *wrapperspb.BoolValue `protobuf:"bytes,1,opt,name=import_jks_certs,json=importJksCerts,proto3" json:"import_jks_certs,omitempty"` + FilterJarPaths []*wrapperspb.StringValue `protobuf:"bytes,2,rep,name=filter_jar_paths,json=filterJarPaths,proto3" json:"filter_jar_paths,omitempty"` } func (x *Javaagent) Reset() { *x = Javaagent{} if protoimpl.UnsafeEnabled { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[8] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -847,7 +1219,7 @@ func (x *Javaagent) String() string { func (*Javaagent) ProtoMessage() {} func (x *Javaagent) ProtoReflect() protoreflect.Message { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[8] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[9] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -860,7 +1232,7 @@ func (x *Javaagent) ProtoReflect() protoreflect.Message { // Deprecated: Use Javaagent.ProtoReflect.Descriptor instead. func (*Javaagent) Descriptor() ([]byte, []int) { - return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{8} + return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{9} } func (x *Javaagent) GetImportJksCerts() *wrapperspb.BoolValue { @@ -870,6 +1242,13 @@ func (x *Javaagent) GetImportJksCerts() *wrapperspb.BoolValue { return nil } +func (x *Javaagent) GetFilterJarPaths() []*wrapperspb.StringValue { + if x != nil { + return x.FilterJarPaths + } + return nil +} + type LogConfig struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -884,7 +1263,7 @@ type LogConfig struct { func (x *LogConfig) Reset() { *x = LogConfig{} if protoimpl.UnsafeEnabled { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[9] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[10] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -897,7 +1276,7 @@ func (x *LogConfig) String() string { func (*LogConfig) ProtoMessage() {} func (x *LogConfig) ProtoReflect() protoreflect.Message { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[9] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[10] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -910,7 +1289,7 @@ func (x *LogConfig) ProtoReflect() protoreflect.Message { // Deprecated: Use LogConfig.ProtoReflect.Descriptor instead. func (*LogConfig) Descriptor() ([]byte, []int) { - return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{9} + return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{10} } func (x *LogConfig) GetLogMode() LogMode { @@ -950,7 +1329,7 @@ type LogFileConfig struct { func (x *LogFileConfig) Reset() { *x = LogFileConfig{} if protoimpl.UnsafeEnabled { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[10] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -963,7 +1342,7 @@ func (x *LogFileConfig) String() string { func (*LogFileConfig) ProtoMessage() {} func (x *LogFileConfig) ProtoReflect() protoreflect.Message { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[10] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[11] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -976,7 +1355,7 @@ func (x *LogFileConfig) ProtoReflect() protoreflect.Message { // Deprecated: Use LogFileConfig.ProtoReflect.Descriptor instead. func (*LogFileConfig) Descriptor() ([]byte, []int) { - return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{10} + return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{11} } func (x *LogFileConfig) GetMaxFiles() *wrapperspb.Int32Value { @@ -1014,7 +1393,7 @@ type MetricsLogConfig struct { func (x *MetricsLogConfig) Reset() { *x = MetricsLogConfig{} if protoimpl.UnsafeEnabled { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[11] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1027,7 +1406,7 @@ func (x *MetricsLogConfig) String() string { func (*MetricsLogConfig) ProtoMessage() {} func (x *MetricsLogConfig) ProtoReflect() protoreflect.Message { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[11] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[12] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1040,7 +1419,7 @@ func (x *MetricsLogConfig) ProtoReflect() protoreflect.Message { // Deprecated: Use MetricsLogConfig.ProtoReflect.Descriptor instead. func (*MetricsLogConfig) Descriptor() ([]byte, []int) { - return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{11} + return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{12} } func (x *MetricsLogConfig) GetEnabled() *wrapperspb.BoolValue { @@ -1073,7 +1452,7 @@ type EndpointMetricsConfig struct { func (x *EndpointMetricsConfig) Reset() { *x = EndpointMetricsConfig{} if protoimpl.UnsafeEnabled { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[12] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1086,7 +1465,7 @@ func (x *EndpointMetricsConfig) String() string { func (*EndpointMetricsConfig) ProtoMessage() {} func (x *EndpointMetricsConfig) ProtoReflect() protoreflect.Message { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[12] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[13] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1099,7 +1478,7 @@ func (x *EndpointMetricsConfig) ProtoReflect() protoreflect.Message { // Deprecated: Use EndpointMetricsConfig.ProtoReflect.Descriptor instead. func (*EndpointMetricsConfig) Descriptor() ([]byte, []int) { - return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{12} + return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{13} } func (x *EndpointMetricsConfig) GetEnabled() *wrapperspb.BoolValue { @@ -1139,7 +1518,7 @@ type MetricsConfig struct { func (x *MetricsConfig) Reset() { *x = MetricsConfig{} if protoimpl.UnsafeEnabled { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[13] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[14] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1152,7 +1531,7 @@ func (x *MetricsConfig) String() string { func (*MetricsConfig) ProtoMessage() {} func (x *MetricsConfig) ProtoReflect() protoreflect.Message { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[13] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[14] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1165,7 +1544,7 @@ func (x *MetricsConfig) ProtoReflect() protoreflect.Message { // Deprecated: Use MetricsConfig.ProtoReflect.Descriptor instead. func (*MetricsConfig) Descriptor() ([]byte, []int) { - return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{13} + return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{14} } func (x *MetricsConfig) GetEnabled() *wrapperspb.BoolValue { @@ -1211,7 +1590,7 @@ type RateLimitConfig struct { func (x *RateLimitConfig) Reset() { *x = RateLimitConfig{} if protoimpl.UnsafeEnabled { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[14] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[15] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1224,7 +1603,7 @@ func (x *RateLimitConfig) String() string { func (*RateLimitConfig) ProtoMessage() {} func (x *RateLimitConfig) ProtoReflect() protoreflect.Message { - mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[14] + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[15] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1237,7 +1616,7 @@ func (x *RateLimitConfig) ProtoReflect() protoreflect.Message { // Deprecated: Use RateLimitConfig.ProtoReflect.Descriptor instead. func (*RateLimitConfig) Descriptor() ([]byte, []int) { - return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{14} + return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{15} } func (x *RateLimitConfig) GetEnabled() *wrapperspb.BoolValue { @@ -1282,6 +1661,287 @@ func (x *RateLimitConfig) GetSpanType() SpanType { return SpanType_SPAN_TYPE_UNSPECIFIED } +// Message describes what message should be considered for certain DataCapture option +type Message struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // when `false` it disables the capture for the request in a client/request operation + Request *wrapperspb.BoolValue `protobuf:"bytes,1,opt,name=request,proto3" json:"request,omitempty"` + // when `false` it disables the capture for the response in a client/request operation + Response *wrapperspb.BoolValue `protobuf:"bytes,2,opt,name=response,proto3" json:"response,omitempty"` +} + +func (x *Message) Reset() { + *x = Message{} + if protoimpl.UnsafeEnabled { + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[16] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Message) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Message) ProtoMessage() {} + +func (x *Message) ProtoReflect() protoreflect.Message { + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[16] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Message.ProtoReflect.Descriptor instead. +func (*Message) Descriptor() ([]byte, []int) { + return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{16} +} + +func (x *Message) GetRequest() *wrapperspb.BoolValue { + if x != nil { + return x.Request + } + return nil +} + +func (x *Message) GetResponse() *wrapperspb.BoolValue { + if x != nil { + return x.Response + } + return nil +} + +// DataCapture describes the elements to be captured by the agent instrumentation +type DataCapture struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // http_headers enables/disables the capture of the request/response headers in HTTP + HttpHeaders *Message `protobuf:"bytes,1,opt,name=http_headers,json=httpHeaders,proto3" json:"http_headers,omitempty"` + // http_body enables/disables the capture of the request/response body in HTTP + HttpBody *Message `protobuf:"bytes,2,opt,name=http_body,json=httpBody,proto3" json:"http_body,omitempty"` + // rpc_metadata enables/disables the capture of the request/response metadata in RPC + RpcMetadata *Message `protobuf:"bytes,3,opt,name=rpc_metadata,json=rpcMetadata,proto3" json:"rpc_metadata,omitempty"` + // rpc_body enables/disables the capture of the request/response body in RPC + RpcBody *Message `protobuf:"bytes,4,opt,name=rpc_body,json=rpcBody,proto3" json:"rpc_body,omitempty"` + // body_max_size_bytes is the maximum size of captured body in bytes. + // Default should be 131_072 (128 KiB). + BodyMaxSizeBytes *wrapperspb.Int32Value `protobuf:"bytes,5,opt,name=body_max_size_bytes,json=bodyMaxSizeBytes,proto3" json:"body_max_size_bytes,omitempty"` + // body_max_processing_size_bytes is maximum size of body being processed by filters in bytes. + // Default should be 1_048_576 (1MB). + // + // For uncompressed bodies we capture all bytes up to `body_max_processing_size_bytes` + // in memory and pass that through the filter. + // For compressed and GRPC bodies, if the size of the body is larger than this, we ignore + // it entirely, otherwise we decompress/decode the body and then pass it to the filter. + BodyMaxProcessingSizeBytes *wrapperspb.Int32Value `protobuf:"bytes,6,opt,name=body_max_processing_size_bytes,json=bodyMaxProcessingSizeBytes,proto3" json:"body_max_processing_size_bytes,omitempty"` + // Array of allowed content type substrings to record + // default should be json, x-www-form-urlencoded + // ex: ["json"] will record any request bodies that have a content-type header that includes "json" + AllowedContentTypes []*wrapperspb.StringValue `protobuf:"bytes,10,rep,name=allowed_content_types,json=allowedContentTypes,proto3" json:"allowed_content_types,omitempty"` +} + +func (x *DataCapture) Reset() { + *x = DataCapture{} + if protoimpl.UnsafeEnabled { + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[17] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *DataCapture) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DataCapture) ProtoMessage() {} + +func (x *DataCapture) ProtoReflect() protoreflect.Message { + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[17] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DataCapture.ProtoReflect.Descriptor instead. +func (*DataCapture) Descriptor() ([]byte, []int) { + return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{17} +} + +func (x *DataCapture) GetHttpHeaders() *Message { + if x != nil { + return x.HttpHeaders + } + return nil +} + +func (x *DataCapture) GetHttpBody() *Message { + if x != nil { + return x.HttpBody + } + return nil +} + +func (x *DataCapture) GetRpcMetadata() *Message { + if x != nil { + return x.RpcMetadata + } + return nil +} + +func (x *DataCapture) GetRpcBody() *Message { + if x != nil { + return x.RpcBody + } + return nil +} + +func (x *DataCapture) GetBodyMaxSizeBytes() *wrapperspb.Int32Value { + if x != nil { + return x.BodyMaxSizeBytes + } + return nil +} + +func (x *DataCapture) GetBodyMaxProcessingSizeBytes() *wrapperspb.Int32Value { + if x != nil { + return x.BodyMaxProcessingSizeBytes + } + return nil +} + +func (x *DataCapture) GetAllowedContentTypes() []*wrapperspb.StringValue { + if x != nil { + return x.AllowedContentTypes + } + return nil +} + +// GoAgent has the configs specific to goagent +type GoAgent struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // use the custom batch_span_processor adapted from the one in opentelemetry go + // and supports some additional metrics + UseCustomBsp *wrapperspb.BoolValue `protobuf:"bytes,1,opt,name=use_custom_bsp,json=useCustomBsp,proto3" json:"use_custom_bsp,omitempty"` +} + +func (x *GoAgent) Reset() { + *x = GoAgent{} + if protoimpl.UnsafeEnabled { + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[18] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GoAgent) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GoAgent) ProtoMessage() {} + +func (x *GoAgent) ProtoReflect() protoreflect.Message { + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[18] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GoAgent.ProtoReflect.Descriptor instead. +func (*GoAgent) Descriptor() ([]byte, []int) { + return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{18} +} + +func (x *GoAgent) GetUseCustomBsp() *wrapperspb.BoolValue { + if x != nil { + return x.UseCustomBsp + } + return nil +} + +// Telemetry has config for agent telemetry: traces and metrics on agent's +// performance and events. +type Telemetry struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // when `true`, an internal span is created and exported when the agent is initialized and started. + // It's useful to denote when the application the agent is in started. + StartupSpanEnabled *wrapperspb.BoolValue `protobuf:"bytes,1,opt,name=startup_span_enabled,json=startupSpanEnabled,proto3" json:"startup_span_enabled,omitempty"` + // Whether to capture metrics or not. The metrics will be otel go metrics. + // See https://github.com/open-telemetry/opentelemetry-go/tree/main/metric + MetricsEnabled *wrapperspb.BoolValue `protobuf:"bytes,2,opt,name=metrics_enabled,json=metricsEnabled,proto3" json:"metrics_enabled,omitempty"` +} + +func (x *Telemetry) Reset() { + *x = Telemetry{} + if protoimpl.UnsafeEnabled { + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[19] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Telemetry) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Telemetry) ProtoMessage() {} + +func (x *Telemetry) ProtoReflect() protoreflect.Message { + mi := &file_ai_traceable_agent_config_v1_config_proto_msgTypes[19] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Telemetry.ProtoReflect.Descriptor instead. +func (*Telemetry) Descriptor() ([]byte, []int) { + return file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP(), []int{19} +} + +func (x *Telemetry) GetStartupSpanEnabled() *wrapperspb.BoolValue { + if x != nil { + return x.StartupSpanEnabled + } + return nil +} + +func (x *Telemetry) GetMetricsEnabled() *wrapperspb.BoolValue { + if x != nil { + return x.MetricsEnabled + } + return nil +} + var File_ai_traceable_agent_config_v1_config_proto protoreflect.FileDescriptor var file_ai_traceable_agent_config_v1_config_proto_rawDesc = []byte{ @@ -1291,7 +1951,7 @@ var file_ai_traceable_agent_config_v1_config_proto_rawDesc = []byte{ 0x74, 0x72, 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, 0x31, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, - 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xee, 0x05, 0x0a, 0x0b, 0x41, 0x67, + 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x9f, 0x0b, 0x0a, 0x0b, 0x41, 0x67, 0x65, 0x6e, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x37, 0x0a, 0x03, 0x6f, 0x70, 0x61, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x61, 0x69, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x63, 0x6f, 0x6e, 0x66, @@ -1338,7 +1998,87 @@ var file_ai_traceable_agent_config_v1_config_proto_rawDesc = []byte{ 0x76, 0x69, 0x72, 0x6f, 0x6e, 0x6d, 0x65, 0x6e, 0x74, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0b, 0x65, - 0x6e, 0x76, 0x69, 0x72, 0x6f, 0x6e, 0x6d, 0x65, 0x6e, 0x74, 0x22, 0xcd, 0x02, 0x0a, 0x03, 0x4f, + 0x6e, 0x76, 0x69, 0x72, 0x6f, 0x6e, 0x6d, 0x65, 0x6e, 0x74, 0x12, 0x3f, 0x0a, 0x0c, 0x73, 0x65, + 0x72, 0x76, 0x69, 0x63, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, + 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0b, + 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x45, 0x0a, 0x09, 0x72, + 0x65, 0x70, 0x6f, 0x72, 0x74, 0x69, 0x6e, 0x67, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x27, + 0x2e, 0x61, 0x69, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x61, 0x67, + 0x65, 0x6e, 0x74, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, + 0x70, 0x6f, 0x72, 0x74, 0x69, 0x6e, 0x67, 0x52, 0x09, 0x72, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x69, + 0x6e, 0x67, 0x12, 0x4c, 0x0a, 0x0c, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x63, 0x61, 0x70, 0x74, 0x75, + 0x72, 0x65, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x61, 0x69, 0x2e, 0x74, 0x72, + 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x63, 0x6f, + 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, 0x31, 0x2e, 0x44, 0x61, 0x74, 0x61, 0x43, 0x61, 0x70, 0x74, + 0x75, 0x72, 0x65, 0x52, 0x0b, 0x64, 0x61, 0x74, 0x61, 0x43, 0x61, 0x70, 0x74, 0x75, 0x72, 0x65, + 0x12, 0x60, 0x0a, 0x13, 0x70, 0x72, 0x6f, 0x70, 0x61, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, + 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x73, 0x18, 0x0e, 0x20, 0x03, 0x28, 0x0e, 0x32, 0x2f, 0x2e, + 0x61, 0x69, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x61, 0x67, 0x65, + 0x6e, 0x74, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, 0x31, 0x2e, 0x50, 0x72, 0x6f, + 0x70, 0x61, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x52, 0x12, + 0x70, 0x72, 0x6f, 0x70, 0x61, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x46, 0x6f, 0x72, 0x6d, 0x61, + 0x74, 0x73, 0x12, 0x34, 0x0a, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x0f, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, + 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x72, 0x0a, 0x13, 0x72, 0x65, 0x73, 0x6f, + 0x75, 0x72, 0x63, 0x65, 0x5f, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x18, + 0x10, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x41, 0x2e, 0x61, 0x69, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, + 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, + 0x67, 0x2e, 0x76, 0x31, 0x2e, 0x41, 0x67, 0x65, 0x6e, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, + 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, + 0x74, 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x12, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, + 0x63, 0x65, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x12, 0x45, 0x0a, 0x09, + 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x18, 0x11, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x27, 0x2e, 0x61, 0x69, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x61, + 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, 0x31, 0x2e, 0x54, + 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x52, 0x09, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, + 0x74, 0x72, 0x79, 0x12, 0x3f, 0x0a, 0x07, 0x67, 0x6f, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x18, 0x12, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x25, 0x2e, 0x61, 0x69, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x61, + 0x62, 0x6c, 0x65, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, + 0x2e, 0x76, 0x31, 0x2e, 0x47, 0x6f, 0x41, 0x67, 0x65, 0x6e, 0x74, 0x52, 0x07, 0x67, 0x6f, 0x61, + 0x67, 0x65, 0x6e, 0x74, 0x1a, 0x45, 0x0a, 0x17, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, + 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, + 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, + 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0xcc, 0x04, 0x0a, 0x09, + 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x69, 0x6e, 0x67, 0x12, 0x38, 0x0a, 0x08, 0x65, 0x6e, 0x64, + 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, + 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x08, 0x65, 0x6e, 0x64, 0x70, 0x6f, + 0x69, 0x6e, 0x74, 0x12, 0x32, 0x0a, 0x06, 0x73, 0x65, 0x63, 0x75, 0x72, 0x65, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, + 0x06, 0x73, 0x65, 0x63, 0x75, 0x72, 0x65, 0x12, 0x32, 0x0a, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, + 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, + 0x61, 0x6c, 0x75, 0x65, 0x52, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x5f, 0x0a, 0x13, 0x74, + 0x72, 0x61, 0x63, 0x65, 0x5f, 0x72, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x72, 0x5f, 0x74, 0x79, + 0x70, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2f, 0x2e, 0x61, 0x69, 0x2e, 0x74, 0x72, + 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x63, 0x6f, + 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, 0x31, 0x2e, 0x54, 0x72, 0x61, 0x63, 0x65, 0x52, 0x65, 0x70, + 0x6f, 0x72, 0x74, 0x65, 0x72, 0x54, 0x79, 0x70, 0x65, 0x52, 0x11, 0x74, 0x72, 0x61, 0x63, 0x65, + 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x72, 0x54, 0x79, 0x70, 0x65, 0x12, 0x39, 0x0a, 0x09, + 0x63, 0x65, 0x72, 0x74, 0x5f, 0x66, 0x69, 0x6c, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x08, 0x63, + 0x65, 0x72, 0x74, 0x46, 0x69, 0x6c, 0x65, 0x12, 0x45, 0x0a, 0x0f, 0x6d, 0x65, 0x74, 0x72, 0x69, + 0x63, 0x5f, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, + 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0e, + 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x12, 0x62, + 0x0a, 0x14, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x5f, 0x72, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x65, + 0x72, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x30, 0x2e, 0x61, + 0x69, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x61, 0x67, 0x65, 0x6e, + 0x74, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x65, 0x74, 0x72, + 0x69, 0x63, 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x72, 0x54, 0x79, 0x70, 0x65, 0x52, 0x12, + 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x72, 0x54, 0x79, + 0x70, 0x65, 0x12, 0x56, 0x0a, 0x19, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x67, 0x72, 0x70, + 0x63, 0x5f, 0x6c, 0x6f, 0x61, 0x64, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x69, 0x6e, 0x67, 0x18, + 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, + 0x65, 0x52, 0x17, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x47, 0x72, 0x70, 0x63, 0x4c, 0x6f, 0x61, + 0x64, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x69, 0x6e, 0x67, 0x22, 0xcd, 0x02, 0x0a, 0x03, 0x4f, 0x70, 0x61, 0x12, 0x34, 0x0a, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, @@ -1460,132 +2200,215 @@ var file_ai_traceable_agent_config_v1_config_proto_rawDesc = []byte{ 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x61, 0x74, 0x65, 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x16, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x52, 0x61, 0x74, 0x65, 0x4c, 0x69, 0x6d, 0x69, 0x74, - 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x22, 0x51, 0x0a, 0x09, 0x4a, 0x61, 0x76, 0x61, 0x61, 0x67, - 0x65, 0x6e, 0x74, 0x12, 0x44, 0x0a, 0x10, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x6a, 0x6b, - 0x73, 0x5f, 0x63, 0x65, 0x72, 0x74, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, - 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, - 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0e, 0x69, 0x6d, 0x70, 0x6f, 0x72, - 0x74, 0x4a, 0x6b, 0x73, 0x43, 0x65, 0x72, 0x74, 0x73, 0x22, 0xda, 0x01, 0x0a, 0x09, 0x4c, 0x6f, - 0x67, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x40, 0x0a, 0x08, 0x6c, 0x6f, 0x67, 0x5f, 0x6d, - 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x25, 0x2e, 0x61, 0x69, 0x2e, 0x74, + 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x22, 0x99, 0x01, 0x0a, 0x09, 0x4a, 0x61, 0x76, 0x61, 0x61, + 0x67, 0x65, 0x6e, 0x74, 0x12, 0x44, 0x0a, 0x10, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x6a, + 0x6b, 0x73, 0x5f, 0x63, 0x65, 0x72, 0x74, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0e, 0x69, 0x6d, 0x70, 0x6f, + 0x72, 0x74, 0x4a, 0x6b, 0x73, 0x43, 0x65, 0x72, 0x74, 0x73, 0x12, 0x46, 0x0a, 0x10, 0x66, 0x69, + 0x6c, 0x74, 0x65, 0x72, 0x5f, 0x6a, 0x61, 0x72, 0x5f, 0x70, 0x61, 0x74, 0x68, 0x73, 0x18, 0x02, + 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, + 0x75, 0x65, 0x52, 0x0e, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x4a, 0x61, 0x72, 0x50, 0x61, 0x74, + 0x68, 0x73, 0x22, 0xda, 0x01, 0x0a, 0x09, 0x4c, 0x6f, 0x67, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, + 0x12, 0x40, 0x0a, 0x08, 0x6c, 0x6f, 0x67, 0x5f, 0x6d, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x0e, 0x32, 0x25, 0x2e, 0x61, 0x69, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, + 0x65, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, + 0x31, 0x2e, 0x4c, 0x6f, 0x67, 0x4d, 0x6f, 0x64, 0x65, 0x52, 0x07, 0x6c, 0x6f, 0x67, 0x4d, 0x6f, + 0x64, 0x65, 0x12, 0x43, 0x0a, 0x09, 0x6c, 0x6f, 0x67, 0x5f, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x26, 0x2e, 0x61, 0x69, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, + 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, + 0x67, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x6f, 0x67, 0x4c, 0x65, 0x76, 0x65, 0x6c, 0x52, 0x08, 0x6c, + 0x6f, 0x67, 0x4c, 0x65, 0x76, 0x65, 0x6c, 0x12, 0x46, 0x0a, 0x08, 0x6c, 0x6f, 0x67, 0x5f, 0x66, + 0x69, 0x6c, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x61, 0x69, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x63, - 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x6f, 0x67, 0x4d, 0x6f, 0x64, 0x65, - 0x52, 0x07, 0x6c, 0x6f, 0x67, 0x4d, 0x6f, 0x64, 0x65, 0x12, 0x43, 0x0a, 0x09, 0x6c, 0x6f, 0x67, - 0x5f, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x26, 0x2e, 0x61, - 0x69, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x61, 0x67, 0x65, 0x6e, - 0x74, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x6f, 0x67, 0x4c, - 0x65, 0x76, 0x65, 0x6c, 0x52, 0x08, 0x6c, 0x6f, 0x67, 0x4c, 0x65, 0x76, 0x65, 0x6c, 0x12, 0x46, - 0x0a, 0x08, 0x6c, 0x6f, 0x67, 0x5f, 0x66, 0x69, 0x6c, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, - 0x32, 0x2b, 0x2e, 0x61, 0x69, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x2e, - 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, 0x31, 0x2e, - 0x4c, 0x6f, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x07, 0x6c, - 0x6f, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x22, 0xc5, 0x01, 0x0a, 0x0d, 0x4c, 0x6f, 0x67, 0x46, 0x69, - 0x6c, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x38, 0x0a, 0x09, 0x6d, 0x61, 0x78, 0x5f, - 0x66, 0x69, 0x6c, 0x65, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, + 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x6f, 0x67, 0x46, 0x69, 0x6c, 0x65, + 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x07, 0x6c, 0x6f, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x22, + 0xc5, 0x01, 0x0a, 0x0d, 0x4c, 0x6f, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, + 0x67, 0x12, 0x38, 0x0a, 0x09, 0x6d, 0x61, 0x78, 0x5f, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, + 0x65, 0x52, 0x08, 0x6d, 0x61, 0x78, 0x46, 0x69, 0x6c, 0x65, 0x73, 0x12, 0x3f, 0x0a, 0x0d, 0x6d, + 0x61, 0x78, 0x5f, 0x66, 0x69, 0x6c, 0x65, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x02, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, + 0x0b, 0x6d, 0x61, 0x78, 0x46, 0x69, 0x6c, 0x65, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x39, 0x0a, 0x09, + 0x66, 0x69, 0x6c, 0x65, 0x5f, 0x70, 0x61, 0x74, 0x68, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x08, 0x66, + 0x69, 0x6c, 0x65, 0x50, 0x61, 0x74, 0x68, 0x22, 0x84, 0x01, 0x0a, 0x10, 0x4d, 0x65, 0x74, 0x72, + 0x69, 0x63, 0x73, 0x4c, 0x6f, 0x67, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x34, 0x0a, 0x07, + 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, + 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, + 0x65, 0x64, 0x12, 0x3a, 0x0a, 0x09, 0x66, 0x72, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x63, 0x79, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, + 0x6c, 0x75, 0x65, 0x52, 0x09, 0x66, 0x72, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x63, 0x79, 0x22, 0xd9, + 0x01, 0x0a, 0x15, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x4d, 0x65, 0x74, 0x72, 0x69, + 0x63, 0x73, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x34, 0x0a, 0x07, 0x65, 0x6e, 0x61, 0x62, + 0x6c, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, + 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x40, + 0x0a, 0x0d, 0x6d, 0x61, 0x78, 0x5f, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, + 0x75, 0x65, 0x52, 0x0c, 0x6d, 0x61, 0x78, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x73, + 0x12, 0x48, 0x0a, 0x07, 0x6c, 0x6f, 0x67, 0x67, 0x69, 0x6e, 0x67, 0x18, 0x03, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x2e, 0x2e, 0x61, 0x69, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, 0x65, + 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, 0x31, + 0x2e, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x4c, 0x6f, 0x67, 0x43, 0x6f, 0x6e, 0x66, 0x69, + 0x67, 0x52, 0x07, 0x6c, 0x6f, 0x67, 0x67, 0x69, 0x6e, 0x67, 0x22, 0xed, 0x01, 0x0a, 0x0d, 0x4d, + 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x34, 0x0a, 0x07, + 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, + 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, + 0x65, 0x64, 0x12, 0x5c, 0x0a, 0x0f, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x5f, 0x63, + 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x33, 0x2e, 0x61, 0x69, + 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, + 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x6e, 0x64, 0x70, 0x6f, + 0x69, 0x6e, 0x74, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, + 0x52, 0x0e, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, + 0x12, 0x48, 0x0a, 0x07, 0x6c, 0x6f, 0x67, 0x67, 0x69, 0x6e, 0x67, 0x18, 0x03, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x2e, 0x2e, 0x61, 0x69, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, 0x65, + 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, 0x31, + 0x2e, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x4c, 0x6f, 0x67, 0x43, 0x6f, 0x6e, 0x66, 0x69, + 0x67, 0x52, 0x07, 0x6c, 0x6f, 0x67, 0x67, 0x69, 0x6e, 0x67, 0x22, 0xc0, 0x03, 0x0a, 0x0f, 0x52, + 0x61, 0x74, 0x65, 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x34, + 0x0a, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x07, 0x65, 0x6e, 0x61, + 0x62, 0x6c, 0x65, 0x64, 0x12, 0x45, 0x0a, 0x10, 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x6f, 0x75, 0x6e, + 0x74, 0x5f, 0x67, 0x6c, 0x6f, 0x62, 0x61, 0x6c, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x2e, 0x49, 0x6e, 0x74, 0x36, 0x34, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0e, 0x6d, 0x61, 0x78, + 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x47, 0x6c, 0x6f, 0x62, 0x61, 0x6c, 0x12, 0x50, 0x0a, 0x16, 0x6d, + 0x61, 0x78, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x5f, 0x70, 0x65, 0x72, 0x5f, 0x65, 0x6e, 0x64, + 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x49, 0x6e, - 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x08, 0x6d, 0x61, 0x78, 0x46, 0x69, 0x6c, - 0x65, 0x73, 0x12, 0x3f, 0x0a, 0x0d, 0x6d, 0x61, 0x78, 0x5f, 0x66, 0x69, 0x6c, 0x65, 0x5f, 0x73, - 0x69, 0x7a, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, - 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x49, 0x6e, 0x74, 0x33, - 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0b, 0x6d, 0x61, 0x78, 0x46, 0x69, 0x6c, 0x65, 0x53, - 0x69, 0x7a, 0x65, 0x12, 0x39, 0x0a, 0x09, 0x66, 0x69, 0x6c, 0x65, 0x5f, 0x70, 0x61, 0x74, 0x68, - 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, - 0x61, 0x6c, 0x75, 0x65, 0x52, 0x08, 0x66, 0x69, 0x6c, 0x65, 0x50, 0x61, 0x74, 0x68, 0x22, 0x84, - 0x01, 0x0a, 0x10, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x4c, 0x6f, 0x67, 0x43, 0x6f, 0x6e, - 0x66, 0x69, 0x67, 0x12, 0x34, 0x0a, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, - 0x52, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x3a, 0x0a, 0x09, 0x66, 0x72, 0x65, - 0x71, 0x75, 0x65, 0x6e, 0x63, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, - 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x09, 0x66, 0x72, 0x65, 0x71, - 0x75, 0x65, 0x6e, 0x63, 0x79, 0x22, 0xd9, 0x01, 0x0a, 0x15, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, - 0x6e, 0x74, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, - 0x34, 0x0a, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, + 0x74, 0x36, 0x34, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x13, 0x6d, 0x61, 0x78, 0x43, 0x6f, 0x75, + 0x6e, 0x74, 0x50, 0x65, 0x72, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x12, 0x43, 0x0a, + 0x0e, 0x72, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x5f, 0x70, 0x65, 0x72, 0x69, 0x6f, 0x64, 0x18, + 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, + 0x6c, 0x75, 0x65, 0x52, 0x0d, 0x72, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x50, 0x65, 0x72, 0x69, + 0x6f, 0x64, 0x12, 0x54, 0x0a, 0x17, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x5f, 0x65, 0x78, 0x70, 0x69, + 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x70, 0x65, 0x72, 0x69, 0x6f, 0x64, 0x18, 0x05, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, + 0x65, 0x52, 0x15, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x45, 0x78, 0x70, 0x69, 0x72, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x50, 0x65, 0x72, 0x69, 0x6f, 0x64, 0x12, 0x43, 0x0a, 0x09, 0x73, 0x70, 0x61, 0x6e, + 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x26, 0x2e, 0x61, 0x69, + 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, + 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x61, 0x6e, 0x54, + 0x79, 0x70, 0x65, 0x52, 0x08, 0x73, 0x70, 0x61, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x22, 0x77, 0x0a, + 0x07, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x34, 0x0a, 0x07, 0x72, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, + 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x07, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x36, + 0x0a, 0x08, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, - 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x07, 0x65, 0x6e, - 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x40, 0x0a, 0x0d, 0x6d, 0x61, 0x78, 0x5f, 0x65, 0x6e, 0x64, - 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x49, - 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0c, 0x6d, 0x61, 0x78, 0x45, 0x6e, - 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x12, 0x48, 0x0a, 0x07, 0x6c, 0x6f, 0x67, 0x67, 0x69, - 0x6e, 0x67, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2e, 0x2e, 0x61, 0x69, 0x2e, 0x74, 0x72, - 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x63, 0x6f, - 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x4c, - 0x6f, 0x67, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x07, 0x6c, 0x6f, 0x67, 0x67, 0x69, 0x6e, - 0x67, 0x22, 0xed, 0x01, 0x0a, 0x0d, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x43, 0x6f, 0x6e, - 0x66, 0x69, 0x67, 0x12, 0x34, 0x0a, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, - 0x52, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x5c, 0x0a, 0x0f, 0x65, 0x6e, 0x64, - 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x02, 0x20, 0x01, - 0x28, 0x0b, 0x32, 0x33, 0x2e, 0x61, 0x69, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, - 0x65, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, - 0x31, 0x2e, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, - 0x73, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x0e, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, - 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x48, 0x0a, 0x07, 0x6c, 0x6f, 0x67, 0x67, 0x69, - 0x6e, 0x67, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2e, 0x2e, 0x61, 0x69, 0x2e, 0x74, 0x72, - 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x63, 0x6f, - 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x4c, - 0x6f, 0x67, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x07, 0x6c, 0x6f, 0x67, 0x67, 0x69, 0x6e, - 0x67, 0x22, 0xc0, 0x03, 0x0a, 0x0f, 0x52, 0x61, 0x74, 0x65, 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x43, - 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x34, 0x0a, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, - 0x75, 0x65, 0x52, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x45, 0x0a, 0x10, 0x6d, - 0x61, 0x78, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x5f, 0x67, 0x6c, 0x6f, 0x62, 0x61, 0x6c, 0x18, - 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x49, 0x6e, 0x74, 0x36, 0x34, 0x56, 0x61, 0x6c, - 0x75, 0x65, 0x52, 0x0e, 0x6d, 0x61, 0x78, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x47, 0x6c, 0x6f, 0x62, - 0x61, 0x6c, 0x12, 0x50, 0x0a, 0x16, 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x5f, - 0x70, 0x65, 0x72, 0x5f, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x18, 0x03, 0x20, 0x01, - 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x49, 0x6e, 0x74, 0x36, 0x34, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, - 0x13, 0x6d, 0x61, 0x78, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x50, 0x65, 0x72, 0x45, 0x6e, 0x64, 0x70, - 0x6f, 0x69, 0x6e, 0x74, 0x12, 0x43, 0x0a, 0x0e, 0x72, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x5f, - 0x70, 0x65, 0x72, 0x69, 0x6f, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, + 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x08, 0x72, 0x65, + 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0xa6, 0x04, 0x0a, 0x0b, 0x44, 0x61, 0x74, 0x61, 0x43, + 0x61, 0x70, 0x74, 0x75, 0x72, 0x65, 0x12, 0x48, 0x0a, 0x0c, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x68, + 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x25, 0x2e, 0x61, + 0x69, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x61, 0x67, 0x65, 0x6e, + 0x74, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x65, 0x73, 0x73, + 0x61, 0x67, 0x65, 0x52, 0x0b, 0x68, 0x74, 0x74, 0x70, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x73, + 0x12, 0x42, 0x0a, 0x09, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x62, 0x6f, 0x64, 0x79, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x25, 0x2e, 0x61, 0x69, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x61, 0x62, + 0x6c, 0x65, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, + 0x76, 0x31, 0x2e, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x52, 0x08, 0x68, 0x74, 0x74, 0x70, + 0x42, 0x6f, 0x64, 0x79, 0x12, 0x48, 0x0a, 0x0c, 0x72, 0x70, 0x63, 0x5f, 0x6d, 0x65, 0x74, 0x61, + 0x64, 0x61, 0x74, 0x61, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x25, 0x2e, 0x61, 0x69, 0x2e, + 0x74, 0x72, 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, + 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, + 0x65, 0x52, 0x0b, 0x72, 0x70, 0x63, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x40, + 0x0a, 0x08, 0x72, 0x70, 0x63, 0x5f, 0x62, 0x6f, 0x64, 0x79, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x25, 0x2e, 0x61, 0x69, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x2e, + 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, 0x31, 0x2e, + 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x52, 0x07, 0x72, 0x70, 0x63, 0x42, 0x6f, 0x64, 0x79, + 0x12, 0x4a, 0x0a, 0x13, 0x62, 0x6f, 0x64, 0x79, 0x5f, 0x6d, 0x61, 0x78, 0x5f, 0x73, 0x69, 0x7a, + 0x65, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, + 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x10, 0x62, 0x6f, 0x64, 0x79, + 0x4d, 0x61, 0x78, 0x53, 0x69, 0x7a, 0x65, 0x42, 0x79, 0x74, 0x65, 0x73, 0x12, 0x5f, 0x0a, 0x1e, + 0x62, 0x6f, 0x64, 0x79, 0x5f, 0x6d, 0x61, 0x78, 0x5f, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, + 0x69, 0x6e, 0x67, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x06, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, + 0x65, 0x52, 0x1a, 0x62, 0x6f, 0x64, 0x79, 0x4d, 0x61, 0x78, 0x50, 0x72, 0x6f, 0x63, 0x65, 0x73, + 0x73, 0x69, 0x6e, 0x67, 0x53, 0x69, 0x7a, 0x65, 0x42, 0x79, 0x74, 0x65, 0x73, 0x12, 0x50, 0x0a, + 0x15, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x65, 0x64, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, + 0x5f, 0x74, 0x79, 0x70, 0x65, 0x73, 0x18, 0x0a, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, - 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0d, 0x72, 0x65, 0x66, 0x72, - 0x65, 0x73, 0x68, 0x50, 0x65, 0x72, 0x69, 0x6f, 0x64, 0x12, 0x54, 0x0a, 0x17, 0x76, 0x61, 0x6c, - 0x75, 0x65, 0x5f, 0x65, 0x78, 0x70, 0x69, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x70, 0x65, - 0x72, 0x69, 0x6f, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, - 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x15, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x45, - 0x78, 0x70, 0x69, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x65, 0x72, 0x69, 0x6f, 0x64, 0x12, - 0x43, 0x0a, 0x09, 0x73, 0x70, 0x61, 0x6e, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x06, 0x20, 0x01, - 0x28, 0x0e, 0x32, 0x26, 0x2e, 0x61, 0x69, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, - 0x65, 0x2e, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x76, - 0x31, 0x2e, 0x53, 0x70, 0x61, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x52, 0x08, 0x73, 0x70, 0x61, 0x6e, - 0x54, 0x79, 0x70, 0x65, 0x2a, 0x5e, 0x0a, 0x07, 0x4c, 0x6f, 0x67, 0x4d, 0x6f, 0x64, 0x65, 0x12, - 0x18, 0x0a, 0x14, 0x4c, 0x4f, 0x47, 0x5f, 0x4d, 0x4f, 0x44, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x50, - 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x11, 0x0a, 0x0d, 0x4c, 0x4f, 0x47, - 0x5f, 0x4d, 0x4f, 0x44, 0x45, 0x5f, 0x4e, 0x4f, 0x4e, 0x45, 0x10, 0x01, 0x12, 0x13, 0x0a, 0x0f, - 0x4c, 0x4f, 0x47, 0x5f, 0x4d, 0x4f, 0x44, 0x45, 0x5f, 0x53, 0x54, 0x44, 0x4f, 0x55, 0x54, 0x10, - 0x02, 0x12, 0x11, 0x0a, 0x0d, 0x4c, 0x4f, 0x47, 0x5f, 0x4d, 0x4f, 0x44, 0x45, 0x5f, 0x46, 0x49, - 0x4c, 0x45, 0x10, 0x03, 0x2a, 0xa4, 0x01, 0x0a, 0x08, 0x4c, 0x6f, 0x67, 0x4c, 0x65, 0x76, 0x65, - 0x6c, 0x12, 0x19, 0x0a, 0x15, 0x4c, 0x4f, 0x47, 0x5f, 0x4c, 0x45, 0x56, 0x45, 0x4c, 0x5f, 0x55, - 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x13, 0x0a, 0x0f, - 0x4c, 0x4f, 0x47, 0x5f, 0x4c, 0x45, 0x56, 0x45, 0x4c, 0x5f, 0x54, 0x52, 0x41, 0x43, 0x45, 0x10, - 0x01, 0x12, 0x13, 0x0a, 0x0f, 0x4c, 0x4f, 0x47, 0x5f, 0x4c, 0x45, 0x56, 0x45, 0x4c, 0x5f, 0x44, - 0x45, 0x42, 0x55, 0x47, 0x10, 0x02, 0x12, 0x12, 0x0a, 0x0e, 0x4c, 0x4f, 0x47, 0x5f, 0x4c, 0x45, - 0x56, 0x45, 0x4c, 0x5f, 0x49, 0x4e, 0x46, 0x4f, 0x10, 0x03, 0x12, 0x12, 0x0a, 0x0e, 0x4c, 0x4f, - 0x47, 0x5f, 0x4c, 0x45, 0x56, 0x45, 0x4c, 0x5f, 0x57, 0x41, 0x52, 0x4e, 0x10, 0x04, 0x12, 0x13, - 0x0a, 0x0f, 0x4c, 0x4f, 0x47, 0x5f, 0x4c, 0x45, 0x56, 0x45, 0x4c, 0x5f, 0x45, 0x52, 0x52, 0x4f, - 0x52, 0x10, 0x05, 0x12, 0x16, 0x0a, 0x12, 0x4c, 0x4f, 0x47, 0x5f, 0x4c, 0x45, 0x56, 0x45, 0x4c, - 0x5f, 0x43, 0x52, 0x49, 0x54, 0x49, 0x43, 0x41, 0x4c, 0x10, 0x06, 0x2a, 0x6e, 0x0a, 0x08, 0x53, - 0x70, 0x61, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x12, 0x19, 0x0a, 0x15, 0x53, 0x50, 0x41, 0x4e, 0x5f, + 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x13, 0x61, 0x6c, 0x6c, 0x6f, + 0x77, 0x65, 0x64, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x73, 0x22, + 0x4b, 0x0a, 0x07, 0x47, 0x6f, 0x41, 0x67, 0x65, 0x6e, 0x74, 0x12, 0x40, 0x0a, 0x0e, 0x75, 0x73, + 0x65, 0x5f, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x62, 0x73, 0x70, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0c, + 0x75, 0x73, 0x65, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x42, 0x73, 0x70, 0x22, 0x9e, 0x01, 0x0a, + 0x09, 0x54, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x12, 0x4c, 0x0a, 0x14, 0x73, 0x74, + 0x61, 0x72, 0x74, 0x75, 0x70, 0x5f, 0x73, 0x70, 0x61, 0x6e, 0x5f, 0x65, 0x6e, 0x61, 0x62, 0x6c, + 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, + 0x61, 0x6c, 0x75, 0x65, 0x52, 0x12, 0x73, 0x74, 0x61, 0x72, 0x74, 0x75, 0x70, 0x53, 0x70, 0x61, + 0x6e, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x43, 0x0a, 0x0f, 0x6d, 0x65, 0x74, 0x72, + 0x69, 0x63, 0x73, 0x5f, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0e, 0x6d, + 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x2a, 0x5e, 0x0a, + 0x07, 0x4c, 0x6f, 0x67, 0x4d, 0x6f, 0x64, 0x65, 0x12, 0x18, 0x0a, 0x14, 0x4c, 0x4f, 0x47, 0x5f, + 0x4d, 0x4f, 0x44, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, + 0x10, 0x00, 0x12, 0x11, 0x0a, 0x0d, 0x4c, 0x4f, 0x47, 0x5f, 0x4d, 0x4f, 0x44, 0x45, 0x5f, 0x4e, + 0x4f, 0x4e, 0x45, 0x10, 0x01, 0x12, 0x13, 0x0a, 0x0f, 0x4c, 0x4f, 0x47, 0x5f, 0x4d, 0x4f, 0x44, + 0x45, 0x5f, 0x53, 0x54, 0x44, 0x4f, 0x55, 0x54, 0x10, 0x02, 0x12, 0x11, 0x0a, 0x0d, 0x4c, 0x4f, + 0x47, 0x5f, 0x4d, 0x4f, 0x44, 0x45, 0x5f, 0x46, 0x49, 0x4c, 0x45, 0x10, 0x03, 0x2a, 0xa4, 0x01, + 0x0a, 0x08, 0x4c, 0x6f, 0x67, 0x4c, 0x65, 0x76, 0x65, 0x6c, 0x12, 0x19, 0x0a, 0x15, 0x4c, 0x4f, + 0x47, 0x5f, 0x4c, 0x45, 0x56, 0x45, 0x4c, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, + 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x13, 0x0a, 0x0f, 0x4c, 0x4f, 0x47, 0x5f, 0x4c, 0x45, 0x56, + 0x45, 0x4c, 0x5f, 0x54, 0x52, 0x41, 0x43, 0x45, 0x10, 0x01, 0x12, 0x13, 0x0a, 0x0f, 0x4c, 0x4f, + 0x47, 0x5f, 0x4c, 0x45, 0x56, 0x45, 0x4c, 0x5f, 0x44, 0x45, 0x42, 0x55, 0x47, 0x10, 0x02, 0x12, + 0x12, 0x0a, 0x0e, 0x4c, 0x4f, 0x47, 0x5f, 0x4c, 0x45, 0x56, 0x45, 0x4c, 0x5f, 0x49, 0x4e, 0x46, + 0x4f, 0x10, 0x03, 0x12, 0x12, 0x0a, 0x0e, 0x4c, 0x4f, 0x47, 0x5f, 0x4c, 0x45, 0x56, 0x45, 0x4c, + 0x5f, 0x57, 0x41, 0x52, 0x4e, 0x10, 0x04, 0x12, 0x13, 0x0a, 0x0f, 0x4c, 0x4f, 0x47, 0x5f, 0x4c, + 0x45, 0x56, 0x45, 0x4c, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x05, 0x12, 0x16, 0x0a, 0x12, + 0x4c, 0x4f, 0x47, 0x5f, 0x4c, 0x45, 0x56, 0x45, 0x4c, 0x5f, 0x43, 0x52, 0x49, 0x54, 0x49, 0x43, + 0x41, 0x4c, 0x10, 0x06, 0x2a, 0x6e, 0x0a, 0x08, 0x53, 0x70, 0x61, 0x6e, 0x54, 0x79, 0x70, 0x65, + 0x12, 0x19, 0x0a, 0x15, 0x53, 0x50, 0x41, 0x4e, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x55, 0x4e, + 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x15, 0x0a, 0x11, 0x53, + 0x50, 0x41, 0x4e, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x4e, 0x4f, 0x5f, 0x53, 0x50, 0x41, 0x4e, + 0x10, 0x01, 0x12, 0x17, 0x0a, 0x13, 0x53, 0x50, 0x41, 0x4e, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, + 0x42, 0x41, 0x52, 0x45, 0x5f, 0x53, 0x50, 0x41, 0x4e, 0x10, 0x02, 0x12, 0x17, 0x0a, 0x13, 0x53, + 0x50, 0x41, 0x4e, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x46, 0x55, 0x4c, 0x4c, 0x5f, 0x53, 0x50, + 0x41, 0x4e, 0x10, 0x03, 0x2a, 0x2d, 0x0a, 0x11, 0x50, 0x72, 0x6f, 0x70, 0x61, 0x67, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x12, 0x06, 0x0a, 0x02, 0x42, 0x33, 0x10, + 0x00, 0x12, 0x10, 0x0a, 0x0c, 0x54, 0x52, 0x41, 0x43, 0x45, 0x43, 0x4f, 0x4e, 0x54, 0x45, 0x58, + 0x54, 0x10, 0x01, 0x2a, 0x60, 0x0a, 0x11, 0x54, 0x72, 0x61, 0x63, 0x65, 0x52, 0x65, 0x70, 0x6f, + 0x72, 0x74, 0x65, 0x72, 0x54, 0x79, 0x70, 0x65, 0x12, 0x0f, 0x0a, 0x0b, 0x55, 0x4e, 0x53, 0x50, + 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x5a, 0x49, 0x50, + 0x4b, 0x49, 0x4e, 0x10, 0x01, 0x12, 0x08, 0x0a, 0x04, 0x4f, 0x54, 0x4c, 0x50, 0x10, 0x02, 0x12, + 0x0b, 0x0a, 0x07, 0x4c, 0x4f, 0x47, 0x47, 0x49, 0x4e, 0x47, 0x10, 0x03, 0x12, 0x08, 0x0a, 0x04, + 0x4e, 0x4f, 0x4e, 0x45, 0x10, 0x04, 0x12, 0x0d, 0x0a, 0x09, 0x4f, 0x54, 0x4c, 0x50, 0x5f, 0x48, + 0x54, 0x54, 0x50, 0x10, 0x05, 0x2a, 0xbf, 0x01, 0x0a, 0x12, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, + 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x72, 0x54, 0x79, 0x70, 0x65, 0x12, 0x24, 0x0a, 0x20, + 0x4d, 0x45, 0x54, 0x52, 0x49, 0x43, 0x5f, 0x52, 0x45, 0x50, 0x4f, 0x52, 0x54, 0x45, 0x52, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, - 0x10, 0x00, 0x12, 0x15, 0x0a, 0x11, 0x53, 0x50, 0x41, 0x4e, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, - 0x4e, 0x4f, 0x5f, 0x53, 0x50, 0x41, 0x4e, 0x10, 0x01, 0x12, 0x17, 0x0a, 0x13, 0x53, 0x50, 0x41, - 0x4e, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x42, 0x41, 0x52, 0x45, 0x5f, 0x53, 0x50, 0x41, 0x4e, - 0x10, 0x02, 0x12, 0x17, 0x0a, 0x13, 0x53, 0x50, 0x41, 0x4e, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, - 0x46, 0x55, 0x4c, 0x4c, 0x5f, 0x53, 0x50, 0x41, 0x4e, 0x10, 0x03, 0x42, 0x4b, 0x5a, 0x2d, 0x67, - 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x54, 0x72, 0x61, 0x63, 0x65, 0x61, - 0x62, 0x6c, 0x65, 0x61, 0x69, 0x2f, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2d, 0x63, 0x6f, 0x6e, 0x66, - 0x69, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x2f, 0x67, 0x6f, 0x2f, 0x76, 0x31, 0xaa, 0x02, 0x19, 0x54, - 0x72, 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x41, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x43, - 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x10, 0x00, 0x12, 0x1d, 0x0a, 0x19, 0x4d, 0x45, 0x54, 0x52, 0x49, 0x43, 0x5f, 0x52, 0x45, 0x50, + 0x4f, 0x52, 0x54, 0x45, 0x52, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x4f, 0x54, 0x4c, 0x50, 0x10, + 0x01, 0x12, 0x23, 0x0a, 0x1f, 0x4d, 0x45, 0x54, 0x52, 0x49, 0x43, 0x5f, 0x52, 0x45, 0x50, 0x4f, + 0x52, 0x54, 0x45, 0x52, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x50, 0x52, 0x4f, 0x4d, 0x45, 0x54, + 0x48, 0x45, 0x55, 0x53, 0x10, 0x02, 0x12, 0x20, 0x0a, 0x1c, 0x4d, 0x45, 0x54, 0x52, 0x49, 0x43, + 0x5f, 0x52, 0x45, 0x50, 0x4f, 0x52, 0x54, 0x45, 0x52, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x4c, + 0x4f, 0x47, 0x47, 0x49, 0x4e, 0x47, 0x10, 0x03, 0x12, 0x1d, 0x0a, 0x19, 0x4d, 0x45, 0x54, 0x52, + 0x49, 0x43, 0x5f, 0x52, 0x45, 0x50, 0x4f, 0x52, 0x54, 0x45, 0x52, 0x5f, 0x54, 0x59, 0x50, 0x45, + 0x5f, 0x4e, 0x4f, 0x4e, 0x45, 0x10, 0x04, 0x42, 0x4b, 0x5a, 0x2d, 0x67, 0x69, 0x74, 0x68, 0x75, + 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x54, 0x72, 0x61, 0x63, 0x65, 0x61, 0x62, 0x6c, 0x65, 0x61, + 0x69, 0x2f, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x2d, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2f, 0x67, + 0x65, 0x6e, 0x2f, 0x67, 0x6f, 0x2f, 0x76, 0x31, 0xaa, 0x02, 0x19, 0x54, 0x72, 0x61, 0x63, 0x65, + 0x61, 0x62, 0x6c, 0x65, 0x2e, 0x41, 0x67, 0x65, 0x6e, 0x74, 0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x69, + 0x67, 0x2e, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -1600,95 +2423,133 @@ func file_ai_traceable_agent_config_v1_config_proto_rawDescGZIP() []byte { return file_ai_traceable_agent_config_v1_config_proto_rawDescData } -var file_ai_traceable_agent_config_v1_config_proto_enumTypes = make([]protoimpl.EnumInfo, 3) -var file_ai_traceable_agent_config_v1_config_proto_msgTypes = make([]protoimpl.MessageInfo, 15) +var file_ai_traceable_agent_config_v1_config_proto_enumTypes = make([]protoimpl.EnumInfo, 6) +var file_ai_traceable_agent_config_v1_config_proto_msgTypes = make([]protoimpl.MessageInfo, 21) var file_ai_traceable_agent_config_v1_config_proto_goTypes = []interface{}{ (LogMode)(0), // 0: ai.traceable.agent.config.v1.LogMode (LogLevel)(0), // 1: ai.traceable.agent.config.v1.LogLevel (SpanType)(0), // 2: ai.traceable.agent.config.v1.SpanType - (*AgentConfig)(nil), // 3: ai.traceable.agent.config.v1.AgentConfig - (*Opa)(nil), // 4: ai.traceable.agent.config.v1.Opa - (*BlockingConfig)(nil), // 5: ai.traceable.agent.config.v1.BlockingConfig - (*ModsecurityConfig)(nil), // 6: ai.traceable.agent.config.v1.ModsecurityConfig - (*RegionBlockingConfig)(nil), // 7: ai.traceable.agent.config.v1.RegionBlockingConfig - (*RemoteConfig)(nil), // 8: ai.traceable.agent.config.v1.RemoteConfig - (*ApiDiscoveryConfig)(nil), // 9: ai.traceable.agent.config.v1.ApiDiscoveryConfig - (*SamplingConfig)(nil), // 10: ai.traceable.agent.config.v1.SamplingConfig - (*Javaagent)(nil), // 11: ai.traceable.agent.config.v1.Javaagent - (*LogConfig)(nil), // 12: ai.traceable.agent.config.v1.LogConfig - (*LogFileConfig)(nil), // 13: ai.traceable.agent.config.v1.LogFileConfig - (*MetricsLogConfig)(nil), // 14: ai.traceable.agent.config.v1.MetricsLogConfig - (*EndpointMetricsConfig)(nil), // 15: ai.traceable.agent.config.v1.EndpointMetricsConfig - (*MetricsConfig)(nil), // 16: ai.traceable.agent.config.v1.MetricsConfig - (*RateLimitConfig)(nil), // 17: ai.traceable.agent.config.v1.RateLimitConfig - (*wrapperspb.BoolValue)(nil), // 18: google.protobuf.BoolValue - (*wrapperspb.StringValue)(nil), // 19: google.protobuf.StringValue - (*wrapperspb.Int32Value)(nil), // 20: google.protobuf.Int32Value - (*wrapperspb.Int64Value)(nil), // 21: google.protobuf.Int64Value + (PropagationFormat)(0), // 3: ai.traceable.agent.config.v1.PropagationFormat + (TraceReporterType)(0), // 4: ai.traceable.agent.config.v1.TraceReporterType + (MetricReporterType)(0), // 5: ai.traceable.agent.config.v1.MetricReporterType + (*AgentConfig)(nil), // 6: ai.traceable.agent.config.v1.AgentConfig + (*Reporting)(nil), // 7: ai.traceable.agent.config.v1.Reporting + (*Opa)(nil), // 8: ai.traceable.agent.config.v1.Opa + (*BlockingConfig)(nil), // 9: ai.traceable.agent.config.v1.BlockingConfig + (*ModsecurityConfig)(nil), // 10: ai.traceable.agent.config.v1.ModsecurityConfig + (*RegionBlockingConfig)(nil), // 11: ai.traceable.agent.config.v1.RegionBlockingConfig + (*RemoteConfig)(nil), // 12: ai.traceable.agent.config.v1.RemoteConfig + (*ApiDiscoveryConfig)(nil), // 13: ai.traceable.agent.config.v1.ApiDiscoveryConfig + (*SamplingConfig)(nil), // 14: ai.traceable.agent.config.v1.SamplingConfig + (*Javaagent)(nil), // 15: ai.traceable.agent.config.v1.Javaagent + (*LogConfig)(nil), // 16: ai.traceable.agent.config.v1.LogConfig + (*LogFileConfig)(nil), // 17: ai.traceable.agent.config.v1.LogFileConfig + (*MetricsLogConfig)(nil), // 18: ai.traceable.agent.config.v1.MetricsLogConfig + (*EndpointMetricsConfig)(nil), // 19: ai.traceable.agent.config.v1.EndpointMetricsConfig + (*MetricsConfig)(nil), // 20: ai.traceable.agent.config.v1.MetricsConfig + (*RateLimitConfig)(nil), // 21: ai.traceable.agent.config.v1.RateLimitConfig + (*Message)(nil), // 22: ai.traceable.agent.config.v1.Message + (*DataCapture)(nil), // 23: ai.traceable.agent.config.v1.DataCapture + (*GoAgent)(nil), // 24: ai.traceable.agent.config.v1.GoAgent + (*Telemetry)(nil), // 25: ai.traceable.agent.config.v1.Telemetry + nil, // 26: ai.traceable.agent.config.v1.AgentConfig.ResourceAttributesEntry + (*wrapperspb.BoolValue)(nil), // 27: google.protobuf.BoolValue + (*wrapperspb.StringValue)(nil), // 28: google.protobuf.StringValue + (*wrapperspb.Int32Value)(nil), // 29: google.protobuf.Int32Value + (*wrapperspb.Int64Value)(nil), // 30: google.protobuf.Int64Value } var file_ai_traceable_agent_config_v1_config_proto_depIdxs = []int32{ - 4, // 0: ai.traceable.agent.config.v1.AgentConfig.opa:type_name -> ai.traceable.agent.config.v1.Opa - 5, // 1: ai.traceable.agent.config.v1.AgentConfig.blocking_config:type_name -> ai.traceable.agent.config.v1.BlockingConfig - 18, // 2: ai.traceable.agent.config.v1.AgentConfig.debug_log:type_name -> google.protobuf.BoolValue - 8, // 3: ai.traceable.agent.config.v1.AgentConfig.remote_config:type_name -> ai.traceable.agent.config.v1.RemoteConfig - 9, // 4: ai.traceable.agent.config.v1.AgentConfig.api_discovery:type_name -> ai.traceable.agent.config.v1.ApiDiscoveryConfig - 10, // 5: ai.traceable.agent.config.v1.AgentConfig.sampling:type_name -> ai.traceable.agent.config.v1.SamplingConfig - 11, // 6: ai.traceable.agent.config.v1.AgentConfig.javaagent:type_name -> ai.traceable.agent.config.v1.Javaagent - 12, // 7: ai.traceable.agent.config.v1.AgentConfig.logging:type_name -> ai.traceable.agent.config.v1.LogConfig - 16, // 8: ai.traceable.agent.config.v1.AgentConfig.metrics_config:type_name -> ai.traceable.agent.config.v1.MetricsConfig - 19, // 9: ai.traceable.agent.config.v1.AgentConfig.environment:type_name -> google.protobuf.StringValue - 18, // 10: ai.traceable.agent.config.v1.Opa.enabled:type_name -> google.protobuf.BoolValue - 19, // 11: ai.traceable.agent.config.v1.Opa.endpoint:type_name -> google.protobuf.StringValue - 20, // 12: ai.traceable.agent.config.v1.Opa.poll_period_seconds:type_name -> google.protobuf.Int32Value - 19, // 13: ai.traceable.agent.config.v1.Opa.cert_file:type_name -> google.protobuf.StringValue - 18, // 14: ai.traceable.agent.config.v1.Opa.use_secure_connection:type_name -> google.protobuf.BoolValue - 18, // 15: ai.traceable.agent.config.v1.BlockingConfig.enabled:type_name -> google.protobuf.BoolValue - 18, // 16: ai.traceable.agent.config.v1.BlockingConfig.debug_log:type_name -> google.protobuf.BoolValue - 6, // 17: ai.traceable.agent.config.v1.BlockingConfig.modsecurity:type_name -> ai.traceable.agent.config.v1.ModsecurityConfig - 18, // 18: ai.traceable.agent.config.v1.BlockingConfig.evaluate_body:type_name -> google.protobuf.BoolValue - 7, // 19: ai.traceable.agent.config.v1.BlockingConfig.region_blocking:type_name -> ai.traceable.agent.config.v1.RegionBlockingConfig - 8, // 20: ai.traceable.agent.config.v1.BlockingConfig.remote_config:type_name -> ai.traceable.agent.config.v1.RemoteConfig - 18, // 21: ai.traceable.agent.config.v1.BlockingConfig.skip_internal_request:type_name -> google.protobuf.BoolValue - 20, // 22: ai.traceable.agent.config.v1.BlockingConfig.response_status_code:type_name -> google.protobuf.Int32Value - 20, // 23: ai.traceable.agent.config.v1.BlockingConfig.max_recursion_depth:type_name -> google.protobuf.Int32Value - 19, // 24: ai.traceable.agent.config.v1.BlockingConfig.response_message:type_name -> google.protobuf.StringValue - 18, // 25: ai.traceable.agent.config.v1.ModsecurityConfig.enabled:type_name -> google.protobuf.BoolValue - 18, // 26: ai.traceable.agent.config.v1.RegionBlockingConfig.enabled:type_name -> google.protobuf.BoolValue - 18, // 27: ai.traceable.agent.config.v1.RemoteConfig.enabled:type_name -> google.protobuf.BoolValue - 19, // 28: ai.traceable.agent.config.v1.RemoteConfig.endpoint:type_name -> google.protobuf.StringValue - 20, // 29: ai.traceable.agent.config.v1.RemoteConfig.poll_period_seconds:type_name -> google.protobuf.Int32Value - 19, // 30: ai.traceable.agent.config.v1.RemoteConfig.cert_file:type_name -> google.protobuf.StringValue - 20, // 31: ai.traceable.agent.config.v1.RemoteConfig.grpc_max_call_recv_msg_size:type_name -> google.protobuf.Int32Value - 18, // 32: ai.traceable.agent.config.v1.RemoteConfig.use_secure_connection:type_name -> google.protobuf.BoolValue - 18, // 33: ai.traceable.agent.config.v1.ApiDiscoveryConfig.enabled:type_name -> google.protobuf.BoolValue - 18, // 34: ai.traceable.agent.config.v1.SamplingConfig.enabled:type_name -> google.protobuf.BoolValue - 17, // 35: ai.traceable.agent.config.v1.SamplingConfig.default_rate_limit_config:type_name -> ai.traceable.agent.config.v1.RateLimitConfig - 18, // 36: ai.traceable.agent.config.v1.Javaagent.import_jks_certs:type_name -> google.protobuf.BoolValue - 0, // 37: ai.traceable.agent.config.v1.LogConfig.log_mode:type_name -> ai.traceable.agent.config.v1.LogMode - 1, // 38: ai.traceable.agent.config.v1.LogConfig.log_level:type_name -> ai.traceable.agent.config.v1.LogLevel - 13, // 39: ai.traceable.agent.config.v1.LogConfig.log_file:type_name -> ai.traceable.agent.config.v1.LogFileConfig - 20, // 40: ai.traceable.agent.config.v1.LogFileConfig.max_files:type_name -> google.protobuf.Int32Value - 20, // 41: ai.traceable.agent.config.v1.LogFileConfig.max_file_size:type_name -> google.protobuf.Int32Value - 19, // 42: ai.traceable.agent.config.v1.LogFileConfig.file_path:type_name -> google.protobuf.StringValue - 18, // 43: ai.traceable.agent.config.v1.MetricsLogConfig.enabled:type_name -> google.protobuf.BoolValue - 19, // 44: ai.traceable.agent.config.v1.MetricsLogConfig.frequency:type_name -> google.protobuf.StringValue - 18, // 45: ai.traceable.agent.config.v1.EndpointMetricsConfig.enabled:type_name -> google.protobuf.BoolValue - 20, // 46: ai.traceable.agent.config.v1.EndpointMetricsConfig.max_endpoints:type_name -> google.protobuf.Int32Value - 14, // 47: ai.traceable.agent.config.v1.EndpointMetricsConfig.logging:type_name -> ai.traceable.agent.config.v1.MetricsLogConfig - 18, // 48: ai.traceable.agent.config.v1.MetricsConfig.enabled:type_name -> google.protobuf.BoolValue - 15, // 49: ai.traceable.agent.config.v1.MetricsConfig.endpoint_config:type_name -> ai.traceable.agent.config.v1.EndpointMetricsConfig - 14, // 50: ai.traceable.agent.config.v1.MetricsConfig.logging:type_name -> ai.traceable.agent.config.v1.MetricsLogConfig - 18, // 51: ai.traceable.agent.config.v1.RateLimitConfig.enabled:type_name -> google.protobuf.BoolValue - 21, // 52: ai.traceable.agent.config.v1.RateLimitConfig.max_count_global:type_name -> google.protobuf.Int64Value - 21, // 53: ai.traceable.agent.config.v1.RateLimitConfig.max_count_per_endpoint:type_name -> google.protobuf.Int64Value - 19, // 54: ai.traceable.agent.config.v1.RateLimitConfig.refresh_period:type_name -> google.protobuf.StringValue - 19, // 55: ai.traceable.agent.config.v1.RateLimitConfig.value_expiration_period:type_name -> google.protobuf.StringValue - 2, // 56: ai.traceable.agent.config.v1.RateLimitConfig.span_type:type_name -> ai.traceable.agent.config.v1.SpanType - 57, // [57:57] is the sub-list for method output_type - 57, // [57:57] is the sub-list for method input_type - 57, // [57:57] is the sub-list for extension type_name - 57, // [57:57] is the sub-list for extension extendee - 0, // [0:57] is the sub-list for field type_name + 8, // 0: ai.traceable.agent.config.v1.AgentConfig.opa:type_name -> ai.traceable.agent.config.v1.Opa + 9, // 1: ai.traceable.agent.config.v1.AgentConfig.blocking_config:type_name -> ai.traceable.agent.config.v1.BlockingConfig + 27, // 2: ai.traceable.agent.config.v1.AgentConfig.debug_log:type_name -> google.protobuf.BoolValue + 12, // 3: ai.traceable.agent.config.v1.AgentConfig.remote_config:type_name -> ai.traceable.agent.config.v1.RemoteConfig + 13, // 4: ai.traceable.agent.config.v1.AgentConfig.api_discovery:type_name -> ai.traceable.agent.config.v1.ApiDiscoveryConfig + 14, // 5: ai.traceable.agent.config.v1.AgentConfig.sampling:type_name -> ai.traceable.agent.config.v1.SamplingConfig + 15, // 6: ai.traceable.agent.config.v1.AgentConfig.javaagent:type_name -> ai.traceable.agent.config.v1.Javaagent + 16, // 7: ai.traceable.agent.config.v1.AgentConfig.logging:type_name -> ai.traceable.agent.config.v1.LogConfig + 20, // 8: ai.traceable.agent.config.v1.AgentConfig.metrics_config:type_name -> ai.traceable.agent.config.v1.MetricsConfig + 28, // 9: ai.traceable.agent.config.v1.AgentConfig.environment:type_name -> google.protobuf.StringValue + 28, // 10: ai.traceable.agent.config.v1.AgentConfig.service_name:type_name -> google.protobuf.StringValue + 7, // 11: ai.traceable.agent.config.v1.AgentConfig.reporting:type_name -> ai.traceable.agent.config.v1.Reporting + 23, // 12: ai.traceable.agent.config.v1.AgentConfig.data_capture:type_name -> ai.traceable.agent.config.v1.DataCapture + 3, // 13: ai.traceable.agent.config.v1.AgentConfig.propagation_formats:type_name -> ai.traceable.agent.config.v1.PropagationFormat + 27, // 14: ai.traceable.agent.config.v1.AgentConfig.enabled:type_name -> google.protobuf.BoolValue + 26, // 15: ai.traceable.agent.config.v1.AgentConfig.resource_attributes:type_name -> ai.traceable.agent.config.v1.AgentConfig.ResourceAttributesEntry + 25, // 16: ai.traceable.agent.config.v1.AgentConfig.telemetry:type_name -> ai.traceable.agent.config.v1.Telemetry + 24, // 17: ai.traceable.agent.config.v1.AgentConfig.goagent:type_name -> ai.traceable.agent.config.v1.GoAgent + 28, // 18: ai.traceable.agent.config.v1.Reporting.endpoint:type_name -> google.protobuf.StringValue + 27, // 19: ai.traceable.agent.config.v1.Reporting.secure:type_name -> google.protobuf.BoolValue + 28, // 20: ai.traceable.agent.config.v1.Reporting.token:type_name -> google.protobuf.StringValue + 4, // 21: ai.traceable.agent.config.v1.Reporting.trace_reporter_type:type_name -> ai.traceable.agent.config.v1.TraceReporterType + 28, // 22: ai.traceable.agent.config.v1.Reporting.cert_file:type_name -> google.protobuf.StringValue + 28, // 23: ai.traceable.agent.config.v1.Reporting.metric_endpoint:type_name -> google.protobuf.StringValue + 5, // 24: ai.traceable.agent.config.v1.Reporting.metric_reporter_type:type_name -> ai.traceable.agent.config.v1.MetricReporterType + 27, // 25: ai.traceable.agent.config.v1.Reporting.enable_grpc_loadbalancing:type_name -> google.protobuf.BoolValue + 27, // 26: ai.traceable.agent.config.v1.Opa.enabled:type_name -> google.protobuf.BoolValue + 28, // 27: ai.traceable.agent.config.v1.Opa.endpoint:type_name -> google.protobuf.StringValue + 29, // 28: ai.traceable.agent.config.v1.Opa.poll_period_seconds:type_name -> google.protobuf.Int32Value + 28, // 29: ai.traceable.agent.config.v1.Opa.cert_file:type_name -> google.protobuf.StringValue + 27, // 30: ai.traceable.agent.config.v1.Opa.use_secure_connection:type_name -> google.protobuf.BoolValue + 27, // 31: ai.traceable.agent.config.v1.BlockingConfig.enabled:type_name -> google.protobuf.BoolValue + 27, // 32: ai.traceable.agent.config.v1.BlockingConfig.debug_log:type_name -> google.protobuf.BoolValue + 10, // 33: ai.traceable.agent.config.v1.BlockingConfig.modsecurity:type_name -> ai.traceable.agent.config.v1.ModsecurityConfig + 27, // 34: ai.traceable.agent.config.v1.BlockingConfig.evaluate_body:type_name -> google.protobuf.BoolValue + 11, // 35: ai.traceable.agent.config.v1.BlockingConfig.region_blocking:type_name -> ai.traceable.agent.config.v1.RegionBlockingConfig + 12, // 36: ai.traceable.agent.config.v1.BlockingConfig.remote_config:type_name -> ai.traceable.agent.config.v1.RemoteConfig + 27, // 37: ai.traceable.agent.config.v1.BlockingConfig.skip_internal_request:type_name -> google.protobuf.BoolValue + 29, // 38: ai.traceable.agent.config.v1.BlockingConfig.response_status_code:type_name -> google.protobuf.Int32Value + 29, // 39: ai.traceable.agent.config.v1.BlockingConfig.max_recursion_depth:type_name -> google.protobuf.Int32Value + 28, // 40: ai.traceable.agent.config.v1.BlockingConfig.response_message:type_name -> google.protobuf.StringValue + 27, // 41: ai.traceable.agent.config.v1.ModsecurityConfig.enabled:type_name -> google.protobuf.BoolValue + 27, // 42: ai.traceable.agent.config.v1.RegionBlockingConfig.enabled:type_name -> google.protobuf.BoolValue + 27, // 43: ai.traceable.agent.config.v1.RemoteConfig.enabled:type_name -> google.protobuf.BoolValue + 28, // 44: ai.traceable.agent.config.v1.RemoteConfig.endpoint:type_name -> google.protobuf.StringValue + 29, // 45: ai.traceable.agent.config.v1.RemoteConfig.poll_period_seconds:type_name -> google.protobuf.Int32Value + 28, // 46: ai.traceable.agent.config.v1.RemoteConfig.cert_file:type_name -> google.protobuf.StringValue + 29, // 47: ai.traceable.agent.config.v1.RemoteConfig.grpc_max_call_recv_msg_size:type_name -> google.protobuf.Int32Value + 27, // 48: ai.traceable.agent.config.v1.RemoteConfig.use_secure_connection:type_name -> google.protobuf.BoolValue + 27, // 49: ai.traceable.agent.config.v1.ApiDiscoveryConfig.enabled:type_name -> google.protobuf.BoolValue + 27, // 50: ai.traceable.agent.config.v1.SamplingConfig.enabled:type_name -> google.protobuf.BoolValue + 21, // 51: ai.traceable.agent.config.v1.SamplingConfig.default_rate_limit_config:type_name -> ai.traceable.agent.config.v1.RateLimitConfig + 27, // 52: ai.traceable.agent.config.v1.Javaagent.import_jks_certs:type_name -> google.protobuf.BoolValue + 28, // 53: ai.traceable.agent.config.v1.Javaagent.filter_jar_paths:type_name -> google.protobuf.StringValue + 0, // 54: ai.traceable.agent.config.v1.LogConfig.log_mode:type_name -> ai.traceable.agent.config.v1.LogMode + 1, // 55: ai.traceable.agent.config.v1.LogConfig.log_level:type_name -> ai.traceable.agent.config.v1.LogLevel + 17, // 56: ai.traceable.agent.config.v1.LogConfig.log_file:type_name -> ai.traceable.agent.config.v1.LogFileConfig + 29, // 57: ai.traceable.agent.config.v1.LogFileConfig.max_files:type_name -> google.protobuf.Int32Value + 29, // 58: ai.traceable.agent.config.v1.LogFileConfig.max_file_size:type_name -> google.protobuf.Int32Value + 28, // 59: ai.traceable.agent.config.v1.LogFileConfig.file_path:type_name -> google.protobuf.StringValue + 27, // 60: ai.traceable.agent.config.v1.MetricsLogConfig.enabled:type_name -> google.protobuf.BoolValue + 28, // 61: ai.traceable.agent.config.v1.MetricsLogConfig.frequency:type_name -> google.protobuf.StringValue + 27, // 62: ai.traceable.agent.config.v1.EndpointMetricsConfig.enabled:type_name -> google.protobuf.BoolValue + 29, // 63: ai.traceable.agent.config.v1.EndpointMetricsConfig.max_endpoints:type_name -> google.protobuf.Int32Value + 18, // 64: ai.traceable.agent.config.v1.EndpointMetricsConfig.logging:type_name -> ai.traceable.agent.config.v1.MetricsLogConfig + 27, // 65: ai.traceable.agent.config.v1.MetricsConfig.enabled:type_name -> google.protobuf.BoolValue + 19, // 66: ai.traceable.agent.config.v1.MetricsConfig.endpoint_config:type_name -> ai.traceable.agent.config.v1.EndpointMetricsConfig + 18, // 67: ai.traceable.agent.config.v1.MetricsConfig.logging:type_name -> ai.traceable.agent.config.v1.MetricsLogConfig + 27, // 68: ai.traceable.agent.config.v1.RateLimitConfig.enabled:type_name -> google.protobuf.BoolValue + 30, // 69: ai.traceable.agent.config.v1.RateLimitConfig.max_count_global:type_name -> google.protobuf.Int64Value + 30, // 70: ai.traceable.agent.config.v1.RateLimitConfig.max_count_per_endpoint:type_name -> google.protobuf.Int64Value + 28, // 71: ai.traceable.agent.config.v1.RateLimitConfig.refresh_period:type_name -> google.protobuf.StringValue + 28, // 72: ai.traceable.agent.config.v1.RateLimitConfig.value_expiration_period:type_name -> google.protobuf.StringValue + 2, // 73: ai.traceable.agent.config.v1.RateLimitConfig.span_type:type_name -> ai.traceable.agent.config.v1.SpanType + 27, // 74: ai.traceable.agent.config.v1.Message.request:type_name -> google.protobuf.BoolValue + 27, // 75: ai.traceable.agent.config.v1.Message.response:type_name -> google.protobuf.BoolValue + 22, // 76: ai.traceable.agent.config.v1.DataCapture.http_headers:type_name -> ai.traceable.agent.config.v1.Message + 22, // 77: ai.traceable.agent.config.v1.DataCapture.http_body:type_name -> ai.traceable.agent.config.v1.Message + 22, // 78: ai.traceable.agent.config.v1.DataCapture.rpc_metadata:type_name -> ai.traceable.agent.config.v1.Message + 22, // 79: ai.traceable.agent.config.v1.DataCapture.rpc_body:type_name -> ai.traceable.agent.config.v1.Message + 29, // 80: ai.traceable.agent.config.v1.DataCapture.body_max_size_bytes:type_name -> google.protobuf.Int32Value + 29, // 81: ai.traceable.agent.config.v1.DataCapture.body_max_processing_size_bytes:type_name -> google.protobuf.Int32Value + 28, // 82: ai.traceable.agent.config.v1.DataCapture.allowed_content_types:type_name -> google.protobuf.StringValue + 27, // 83: ai.traceable.agent.config.v1.GoAgent.use_custom_bsp:type_name -> google.protobuf.BoolValue + 27, // 84: ai.traceable.agent.config.v1.Telemetry.startup_span_enabled:type_name -> google.protobuf.BoolValue + 27, // 85: ai.traceable.agent.config.v1.Telemetry.metrics_enabled:type_name -> google.protobuf.BoolValue + 86, // [86:86] is the sub-list for method output_type + 86, // [86:86] is the sub-list for method input_type + 86, // [86:86] is the sub-list for extension type_name + 86, // [86:86] is the sub-list for extension extendee + 0, // [0:86] is the sub-list for field type_name } func init() { file_ai_traceable_agent_config_v1_config_proto_init() } @@ -1710,7 +2571,7 @@ func file_ai_traceable_agent_config_v1_config_proto_init() { } } file_ai_traceable_agent_config_v1_config_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Opa); i { + switch v := v.(*Reporting); i { case 0: return &v.state case 1: @@ -1722,7 +2583,7 @@ func file_ai_traceable_agent_config_v1_config_proto_init() { } } file_ai_traceable_agent_config_v1_config_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*BlockingConfig); i { + switch v := v.(*Opa); i { case 0: return &v.state case 1: @@ -1734,7 +2595,7 @@ func file_ai_traceable_agent_config_v1_config_proto_init() { } } file_ai_traceable_agent_config_v1_config_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ModsecurityConfig); i { + switch v := v.(*BlockingConfig); i { case 0: return &v.state case 1: @@ -1746,7 +2607,7 @@ func file_ai_traceable_agent_config_v1_config_proto_init() { } } file_ai_traceable_agent_config_v1_config_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*RegionBlockingConfig); i { + switch v := v.(*ModsecurityConfig); i { case 0: return &v.state case 1: @@ -1758,7 +2619,7 @@ func file_ai_traceable_agent_config_v1_config_proto_init() { } } file_ai_traceable_agent_config_v1_config_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*RemoteConfig); i { + switch v := v.(*RegionBlockingConfig); i { case 0: return &v.state case 1: @@ -1770,7 +2631,7 @@ func file_ai_traceable_agent_config_v1_config_proto_init() { } } file_ai_traceable_agent_config_v1_config_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ApiDiscoveryConfig); i { + switch v := v.(*RemoteConfig); i { case 0: return &v.state case 1: @@ -1782,7 +2643,7 @@ func file_ai_traceable_agent_config_v1_config_proto_init() { } } file_ai_traceable_agent_config_v1_config_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*SamplingConfig); i { + switch v := v.(*ApiDiscoveryConfig); i { case 0: return &v.state case 1: @@ -1794,7 +2655,7 @@ func file_ai_traceable_agent_config_v1_config_proto_init() { } } file_ai_traceable_agent_config_v1_config_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Javaagent); i { + switch v := v.(*SamplingConfig); i { case 0: return &v.state case 1: @@ -1806,7 +2667,7 @@ func file_ai_traceable_agent_config_v1_config_proto_init() { } } file_ai_traceable_agent_config_v1_config_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*LogConfig); i { + switch v := v.(*Javaagent); i { case 0: return &v.state case 1: @@ -1818,7 +2679,7 @@ func file_ai_traceable_agent_config_v1_config_proto_init() { } } file_ai_traceable_agent_config_v1_config_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*LogFileConfig); i { + switch v := v.(*LogConfig); i { case 0: return &v.state case 1: @@ -1830,7 +2691,7 @@ func file_ai_traceable_agent_config_v1_config_proto_init() { } } file_ai_traceable_agent_config_v1_config_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*MetricsLogConfig); i { + switch v := v.(*LogFileConfig); i { case 0: return &v.state case 1: @@ -1842,7 +2703,7 @@ func file_ai_traceable_agent_config_v1_config_proto_init() { } } file_ai_traceable_agent_config_v1_config_proto_msgTypes[12].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*EndpointMetricsConfig); i { + switch v := v.(*MetricsLogConfig); i { case 0: return &v.state case 1: @@ -1854,7 +2715,7 @@ func file_ai_traceable_agent_config_v1_config_proto_init() { } } file_ai_traceable_agent_config_v1_config_proto_msgTypes[13].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*MetricsConfig); i { + switch v := v.(*EndpointMetricsConfig); i { case 0: return &v.state case 1: @@ -1866,6 +2727,18 @@ func file_ai_traceable_agent_config_v1_config_proto_init() { } } file_ai_traceable_agent_config_v1_config_proto_msgTypes[14].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*MetricsConfig); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_ai_traceable_agent_config_v1_config_proto_msgTypes[15].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*RateLimitConfig); i { case 0: return &v.state @@ -1877,14 +2750,62 @@ func file_ai_traceable_agent_config_v1_config_proto_init() { return nil } } + file_ai_traceable_agent_config_v1_config_proto_msgTypes[16].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Message); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_ai_traceable_agent_config_v1_config_proto_msgTypes[17].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*DataCapture); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_ai_traceable_agent_config_v1_config_proto_msgTypes[18].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GoAgent); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_ai_traceable_agent_config_v1_config_proto_msgTypes[19].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Telemetry); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_ai_traceable_agent_config_v1_config_proto_rawDesc, - NumEnums: 3, - NumMessages: 15, + NumEnums: 6, + NumMessages: 21, NumExtensions: 0, NumServices: 0, }, diff --git a/gen/go/v1/config.pbloader.go b/gen/go/v1/config.pbloader.go index f018ef2..193bcf8 100644 --- a/gen/go/v1/config.pbloader.go +++ b/gen/go/v1/config.pbloader.go @@ -98,6 +98,173 @@ func (x *AgentConfig) loadFromEnv(prefix string, defaultValues *AgentConfig) { x.Environment = &wrappers.StringValue{Value: defaultValues.Environment.Value} } } + if val, ok := getStringEnv(prefix + "SERVICE_NAME"); ok { + x.ServiceName = &wrappers.StringValue{Value: val} + } else if x.ServiceName == nil { + // when there is no value to set we still prefer to initialize the variable to avoid + // `nil` checks in the consumers. + x.ServiceName = new(wrappers.StringValue) + if defaultValues != nil && defaultValues.ServiceName != nil { + x.ServiceName = &wrappers.StringValue{Value: defaultValues.ServiceName.Value} + } + } + if x.Reporting == nil { + x.Reporting = new(Reporting) + } + if defaultValues == nil { + x.Reporting.loadFromEnv(prefix+"REPORTING_", nil) + } else { + x.Reporting.loadFromEnv(prefix+"REPORTING_", defaultValues.Reporting) + } + + if x.DataCapture == nil { + x.DataCapture = new(DataCapture) + } + if defaultValues == nil { + x.DataCapture.loadFromEnv(prefix+"DATA_CAPTURE_", nil) + } else { + x.DataCapture.loadFromEnv(prefix+"DATA_CAPTURE_", defaultValues.DataCapture) + } + + if rawVals, ok := getArrayStringEnv(prefix + "PROPAGATION_FORMATS"); ok { + vals := []PropagationFormat{} + for _, rawVal := range rawVals { + vals = append(vals, PropagationFormat(PropagationFormat_value[rawVal])) + } + x.PropagationFormats = vals + } else if len(x.PropagationFormats) == 0 && defaultValues != nil && len(defaultValues.PropagationFormats) > 0 { + x.PropagationFormats = defaultValues.PropagationFormats + } + + if val, ok := getBoolEnv(prefix + "ENABLED"); ok { + x.Enabled = &wrappers.BoolValue{Value: val} + } else if x.Enabled == nil { + // when there is no value to set we still prefer to initialize the variable to avoid + // `nil` checks in the consumers. + x.Enabled = new(wrappers.BoolValue) + if defaultValues != nil && defaultValues.Enabled != nil { + x.Enabled = &wrappers.BoolValue{Value: defaultValues.Enabled.Value} + } + } + if defaultValues != nil && len(defaultValues.ResourceAttributes) > 0 { + if x.ResourceAttributes == nil { + x.ResourceAttributes = make(map[string]string) + } + for k, v := range defaultValues.ResourceAttributes { + // defaults should not override existing resource attributes unless empty + if _, ok := x.ResourceAttributes[k]; !ok { + x.ResourceAttributes[k] = v + } + } + } + + if x.Telemetry == nil { + x.Telemetry = new(Telemetry) + } + if defaultValues == nil { + x.Telemetry.loadFromEnv(prefix+"TELEMETRY_", nil) + } else { + x.Telemetry.loadFromEnv(prefix+"TELEMETRY_", defaultValues.Telemetry) + } + + if x.Goagent == nil { + x.Goagent = new(GoAgent) + } + if defaultValues == nil { + x.Goagent.loadFromEnv(prefix+"GOAGENT_", nil) + } else { + x.Goagent.loadFromEnv(prefix+"GOAGENT_", defaultValues.Goagent) + } + +} + +// PutResourceAttributes sets values in the ResourceAttributes map. +func (x *AgentConfig) PutResourceAttributes(m map[string]string) { + if len(m) == 0 { + return + } + if x.ResourceAttributes == nil { + x.ResourceAttributes = make(map[string]string) + } + for k, v := range m { + x.ResourceAttributes[k] = v + } +} + +// loadFromEnv loads the data from env vars, defaults and makes sure all values are initialized. +func (x *Reporting) loadFromEnv(prefix string, defaultValues *Reporting) { + if val, ok := getStringEnv(prefix + "ENDPOINT"); ok { + x.Endpoint = &wrappers.StringValue{Value: val} + } else if x.Endpoint == nil { + // when there is no value to set we still prefer to initialize the variable to avoid + // `nil` checks in the consumers. + x.Endpoint = new(wrappers.StringValue) + if defaultValues != nil && defaultValues.Endpoint != nil { + x.Endpoint = &wrappers.StringValue{Value: defaultValues.Endpoint.Value} + } + } + if val, ok := getBoolEnv(prefix + "SECURE"); ok { + x.Secure = &wrappers.BoolValue{Value: val} + } else if x.Secure == nil { + // when there is no value to set we still prefer to initialize the variable to avoid + // `nil` checks in the consumers. + x.Secure = new(wrappers.BoolValue) + if defaultValues != nil && defaultValues.Secure != nil { + x.Secure = &wrappers.BoolValue{Value: defaultValues.Secure.Value} + } + } + if val, ok := getStringEnv(prefix + "TOKEN"); ok { + x.Token = &wrappers.StringValue{Value: val} + } else if x.Token == nil { + // when there is no value to set we still prefer to initialize the variable to avoid + // `nil` checks in the consumers. + x.Token = new(wrappers.StringValue) + if defaultValues != nil && defaultValues.Token != nil { + x.Token = &wrappers.StringValue{Value: defaultValues.Token.Value} + } + } + if rawVal, ok := getStringEnv(prefix + "TRACE_REPORTER_TYPE"); ok { + x.TraceReporterType = TraceReporterType(TraceReporterType_value[rawVal]) + } else if x.TraceReporterType == TraceReporterType(0) && defaultValues != nil && defaultValues.TraceReporterType != TraceReporterType(0) { + x.TraceReporterType = defaultValues.TraceReporterType + } + + if val, ok := getStringEnv(prefix + "CERT_FILE"); ok { + x.CertFile = &wrappers.StringValue{Value: val} + } else if x.CertFile == nil { + // when there is no value to set we still prefer to initialize the variable to avoid + // `nil` checks in the consumers. + x.CertFile = new(wrappers.StringValue) + if defaultValues != nil && defaultValues.CertFile != nil { + x.CertFile = &wrappers.StringValue{Value: defaultValues.CertFile.Value} + } + } + if val, ok := getStringEnv(prefix + "METRIC_ENDPOINT"); ok { + x.MetricEndpoint = &wrappers.StringValue{Value: val} + } else if x.MetricEndpoint == nil { + // when there is no value to set we still prefer to initialize the variable to avoid + // `nil` checks in the consumers. + x.MetricEndpoint = new(wrappers.StringValue) + if defaultValues != nil && defaultValues.MetricEndpoint != nil { + x.MetricEndpoint = &wrappers.StringValue{Value: defaultValues.MetricEndpoint.Value} + } + } + if rawVal, ok := getStringEnv(prefix + "METRIC_REPORTER_TYPE"); ok { + x.MetricReporterType = MetricReporterType(MetricReporterType_value[rawVal]) + } else if x.MetricReporterType == MetricReporterType(0) && defaultValues != nil && defaultValues.MetricReporterType != MetricReporterType(0) { + x.MetricReporterType = defaultValues.MetricReporterType + } + + if val, ok := getBoolEnv(prefix + "ENABLE_GRPC_LOADBALANCING"); ok { + x.EnableGrpcLoadbalancing = &wrappers.BoolValue{Value: val} + } else if x.EnableGrpcLoadbalancing == nil { + // when there is no value to set we still prefer to initialize the variable to avoid + // `nil` checks in the consumers. + x.EnableGrpcLoadbalancing = new(wrappers.BoolValue) + if defaultValues != nil && defaultValues.EnableGrpcLoadbalancing != nil { + x.EnableGrpcLoadbalancing = &wrappers.BoolValue{Value: defaultValues.EnableGrpcLoadbalancing.Value} + } + } } // loadFromEnv loads the data from env vars, defaults and makes sure all values are initialized. @@ -396,6 +563,14 @@ func (x *Javaagent) loadFromEnv(prefix string, defaultValues *Javaagent) { x.ImportJksCerts = &wrappers.BoolValue{Value: defaultValues.ImportJksCerts.Value} } } + if rawVals, ok := getArrayStringEnv(prefix + "FILTER_JAR_PATHS"); ok { + for _, val := range rawVals { + x.FilterJarPaths = append(x.FilterJarPaths, wrappers.String(val)) + } + } else if len(x.FilterJarPaths) == 0 && defaultValues != nil && len(defaultValues.FilterJarPaths) > 0 { + x.FilterJarPaths = defaultValues.FilterJarPaths + } + } // loadFromEnv loads the data from env vars, defaults and makes sure all values are initialized. @@ -605,3 +780,133 @@ func (x *RateLimitConfig) loadFromEnv(prefix string, defaultValues *RateLimitCon } } + +// loadFromEnv loads the data from env vars, defaults and makes sure all values are initialized. +func (x *Message) loadFromEnv(prefix string, defaultValues *Message) { + if val, ok := getBoolEnv(prefix + "REQUEST"); ok { + x.Request = &wrappers.BoolValue{Value: val} + } else if x.Request == nil { + // when there is no value to set we still prefer to initialize the variable to avoid + // `nil` checks in the consumers. + x.Request = new(wrappers.BoolValue) + if defaultValues != nil && defaultValues.Request != nil { + x.Request = &wrappers.BoolValue{Value: defaultValues.Request.Value} + } + } + if val, ok := getBoolEnv(prefix + "RESPONSE"); ok { + x.Response = &wrappers.BoolValue{Value: val} + } else if x.Response == nil { + // when there is no value to set we still prefer to initialize the variable to avoid + // `nil` checks in the consumers. + x.Response = new(wrappers.BoolValue) + if defaultValues != nil && defaultValues.Response != nil { + x.Response = &wrappers.BoolValue{Value: defaultValues.Response.Value} + } + } +} + +// loadFromEnv loads the data from env vars, defaults and makes sure all values are initialized. +func (x *DataCapture) loadFromEnv(prefix string, defaultValues *DataCapture) { + if x.HttpHeaders == nil { + x.HttpHeaders = new(Message) + } + if defaultValues == nil { + x.HttpHeaders.loadFromEnv(prefix+"HTTP_HEADERS_", nil) + } else { + x.HttpHeaders.loadFromEnv(prefix+"HTTP_HEADERS_", defaultValues.HttpHeaders) + } + + if x.HttpBody == nil { + x.HttpBody = new(Message) + } + if defaultValues == nil { + x.HttpBody.loadFromEnv(prefix+"HTTP_BODY_", nil) + } else { + x.HttpBody.loadFromEnv(prefix+"HTTP_BODY_", defaultValues.HttpBody) + } + + if x.RpcMetadata == nil { + x.RpcMetadata = new(Message) + } + if defaultValues == nil { + x.RpcMetadata.loadFromEnv(prefix+"RPC_METADATA_", nil) + } else { + x.RpcMetadata.loadFromEnv(prefix+"RPC_METADATA_", defaultValues.RpcMetadata) + } + + if x.RpcBody == nil { + x.RpcBody = new(Message) + } + if defaultValues == nil { + x.RpcBody.loadFromEnv(prefix+"RPC_BODY_", nil) + } else { + x.RpcBody.loadFromEnv(prefix+"RPC_BODY_", defaultValues.RpcBody) + } + + if val, ok := getInt32Env(prefix + "BODY_MAX_SIZE_BYTES"); ok { + x.BodyMaxSizeBytes = &wrappers.Int32Value{Value: val} + } else if x.BodyMaxSizeBytes == nil { + // when there is no value to set we still prefer to initialize the variable to avoid + // `nil` checks in the consumers. + x.BodyMaxSizeBytes = new(wrappers.Int32Value) + if defaultValues != nil && defaultValues.BodyMaxSizeBytes != nil { + x.BodyMaxSizeBytes = &wrappers.Int32Value{Value: defaultValues.BodyMaxSizeBytes.Value} + } + } + if val, ok := getInt32Env(prefix + "BODY_MAX_PROCESSING_SIZE_BYTES"); ok { + x.BodyMaxProcessingSizeBytes = &wrappers.Int32Value{Value: val} + } else if x.BodyMaxProcessingSizeBytes == nil { + // when there is no value to set we still prefer to initialize the variable to avoid + // `nil` checks in the consumers. + x.BodyMaxProcessingSizeBytes = new(wrappers.Int32Value) + if defaultValues != nil && defaultValues.BodyMaxProcessingSizeBytes != nil { + x.BodyMaxProcessingSizeBytes = &wrappers.Int32Value{Value: defaultValues.BodyMaxProcessingSizeBytes.Value} + } + } + if rawVals, ok := getArrayStringEnv(prefix + "ALLOWED_CONTENT_TYPES"); ok { + for _, val := range rawVals { + x.AllowedContentTypes = append(x.AllowedContentTypes, wrappers.String(val)) + } + } else if len(x.AllowedContentTypes) == 0 && defaultValues != nil && len(defaultValues.AllowedContentTypes) > 0 { + x.AllowedContentTypes = defaultValues.AllowedContentTypes + } + +} + +// loadFromEnv loads the data from env vars, defaults and makes sure all values are initialized. +func (x *GoAgent) loadFromEnv(prefix string, defaultValues *GoAgent) { + if val, ok := getBoolEnv(prefix + "USE_CUSTOM_BSP"); ok { + x.UseCustomBsp = &wrappers.BoolValue{Value: val} + } else if x.UseCustomBsp == nil { + // when there is no value to set we still prefer to initialize the variable to avoid + // `nil` checks in the consumers. + x.UseCustomBsp = new(wrappers.BoolValue) + if defaultValues != nil && defaultValues.UseCustomBsp != nil { + x.UseCustomBsp = &wrappers.BoolValue{Value: defaultValues.UseCustomBsp.Value} + } + } +} + +// loadFromEnv loads the data from env vars, defaults and makes sure all values are initialized. +func (x *Telemetry) loadFromEnv(prefix string, defaultValues *Telemetry) { + if val, ok := getBoolEnv(prefix + "STARTUP_SPAN_ENABLED"); ok { + x.StartupSpanEnabled = &wrappers.BoolValue{Value: val} + } else if x.StartupSpanEnabled == nil { + // when there is no value to set we still prefer to initialize the variable to avoid + // `nil` checks in the consumers. + x.StartupSpanEnabled = new(wrappers.BoolValue) + if defaultValues != nil && defaultValues.StartupSpanEnabled != nil { + x.StartupSpanEnabled = &wrappers.BoolValue{Value: defaultValues.StartupSpanEnabled.Value} + } + } + if val, ok := getBoolEnv(prefix + "METRICS_ENABLED"); ok { + x.MetricsEnabled = &wrappers.BoolValue{Value: val} + } else if x.MetricsEnabled == nil { + // when there is no value to set we still prefer to initialize the variable to avoid + // `nil` checks in the consumers. + x.MetricsEnabled = new(wrappers.BoolValue) + if defaultValues != nil && defaultValues.MetricsEnabled != nil { + x.MetricsEnabled = &wrappers.BoolValue{Value: defaultValues.MetricsEnabled.Value} + } + } +} diff --git a/proto/ai/traceable/agent/config/v1/config.proto b/proto/ai/traceable/agent/config/v1/config.proto index e3c9b87..ef42343 100644 --- a/proto/ai/traceable/agent/config/v1/config.proto +++ b/proto/ai/traceable/agent/config/v1/config.proto @@ -20,6 +20,64 @@ message AgentConfig { MetricsConfig metrics_config = 9; // represents the environment name of agent google.protobuf.StringValue environment = 10; + + // From HT config + google.protobuf.StringValue service_name = 11; + + // reporting holds the reporting settings for the agent + Reporting reporting = 12; + + // data_capture describes the data being captured by instrumentation + DataCapture data_capture = 13; + + // propagation_formats list the supported propagation formats + repeated PropagationFormat propagation_formats = 14; + + // when `false`, disables the agent + google.protobuf.BoolValue enabled = 15; + + // resource_attributes map define the static list of resources which is configured on the tracer + map resource_attributes = 16; + + // telemetry + Telemetry telemetry = 17; + + // Goagent specific config + GoAgent goagent = 18; + +} + +// Reporting covers the options related to the mechanics for sending data to the +// tracing server o collector. +message Reporting { + // endpoint represents the endpoint for reporting the traces + // For ZIPKIN reporter type use http://api.traceable.ai:9411/api/v2/spans + // For OTLP reporter type use http://api.traceable.ai:4317 + google.protobuf.StringValue endpoint = 1; + + // when `true`, connects to endpoints over TLS. + google.protobuf.BoolValue secure = 2; + + // user specific token to access Traceable API + google.protobuf.StringValue token = 3; + + // reporter type for traces. + TraceReporterType trace_reporter_type = 5; + + // Certificate file containing the CA to verify the server's certificate. + // This is for private certificates. + // If this is set then `secure` above should also be set to `true`. + google.protobuf.StringValue cert_file = 6; + + // metric_endpoint represents the endpoint for reporting the metrics. + // For OTLP metric reporter type use http://api.traceable.ai:4317 + google.protobuf.StringValue metric_endpoint = 7; + + // reporter type for metrics. + MetricReporterType metric_reporter_type = 8; + + // When `true`, modifies grpc resolver to use dns instead of passthrough and configure round robin client side loadbalancing + google.protobuf.BoolValue enable_grpc_loadbalancing = 9; } // Opa covers the options related to the mechanics for getting Open Policy Agent configuration file. @@ -101,6 +159,7 @@ message SamplingConfig { message Javaagent { // set this flag to export certificates configured in JKS to libtraceable for making HTTPS connection to TPA. google.protobuf.BoolValue import_jks_certs = 1; + repeated google.protobuf.StringValue filter_jar_paths = 2; } enum LogMode { @@ -182,3 +241,120 @@ message RateLimitConfig { // set the span type for rate limited spans SpanType span_type = 6; } + +// Message describes what message should be considered for certain DataCapture option +message Message { + // when `false` it disables the capture for the request in a client/request operation + google.protobuf.BoolValue request = 1; + + // when `false` it disables the capture for the response in a client/request operation + google.protobuf.BoolValue response = 2; +} + +// DataCapture describes the elements to be captured by the agent instrumentation +message DataCapture { + // http_headers enables/disables the capture of the request/response headers in HTTP + Message http_headers = 1; + + // http_body enables/disables the capture of the request/response body in HTTP + Message http_body = 2; + + // rpc_metadata enables/disables the capture of the request/response metadata in RPC + Message rpc_metadata = 3; + + // rpc_body enables/disables the capture of the request/response body in RPC + Message rpc_body = 4; + + // body_max_size_bytes is the maximum size of captured body in bytes. + // Default should be 131_072 (128 KiB). + google.protobuf.Int32Value body_max_size_bytes = 5; + + // body_max_processing_size_bytes is maximum size of body being processed by filters in bytes. + // Default should be 1_048_576 (1MB). + // + // For uncompressed bodies we capture all bytes up to `body_max_processing_size_bytes` + // in memory and pass that through the filter. + // For compressed and GRPC bodies, if the size of the body is larger than this, we ignore + // it entirely, otherwise we decompress/decode the body and then pass it to the filter. + google.protobuf.Int32Value body_max_processing_size_bytes = 6; + + // Array of allowed content type substrings to record + // default should be json, x-www-form-urlencoded + // ex: ["json"] will record any request bodies that have a content-type header that includes "json" + repeated google.protobuf.StringValue allowed_content_types = 10; +} + +// PropagationFormat represents the propagation formats supported by agents +enum PropagationFormat { + // B3 propagation format, agents should support both multi and single value formats + // see https://github.com/openzipkin/b3-propagation + B3 = 0; + + // W3C Propagation format + // see https://www.w3.org/TR/trace-context/ + TRACECONTEXT = 1; +} + +// TraceReporterType represents the reporting format for trace data. +enum TraceReporterType { + + // Default to none. Agent will use it's default reporting type + UNSPECIFIED = 0; + + // Zipkin protobuf reporting format. + // see https://github.com/openzipkin/zipkin-api + ZIPKIN = 1; + + // OpenTelemetry protobuf reporting format. + // see https://github.com/open-telemetry/opentelemetry-proto + OTLP = 2; + + // Logging reporting format + LOGGING = 3; + + // Disable trace reporting + NONE = 4; + + // OTLP over http + OTLP_HTTP = 5; +} + +// MetricReporterType represents the reporting format for metric data. +enum MetricReporterType { + + // Default to none. Agent will use it's default reporting type + METRIC_REPORTER_TYPE_UNSPECIFIED = 0; + + // OpenTelemetry protobuf reporting format. + // see https://github.com/open-telemetry/opentelemetry-proto + METRIC_REPORTER_TYPE_OTLP = 1; + + // Prometheus exposition format. + // see https://github.com/prometheus/docs/blob/main/content/docs/instrumenting/exposition_formats.md + METRIC_REPORTER_TYPE_PROMETHEUS = 2; + + // Logging reporting format + METRIC_REPORTER_TYPE_LOGGING = 3; + + // Disable metric reporting + METRIC_REPORTER_TYPE_NONE = 4; +} + +// GoAgent has the configs specific to goagent +message GoAgent { + // use the custom batch_span_processor adapted from the one in opentelemetry go + // and supports some additional metrics + google.protobuf.BoolValue use_custom_bsp = 1; +} + +// Telemetry has config for agent telemetry: traces and metrics on agent's +// performance and events. +message Telemetry { + // when `true`, an internal span is created and exported when the agent is initialized and started. + // It's useful to denote when the application the agent is in started. + google.protobuf.BoolValue startup_span_enabled = 1; + + // Whether to capture metrics or not. The metrics will be otel go metrics. + // See https://github.com/open-telemetry/opentelemetry-go/tree/main/metric + google.protobuf.BoolValue metrics_enabled = 2; +} diff --git a/tools/env-vars-generator/HEADER.tpl.md b/tools/env-vars-generator/HEADER.tpl.md new file mode 100644 index 0000000..3fb8c9a --- /dev/null +++ b/tools/env-vars-generator/HEADER.tpl.md @@ -0,0 +1,5 @@ +[//]: # (This is the header template for the ENV_VARS.md generated file.) + +# Environment Variables + +Agents can be configured using environment variables: diff --git a/tools/env-vars-generator/go.sum b/tools/env-vars-generator/go.sum new file mode 100644 index 0000000..bfb8e3a --- /dev/null +++ b/tools/env-vars-generator/go.sum @@ -0,0 +1,4 @@ +github.com/iancoleman/strcase v0.2.0 h1:05I4QRnGpI0m37iZQRuskXh+w77mr6Z41lwQzuHLwW0= +github.com/iancoleman/strcase v0.2.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= +github.com/tallstoat/pbparser v0.2.0 h1:lsFH4mdiOv1MIQVmge/idThSTd2uByNodWVfbtysjzg= +github.com/tallstoat/pbparser v0.2.0/go.mod h1:aUC6W9uQLeAXZkknve8ZDO6InhRYpYHlJ9kvsQh1i2k= diff --git a/tools/env-vars-generator/protobuf/.gitmodules b/tools/env-vars-generator/protobuf/.gitmodules new file mode 100644 index 0000000..bcd125a --- /dev/null +++ b/tools/env-vars-generator/protobuf/.gitmodules @@ -0,0 +1,7 @@ +[submodule "third_party/benchmark"] + path = third_party/benchmark + url = https://github.com/google/benchmark.git +[submodule "third_party/googletest"] + path = third_party/googletest + url = https://github.com/google/googletest.git + ignore = dirty diff --git a/tools/env-vars-generator/protobuf/benchmarks/datasets/google_message1/proto2/BUILD b/tools/env-vars-generator/protobuf/benchmarks/datasets/google_message1/proto2/BUILD new file mode 100644 index 0000000..d4d38ce --- /dev/null +++ b/tools/env-vars-generator/protobuf/benchmarks/datasets/google_message1/proto2/BUILD @@ -0,0 +1,44 @@ +load("@rules_cc//cc:defs.bzl", "cc_proto_library") +load("@rules_java//java:defs.bzl", "java_proto_library") +load("@rules_proto//proto:defs.bzl", "proto_library") + +filegroup( + name = "datasets", + srcs = [ + "dataset.google_message1_proto2.pb", + ], + visibility = [ + "//benchmarks/datasets:__pkg__", + ], +) + +proto_library( + name = "benchmark_message1_proto2_proto", + srcs = [ + "benchmark_message1_proto2.proto", + ], + strip_import_prefix = "/benchmarks", + visibility = [ + "//benchmarks/datasets:__pkg__", + ], +) + +cc_proto_library( + name = "benchmark_message1_proto2_cc_proto", + visibility = [ + "//benchmarks/datasets:__pkg__", + ], + deps = [ + "benchmark_message1_proto2_proto", + ], +) + +java_proto_library( + name = "benchmark_message1_proto2_java_proto", + visibility = [ + "//benchmarks/datasets:__pkg__", + ], + deps = [ + "benchmark_message1_proto2_proto", + ], +) diff --git a/tools/env-vars-generator/protobuf/benchmarks/datasets/google_message2/benchmark_message2.proto b/tools/env-vars-generator/protobuf/benchmarks/datasets/google_message2/benchmark_message2.proto new file mode 100644 index 0000000..500c5d6 --- /dev/null +++ b/tools/env-vars-generator/protobuf/benchmarks/datasets/google_message2/benchmark_message2.proto @@ -0,0 +1,108 @@ +// 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. + +// LINT: ALLOW_GROUPS + +// Benchmark messages for proto2. + +syntax = "proto2"; + +package benchmarks.proto2; +option java_package = "com.google.protobuf.benchmarks"; + +// This is the default, but we specify it here explicitly. +option optimize_for = SPEED; + +option cc_enable_arenas = true; + +message GoogleMessage2 { + optional string field1 = 1; + optional int64 field3 = 3; + optional int64 field4 = 4; + optional int64 field30 = 30; + optional bool field75 = 75 [default = false]; + optional string field6 = 6; + optional bytes field2 = 2; + optional int32 field21 = 21 [default = 0]; + optional int32 field71 = 71; + optional float field25 = 25; + optional int32 field109 = 109 [default = 0]; + optional int32 field210 = 210 [default = 0]; + optional int32 field211 = 211 [default = 0]; + optional int32 field212 = 212 [default = 0]; + optional int32 field213 = 213 [default = 0]; + optional int32 field216 = 216 [default = 0]; + optional int32 field217 = 217 [default = 0]; + optional int32 field218 = 218 [default = 0]; + optional int32 field220 = 220 [default = 0]; + optional int32 field221 = 221 [default = 0]; + optional float field222 = 222 [default = 0.0]; + optional int32 field63 = 63; + + repeated group Group1 = 10 { + required float field11 = 11; + optional float field26 = 26; + optional string field12 = 12; + optional string field13 = 13; + repeated string field14 = 14; + required uint64 field15 = 15; + optional int32 field5 = 5; + optional string field27 = 27; + optional int32 field28 = 28; + optional string field29 = 29; + optional string field16 = 16; + repeated string field22 = 22; + repeated int32 field73 = 73; + optional int32 field20 = 20 [default = 0]; + optional string field24 = 24; + optional GoogleMessage2GroupedMessage field31 = 31; + } + repeated string field128 = 128; + optional int64 field131 = 131; + repeated string field127 = 127; + optional int32 field129 = 129; + repeated int64 field130 = 130; + optional bool field205 = 205 [default = false]; + optional bool field206 = 206 [default = false]; +} + +message GoogleMessage2GroupedMessage { + optional float field1 = 1; + optional float field2 = 2; + optional float field3 = 3 [default = 0.0]; + optional bool field4 = 4; + optional bool field5 = 5; + optional bool field6 = 6 [default = true]; + optional bool field7 = 7 [default = false]; + optional float field8 = 8; + optional bool field9 = 9; + optional float field10 = 10; + optional int64 field11 = 11; +} diff --git a/tools/env-vars-generator/protobuf/benchmarks/datasets/google_message3/benchmark_message3.proto b/tools/env-vars-generator/protobuf/benchmarks/datasets/google_message3/benchmark_message3.proto new file mode 100644 index 0000000..82422f9 --- /dev/null +++ b/tools/env-vars-generator/protobuf/benchmarks/datasets/google_message3/benchmark_message3.proto @@ -0,0 +1,566 @@ +// 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. + +// LINT: ALLOW_GROUPS + +syntax = "proto2"; + +package benchmarks.google_message3; + +import "datasets/google_message3/benchmark_message3_1.proto"; +import "datasets/google_message3/benchmark_message3_2.proto"; +import "datasets/google_message3/benchmark_message3_3.proto"; +import "datasets/google_message3/benchmark_message3_4.proto"; +import "datasets/google_message3/benchmark_message3_5.proto"; +import "datasets/google_message3/benchmark_message3_7.proto"; +import "datasets/google_message3/benchmark_message3_8.proto"; + +option cc_enable_arenas = true; +option java_package = "com.google.protobuf.benchmarks"; + +message GoogleMessage3 { + optional .benchmarks.google_message3.Message37487 field37519 = 2; + optional .benchmarks.google_message3.Message36876 field37520 = 3; + optional .benchmarks.google_message3.Message13062 field37521 = 4; + optional .benchmarks.google_message3.Message952 field37522 = 5; + optional .benchmarks.google_message3.UnusedEmptyMessage field37523 = 6; + optional .benchmarks.google_message3.UnusedEmptyMessage field37524 = 7; + optional .benchmarks.google_message3.UnusedEmptyMessage field37525 = 8; + optional .benchmarks.google_message3.UnusedEmptyMessage field37526 = 9; + optional .benchmarks.google_message3.UnusedEmptyMessage field37527 = 10; + optional .benchmarks.google_message3.UnusedEmptyMessage field37528 = 11; + optional .benchmarks.google_message3.UnusedEmptyMessage field37529 = 12; + optional .benchmarks.google_message3.UnusedEmptyMessage field37530 = 13; + optional .benchmarks.google_message3.UnusedEmptyMessage field37531 = 14; + optional .benchmarks.google_message3.UnusedEmptyMessage field37532 = 15; + optional .benchmarks.google_message3.UnusedEmptyMessage field37533 = 16; +} + +message Message1327 { + repeated .benchmarks.google_message3.UnusedEmptyMessage field1369 = 1; + repeated .benchmarks.google_message3.Message1328 field1370 = 3; + repeated .benchmarks.google_message3.UnusedEmptyMessage field1371 = 5; + repeated .benchmarks.google_message3.UnusedEmptyMessage field1372 = 6; + extend .benchmarks.google_message3.Message0 { + optional .benchmarks.google_message3.Message1327 field1373 = 23104162; + } +} + +message Message3672 { + optional .benchmarks.google_message3.Enum3476 field3727 = 1; + optional int32 field3728 = 11; + optional int32 field3729 = 2; + repeated group Message3673 = 3 { + required .benchmarks.google_message3.Enum3476 field3738 = 4; + required int32 field3739 = 5; + } + repeated group Message3674 = 6 { + required .benchmarks.google_message3.Enum3476 field3740 = 7; + required int32 field3741 = 8; + } + optional bool field3732 = 9; + optional int32 field3733 = 10; + optional .benchmarks.google_message3.Enum3476 field3734 = 20; + optional int32 field3735 = 21; + optional .benchmarks.google_message3.UnusedEmptyMessage field3736 = 50; + extend .benchmarks.google_message3.Message0 { + optional .benchmarks.google_message3.Message3672 field3737 = 3144435; + } +} + +message Message3804 { + required int64 field3818 = 1; + required bool field3819 = 2; + repeated .benchmarks.google_message3.Enum3805 field3820 = 4; + optional int32 field3821 = 5; + optional bool field3822 = 6; + optional int64 field3823 = 7; + optional .benchmarks.google_message3.Enum3783 field3824 = 8; + extend .benchmarks.google_message3.Message0 { + optional .benchmarks.google_message3.Message3804 field3825 = 59241828; + } +} + +message Message6849 { + repeated .benchmarks.google_message3.Message6850 field6910 = 1; + extend .benchmarks.google_message3.Message0 { + optional .benchmarks.google_message3.Message6849 field6911 = 107558455; + } +} + +message Message6866 { + repeated .benchmarks.google_message3.Message6863 field6973 = 1; + extend .benchmarks.google_message3.Message0 { + optional .benchmarks.google_message3.Message6866 field6974 = 22259060; + } +} + +message Message6870 { + repeated .benchmarks.google_message3.Message6871 field6991 = 1; + extend .benchmarks.google_message3.Message0 { + optional .benchmarks.google_message3.Message6870 field6992 = 90034652; + } +} + +message Message7651 { + optional string field7685 = 1; + optional int64 field7686 = 2; + optional int64 field7687 = 3; + optional int64 field7688 = 4; + optional int32 field7689 = 5; + optional int32 field7690 = 6; + optional int32 field7691 = 7; + optional int32 field7692 = 8; + optional int32 field7693 = 9; + optional int32 field7694 = 10; + optional int32 field7695 = 11; + optional int32 field7696 = 12; + optional int32 field7697 = 13; + optional int32 field7698 = 14; + optional int32 field7699 = 15; + optional int32 field7700 = 16; + optional int32 field7701 = 17; + optional int32 field7702 = 18; + optional bool field7703 = 19; + repeated int32 field7704 = 20; + repeated int32 field7705 = 21; + repeated string field7706 = 22; + repeated string field7707 = 23; + optional .benchmarks.google_message3.UnusedEmptyMessage field7708 = 24; + optional int32 field7709 = 25; + optional int32 field7710 = 26; + optional int32 field7711 = 27; + optional int32 field7712 = 43; + optional int32 field7713 = 28; + optional int32 field7714 = 29; + repeated .benchmarks.google_message3.Message7547 field7715 = 30; + repeated .benchmarks.google_message3.Message7547 field7716 = 31; + repeated .benchmarks.google_message3.UnusedEmptyMessage field7717 = 32; + repeated string field7718 = 33; + repeated string field7719 = 34; + repeated .benchmarks.google_message3.Message7648 field7720 = 35; + optional bool field7721 = 36; + optional bool field7722 = 37; + optional bool field7723 = 38; + optional bool field7724 = 39; + optional .benchmarks.google_message3.UnusedEmptyMessage field7725 = 40; + optional .benchmarks.google_message3.UnusedEnum field7726 = 41; + optional .benchmarks.google_message3.Enum7654 field7727 = 42; + optional string field7728 = 44; + optional .benchmarks.google_message3.UnusedEmptyMessage field7729 = 45; + extend .benchmarks.google_message3.Message0 { + optional .benchmarks.google_message3.Message7651 field7730 = 55876009; + } +} + +message Message7864 { + optional string field7866 = 1; + optional string field7867 = 2; + repeated .benchmarks.google_message3.Message7865 field7868 = 5; + repeated .benchmarks.google_message3.Message7865 field7869 = 6; + repeated .benchmarks.google_message3.Message7865 field7870 = 7; + repeated .benchmarks.google_message3.UnusedEmptyMessage field7871 = 8; + extend .benchmarks.google_message3.Message0 { + optional .benchmarks.google_message3.Message7864 field7872 = 44542730; + } +} + +message Message7929 { + optional int64 field7942 = 1; + optional int64 field7943 = 4; + optional int64 field7944 = 5; + optional int64 field7945 = 12; + optional int64 field7946 = 13; + optional int64 field7947 = 18; + optional int64 field7948 = 6; + optional int64 field7949 = 7; + repeated .benchmarks.google_message3.Message7919 field7950 = 8; + repeated .benchmarks.google_message3.UnusedEmptyMessage field7951 = 20; + repeated .benchmarks.google_message3.Message7920 field7952 = 14; + repeated .benchmarks.google_message3.Message7921 field7953 = 15; + repeated .benchmarks.google_message3.Message7928 field7954 = 17; + optional int64 field7955 = 19; + optional bool field7956 = 2; + optional int64 field7957 = 3; + optional int64 field7958 = 9; + repeated .benchmarks.google_message3.UnusedEmptyMessage field7959 = 10; + repeated bytes field7960 = 11; + optional int64 field7961 = 16; + extend .benchmarks.google_message3.Message0 { + optional .benchmarks.google_message3.Message7929 field7962 = 53392238; + } +} + +message Message8508 { + repeated .benchmarks.google_message3.Message8511 field8517 = 8; + repeated .benchmarks.google_message3.Message8512 field8518 = 9; + repeated .benchmarks.google_message3.Message8513 field8519 = 11; + optional bool field8520 = 13; + optional .benchmarks.google_message3.Message8514 field8521 = 14; + repeated .benchmarks.google_message3.UnusedEmptyMessage field8522 = 15; + repeated .benchmarks.google_message3.Message8515 field8523 = 16; + repeated .benchmarks.google_message3.UnusedEmptyMessage field8524 = 17; + optional int64 field8525 = 1; + optional float field8526 = 2; + optional int64 field8527 = 3; + optional int64 field8528 = 4; + optional int32 field8529 = 5; + optional bytes field8530 = 6; + repeated bytes field8531 = 7; + optional bool field8532 = 10; + optional bytes field8533 = 12; + extend .benchmarks.google_message3.Message0 { + optional .benchmarks.google_message3.Message8508 field8534 = 3811804; + } +} + +message Message9122 { + optional float field9132 = 1; + optional float field9133 = 2; + extend .benchmarks.google_message3.Message0 { + optional .benchmarks.google_message3.Message9122 field9134 = 120398939; + } +} + +message Message10177 { + repeated .benchmarks.google_message3.Message10155 field10270 = 1; + extend .benchmarks.google_message3.Message0 { + optional .benchmarks.google_message3.Message10177 field10271 = 26801105; + } +} + +message Message10278 { + repeated int32 field10286 = 1 [packed = true]; + repeated int32 field10287 = 2 [packed = true]; + optional int32 field10288 = 3; + extend .benchmarks.google_message3.Message10155 { + optional .benchmarks.google_message3.Message10278 field10289 = 29374161; + } +} + +message Message10323 { + repeated .benchmarks.google_message3.Message10320 field10360 = 1; + extend .benchmarks.google_message3.Message10155 { + optional .benchmarks.google_message3.Message10323 field10361 = 27922524; + } +} + +message Message10324 { + repeated .benchmarks.google_message3.Message10322 field10362 = 1; + optional .benchmarks.google_message3.Message10321 field10363 = 2; + extend .benchmarks.google_message3.Message10155 { + optional .benchmarks.google_message3.Message10324 field10364 = 27832297; + } +} + +message Message11990 { + repeated .benchmarks.google_message3.Message11988 field12030 = 1; + extend .benchmarks.google_message3.Message0 { + optional .benchmarks.google_message3.Message11990 field12031 = 21265426; + } +} + +message Message12691 { + optional string field12713 = 1; + optional int32 field12714 = 2; + optional .benchmarks.google_message3.Message12668 field12715 = 3; + extend .benchmarks.google_message3.Message0 { + optional .benchmarks.google_message3.Message12691 field12716 = 28426536; + } +} + +message Message12870 { + required int32 field12879 = 1; + optional int32 field12880 = 7; + required int32 field12881 = 2; + optional uint64 field12882 = 3; + optional string field12883 = 2001; + optional fixed64 field12884 = 4; + repeated fixed64 field12885 = 14; + optional int32 field12886 = 9; + optional int64 field12887 = 18; + repeated .benchmarks.google_message3.Message12870 field12888 = 8; + optional int32 field12889 = 5; + optional uint64 field12890 = 6; + optional int32 field12891 = 10; + optional int32 field12892 = 11; + optional double field12893 = 12; + optional .benchmarks.google_message3.Message12825 field12894 = 13; + optional double field12895 = 15; + optional string field12896 = 16; + optional .benchmarks.google_message3.Enum12871 field12897 = 17; + optional int32 field12898 = 19; + extend .benchmarks.google_message3.Message0 { + optional .benchmarks.google_message3.Message12870 field12899 = 5447656; + } +} + +message Message13154 { + required float field13164 = 1; + required float field13165 = 2; + extend .benchmarks.google_message3.Message13145 { + optional .benchmarks.google_message3.Message13154 field13166 = 47301086; + } +} + +message Message16507 { + optional bool field16510 = 3; + optional bool field16511 = 4; + optional bool field16512 = 14; + repeated string field16513 = 5; + repeated string field16514 = 6; + optional string field16515 = 8; + repeated int32 field16516 = 9; + repeated int32 field16517 = 10; + optional int32 field16518 = 7; + optional string field16519 = 15; + repeated string field16520 = 11; + repeated .benchmarks.google_message3.UnusedEmptyMessage field16521 = 27; + repeated .benchmarks.google_message3.UnusedEmptyMessage field16522 = 22; + repeated .benchmarks.google_message3.UnusedEmptyMessage field16523 = 28; + optional string field16524 = 18; + optional int32 field16525 = 19; + optional int32 field16526 = 20; + optional .benchmarks.google_message3.UnusedEmptyMessage field16527 = 23; + optional bool field16528 = 24; + repeated string field16529 = 25; + optional double field16530 = 26; + optional .benchmarks.google_message3.Message16478 field16531 = 30; + optional bool field16532 = 31; + optional string field16533 = 32; + optional bool field16534 = 33; + optional bool field16535 = 35; + optional bool field16536 = 36; + optional bool field16537 = 37; + optional bool field16538 = 38; + optional bool field16539 = 39; + optional bool field16540 = 40; + repeated string field16541 = 41; + extensions 21 to 21; + extend .benchmarks.google_message3.Message0 { + optional .benchmarks.google_message3.Message16507 field16542 = 5569941; + } +} + +message Message16564 { + repeated .benchmarks.google_message3.Message16552 field16568 = 1; + extend .benchmarks.google_message3.Message0 { + optional .benchmarks.google_message3.Message16564 field16569 = 25830030; + } +} + +message Message16661 { + repeated .benchmarks.google_message3.Message16660 field16671 = 1; + repeated uint64 field16672 = 2; + extend .benchmarks.google_message3.Message0 { + optional .benchmarks.google_message3.Message16661 field16673 = 31274398; + } +} + +message Message16746 { + repeated .benchmarks.google_message3.Message16727 field16806 = 1; + optional bool field16807 = 2; + optional bool field16808 = 3; + repeated .benchmarks.google_message3.Message16725 field16809 = 4; + extend .benchmarks.google_message3.Message0 { + optional .benchmarks.google_message3.Message16746 field16810 = 28406765; + } +} + +message Message17786 { + repeated group Message17787 = 1 { + required int32 field18177 = 2; + required int32 field18178 = 3; + optional .benchmarks.google_message3.Message17783 field18179 = 4; + optional .benchmarks.google_message3.UnusedEmptyMessage field18180 = 5; + optional .benchmarks.google_message3.UnusedEmptyMessage field18181 = 6; + repeated .benchmarks.google_message3.UnusedEmptyMessage field18182 = 8; + optional .benchmarks.google_message3.UnusedEmptyMessage field18183 = 9; + optional .benchmarks.google_message3.Message17726 field18184 = 10; + optional .benchmarks.google_message3.UnusedEmptyMessage field18185 = 11; + optional .benchmarks.google_message3.Message16945 field18186 = 102; + optional .benchmarks.google_message3.UnusedEmptyMessage field18187 = 12; + optional .benchmarks.google_message3.UnusedEmptyMessage field18188 = 13; + optional .benchmarks.google_message3.UnusedEmptyMessage field18189 = 7; + optional .benchmarks.google_message3.UnusedEmptyMessage field18190 = 100; + optional .benchmarks.google_message3.UnusedEmptyMessage field18191 = 101; + optional .benchmarks.google_message3.UnusedEmptyMessage field18192 = 14; + optional .benchmarks.google_message3.UnusedEmptyMessage field18193 = 19; + optional .benchmarks.google_message3.UnusedEmptyMessage field18194 = 22; + optional .benchmarks.google_message3.UnusedEmptyMessage field18195 = 24; + optional .benchmarks.google_message3.Enum16925 field18196 = 21; + optional bool field18197 = 18; + repeated .benchmarks.google_message3.UnusedEnum field18198 = 23; + optional .benchmarks.google_message3.UnusedEmptyMessage field18199 = 15; + optional string field18200 = 16; + optional string field18201 = 17; + optional bool field18202 = 99; + } + repeated .benchmarks.google_message3.Message17782 field18175 = 20; + extend .benchmarks.google_message3.Message0 { + optional .benchmarks.google_message3.Message17786 field18176 = 11823055; + } +} + +message Message22857 { + repeated .benchmarks.google_message3.Message22853 field22874 = 1; + extend .benchmarks.google_message3.Message10155 { + optional .benchmarks.google_message3.Message22857 field22875 = 67799715; + } +} + +message Message24404 { + repeated group Message24405 = 1 { + required int32 field24686 = 2; + required int32 field24687 = 3; + optional .benchmarks.google_message3.Message24317 field24688 = 4; + optional .benchmarks.google_message3.UnusedEmptyMessage field24689 = 5; + optional .benchmarks.google_message3.Message24376 field24690 = 6; + optional .benchmarks.google_message3.Message24345 field24691 = 7; + optional .benchmarks.google_message3.UnusedEmptyMessage field24692 = 8; + optional .benchmarks.google_message3.Message24379 field24693 = 9; + optional .benchmarks.google_message3.UnusedEmptyMessage field24694 = 10; + optional .benchmarks.google_message3.UnusedEmptyMessage field24695 = 11; + optional .benchmarks.google_message3.Message24391 field24696 = 12; + optional .benchmarks.google_message3.UnusedEmptyMessage field24697 = 13; + optional .benchmarks.google_message3.UnusedEmptyMessage field24698 = 14; + optional .benchmarks.google_message3.UnusedEmptyMessage field24699 = 22; + optional .benchmarks.google_message3.UnusedEmptyMessage field24700 = 23; + optional .benchmarks.google_message3.UnusedEmptyMessage field24701 = 25; + optional .benchmarks.google_message3.Enum16925 field24702 = 18; + optional float field24703 = 20; + optional bool field24704 = 19; + repeated .benchmarks.google_message3.Enum16891 field24705 = 24; + optional .benchmarks.google_message3.UnusedEmptyMessage field24706 = 15; + optional string field24707 = 16; + optional string field24708 = 17; + optional float field24709 = 21; + optional bool field24710 = 26; + optional .benchmarks.google_message3.UnusedEnum field24711 = 27; + optional bool field24712 = 28; + optional .benchmarks.google_message3.UnusedEnum field24713 = 29; + optional bool field24714 = 31; + optional bool field24715 = 99; + optional int64 field24716 = 32; + } + optional .benchmarks.google_message3.Message24403 field24684 = 30; + extend .benchmarks.google_message3.Message0 { + optional .benchmarks.google_message3.Message24404 field24685 = 9129287; + } +} + +message Message27300 { + repeated .benchmarks.google_message3.UnusedEmptyMessage field27302 = 1; + optional string field27303 = 2; + extend .benchmarks.google_message3.Message0 { + optional .benchmarks.google_message3.Message27300 field27304 = 24956467; + } +} + +message Message27453 { + optional string field27459 = 15; + repeated string field27460 = 1; + repeated float field27461 = 6; + repeated int32 field27462 = 27; + repeated int32 field27463 = 28; + repeated .benchmarks.google_message3.Message27454 field27464 = 24; + repeated string field27465 = 2; + repeated float field27466 = 7; + repeated string field27467 = 22; + repeated string field27468 = 23; + optional string field27469 = 26; + repeated .benchmarks.google_message3.Message27357 field27470 = 8; + optional .benchmarks.google_message3.Message27360 field27471 = 16; + optional string field27472 = 25; + optional string field27473 = 11; + optional bool field27474 = 13; + optional bool field27475 = 14; + optional bool field27476 = 17; + optional .benchmarks.google_message3.UnusedEmptyMessage field27477 = 12; + optional bool field27478 = 34268945; + optional bool field27479 = 20; + optional string field27480 = 21; + optional .benchmarks.google_message3.UnusedEmptyMessage field27481 = 10; + extend .benchmarks.google_message3.Message0 { + optional .benchmarks.google_message3.Message27453 field27482 = 8086204; + } +} + +extend .benchmarks.google_message3.Message16945 { + optional string field17026 = 472; + repeated string field17027 = 818; + optional .benchmarks.google_message3.Message0 field17031 = 215; + repeated .benchmarks.google_message3.Message0 field17032 = 292; + repeated .benchmarks.google_message3.Message0 field17038 = 234; + repeated .benchmarks.google_message3.Message0 field17039 = 235; + optional .benchmarks.google_message3.Message0 field17042 = 246; + optional string field17043 = 224; + optional string field17044 = 225; + repeated string field17048 = 63; + repeated string field17049 = 64; + repeated .benchmarks.google_message3.Message0 field17052 = 233; + repeated .benchmarks.google_message3.Message0 field17053 = 66; + repeated string field17056 = 275; + optional string field17057 = 226; + repeated .benchmarks.google_message3.Message0 field17060 = 27; + repeated string field17073 = 75; + repeated .benchmarks.google_message3.Message0 field17076 = 77; + repeated string field17078 = 296; + repeated .benchmarks.google_message3.Message0 field17082 = 160; + repeated .benchmarks.google_message3.Message0 field17091 = 585; + repeated .benchmarks.google_message3.Message0 field17098 = 987; + repeated .benchmarks.google_message3.Message0 field17101 = 157; + repeated string field17102 = 158; + repeated string field17107 = 166; + repeated string field17133 = 567; + repeated string field17134 = 572; + repeated string field17160 = 49; + repeated string field17168 = 32; + repeated string field17170 = 34; + repeated .benchmarks.google_message3.Message0 field17172 = 509; + repeated string field17174 = 39; + repeated .benchmarks.google_message3.Message0 field17175 = 40; + repeated .benchmarks.google_message3.Message0 field17178 = 511; + repeated .benchmarks.google_message3.Message0 field17185 = 50; + repeated int32 field17207 = 1081; + repeated .benchmarks.google_message3.Message0 field17238 = 184; + repeated .benchmarks.google_message3.Message0 field17289 = 177; + repeated .benchmarks.google_message3.Message0 field17290 = 178; + repeated .benchmarks.google_message3.Message0 field17296 = 474; + repeated string field17298 = 44; + repeated .benchmarks.google_message3.Message0 field17301 = 47; + optional .benchmarks.google_message3.Message0 field17412 = 21; + repeated .benchmarks.google_message3.Message0 field17438 = 132; + repeated .benchmarks.google_message3.Message0 field17458 = 512; + repeated string field17460 = 560; + repeated string field17466 = 552; + repeated .benchmarks.google_message3.Message0 field17617 = 1080; + repeated int32 field17618 = 1084; +} diff --git a/tools/env-vars-generator/protobuf/benchmarks/php/PhpBenchmark.php b/tools/env-vars-generator/protobuf/benchmarks/php/PhpBenchmark.php new file mode 100644 index 0000000..d3db61d --- /dev/null +++ b/tools/env-vars-generator/protobuf/benchmarks/php/PhpBenchmark.php @@ -0,0 +1,170 @@ +getPayload(); + for ($i = $payloads->count() - 1; $i >= 0; $i--) { + (new $args[1]())->mergeFromString($payloads->offsetGet($i)); + } + } + + // $args: array of message + static function serialize(&$args) { + foreach ($args as &$temp_message) { + $temp_message->serializeToString(); + } + } +} + +class Benchmark +{ + private $benchmark_name; + private $args; + private $benchmark_time; + private $total_bytes; + private $coefficient; + + public function __construct($benchmark_name, $args, $total_bytes, + $benchmark_time = 5.0) { + $this->args = $args; + $this->benchmark_name = $benchmark_name; + $this->benchmark_time = $benchmark_time; + $this->total_bytes = $total_bytes; + $this->coefficient = pow (10, 0) / pow(2, 20); + } + + public function runBenchmark() { + $t = $this->runBenchmarkWithTimes(1); + $times = ceil($this->benchmark_time / $t); + return $this->total_bytes * $times / + ($times == 1 ? $t : $this->runBenchmarkWithTimes($times)) * + $this->coefficient; + } + + private function runBenchmarkWithTimes($times) { + $st = microtime(true); + for ($i = 0; $i < $times; $i++) { + call_user_func_array($this->benchmark_name, array(&$this->args)); + } + $en = microtime(true); + return $en - $st; + } +} + +function getMessageName(&$dataset) { + switch ($dataset->getMessageName()) { + case "benchmarks.proto3.GoogleMessage1": + return "\Benchmarks\Proto3\GoogleMessage1"; + case "benchmarks.proto2.GoogleMessage1": + return "\Benchmarks\Proto2\GoogleMessage1"; + case "benchmarks.proto2.GoogleMessage2": + return "\Benchmarks\Proto2\GoogleMessage2"; + case "benchmarks.google_message3.GoogleMessage3": + return "\Benchmarks\Google_message3\GoogleMessage3"; + case "benchmarks.google_message4.GoogleMessage4": + return "\Benchmarks\Google_message4\GoogleMessage4"; + default: + exit("Message " . $dataset->getMessageName() . " not found !"); + } +} + +function runBenchmark($file, $behavior_prefix) { + $datafile = fopen($file, "r") or die("Unable to open file " . $file); + $bytes = fread($datafile, filesize($file)); + $dataset = new BenchmarkDataset(NULL); + $dataset->mergeFromString($bytes); + $message_name = getMessageName($dataset); + $message_list = array(); + $total_bytes = 0; + $payloads = $dataset->getPayload(); + for ($i = $payloads->count() - 1; $i >= 0; $i--) { + $new_message = new $message_name(); + $new_message->mergeFromString($payloads->offsetGet($i)); + array_push($message_list, $new_message); + $total_bytes += strlen($payloads->offsetGet($i)); + } + + $parse_benchmark = new Benchmark( + "\Google\Protobuf\Benchmark\BenchmarkMethod::parse", + array($dataset, $message_name), $total_bytes); + $serialize_benchmark = new Benchmark( + "\Google\Protobuf\Benchmark\BenchmarkMethod::serialize", + $message_list, $total_bytes); + + return array( + "filename" => $file, + "benchmarks" => array( + $behavior_prefix . "_parse" => $parse_benchmark->runBenchmark(), + $behavior_prefix . "_serailize" => $serialize_benchmark->runBenchmark() + ), + "message_name" => $dataset->getMessageName() + ); +} + +// main +$json_output = false; +$results = array(); +$behavior_prefix = ""; + +foreach ($argv as $index => $arg) { + if ($index == 0) { + continue; + } + if ($arg == "--json") { + $json_output = true; + } else if (strpos($arg, "--behavior_prefix") == 0) { + $behavior_prefix = str_replace("--behavior_prefix=", "", $arg); + } +} + +foreach ($argv as $index => $arg) { + if ($index == 0) { + continue; + } + if (substr($arg, 0, 2) == "--") { + continue; + } else { + array_push($results, runBenchmark($arg, $behavior_prefix)); + } +} + +if ($json_output) { + print json_encode($results); +} else { + print "PHP protobuf benchmark result:\n\n"; + foreach ($results as $result) { + printf("result for test data file: %s\n", $result["filename"]); + foreach ($result["benchmarks"] as $benchmark => $throughput) { + printf(" Throughput for benchmark %s: %.2f MB/s\n", + $benchmark, $throughput); + } + } +} + +?> diff --git a/tools/env-vars-generator/protobuf/benchmarks/python/py_benchmark.py b/tools/env-vars-generator/protobuf/benchmarks/python/py_benchmark.py new file mode 100644 index 0000000..60e377e --- /dev/null +++ b/tools/env-vars-generator/protobuf/benchmarks/python/py_benchmark.py @@ -0,0 +1,161 @@ +from __future__ import print_function +import sys +import os +import timeit +import math +import argparse +import fnmatch +import json + +parser = argparse.ArgumentParser(description="Python protobuf benchmark") +parser.add_argument("data_files", metavar="dataFile", nargs="+", + help="testing data files.") +parser.add_argument("--json", action="store_const", dest="json", + const="yes", default="no", + help="Whether to output json results") +parser.add_argument("--behavior_prefix", dest="behavior_prefix", + help="The output json format's behavior's name's prefix", + default="") +# BEGIN CPP GENERATED MESSAGE +parser.add_argument("--cpp_generated", action="store_const", + dest="cpp_generated", const="yes", default="no", + help="Whether to link generated code library") +# END CPP GENERATED MESSAGE +args = parser.parse_args() +# BEGIN CPP GENERATED MESSAGE +# CPP generated code must be linked before importing the generated Python code +# for the descriptor can be found in the pool +if args.cpp_generated != "no": + sys.path.append( os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) ) + "/.libs" ) + import libbenchmark_messages + sys.path.append( os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) ) + "/tmp" ) +# END CPP GENERATED MESSAGE + + +import datasets.google_message1.proto2.benchmark_message1_proto2_pb2 as benchmark_message1_proto2_pb2 +import datasets.google_message1.proto3.benchmark_message1_proto3_pb2 as benchmark_message1_proto3_pb2 +import datasets.google_message2.benchmark_message2_pb2 as benchmark_message2_pb2 +import datasets.google_message3.benchmark_message3_pb2 as benchmark_message3_pb2 +import datasets.google_message4.benchmark_message4_pb2 as benchmark_message4_pb2 +import benchmarks_pb2 as benchmarks_pb2 + + +def run_one_test(filename): + data = open(filename, "rb").read() + benchmark_dataset = benchmarks_pb2.BenchmarkDataset() + benchmark_dataset.ParseFromString(data) + total_bytes = 0 + for payload in benchmark_dataset.payload: + total_bytes += len(payload) + benchmark_util = Benchmark(full_iteration=len(benchmark_dataset.payload), + module="py_benchmark", + setup_method="init", + total_bytes=total_bytes) + result={} + result["filename"] = filename + result["message_name"] = benchmark_dataset.message_name + result["benchmarks"] = {} + benchmark_util.set_test_method("parse_from_benchmark") + result["benchmarks"][args.behavior_prefix + "_parse_from_benchmark"] = \ + benchmark_util.run_benchmark(setup_method_args='"%s"' % (filename)) + benchmark_util.set_test_method("serialize_to_benchmark") + result["benchmarks"][args.behavior_prefix + "_serialize_to_benchmark"] = \ + benchmark_util.run_benchmark(setup_method_args='"%s"' % (filename)) + return result + + +def init(filename): + global benchmark_dataset, message_class, message_list, counter, total_bytes + message_list=[] + counter = 0 + total_bytes = 0 + data = open(filename, "rb").read() + benchmark_dataset = benchmarks_pb2.BenchmarkDataset() + benchmark_dataset.ParseFromString(data) + + if benchmark_dataset.message_name == "benchmarks.proto3.GoogleMessage1": + message_class = benchmark_message1_proto3_pb2.GoogleMessage1 + elif benchmark_dataset.message_name == "benchmarks.proto2.GoogleMessage1": + message_class = benchmark_message1_proto2_pb2.GoogleMessage1 + elif benchmark_dataset.message_name == "benchmarks.proto2.GoogleMessage2": + message_class = benchmark_message2_pb2.GoogleMessage2 + elif benchmark_dataset.message_name == "benchmarks.google_message3.GoogleMessage3": + message_class = benchmark_message3_pb2.GoogleMessage3 + elif benchmark_dataset.message_name == "benchmarks.google_message4.GoogleMessage4": + message_class = benchmark_message4_pb2.GoogleMessage4 + else: + raise IOError("Message %s not found!" % (benchmark_dataset.message_name)) + + for one_payload in benchmark_dataset.payload: + temp = message_class() + temp.ParseFromString(one_payload) + message_list.append(temp) + total_bytes += len(one_payload) + + +def parse_from_benchmark(): + global counter, message_class, benchmark_dataset + m = message_class().ParseFromString(benchmark_dataset.payload[counter % len(benchmark_dataset.payload)]) + counter = counter + 1 + + +def serialize_to_benchmark(): + global counter, message_list, message_class + s = message_list[counter % len(benchmark_dataset.payload)].SerializeToString() + counter = counter + 1 + + +class Benchmark: + def __init__(self, module=None, test_method=None, + setup_method=None, total_bytes=None, full_iteration = 1): + self.full_iteration = full_iteration + self.module = module + self.test_method = test_method + self.setup_method = setup_method + self.total_bytes = total_bytes + + def set_test_method(self, test_method): + self.test_method = test_method + + def full_setup_code(self, setup_method_args=''): + setup_code = "" + setup_code += "from %s import %s\n" % (self.module, self.test_method) + setup_code += "from %s import %s\n" % (self.module, self.setup_method) + setup_code += "%s(%s)\n" % (self.setup_method, setup_method_args) + return setup_code + + def dry_run(self, test_method_args='', setup_method_args=''): + return timeit.timeit(stmt="%s(%s)" % (self.test_method, test_method_args), + setup=self.full_setup_code(setup_method_args), + number=self.full_iteration); + + def run_benchmark(self, test_method_args='', setup_method_args=''): + reps = self.full_iteration; + t = self.dry_run(test_method_args, setup_method_args); + if t < 3 : + reps = int(math.ceil(3 / t)) * self.full_iteration + if reps != self.full_iteration: + t = timeit.timeit(stmt="%s(%s)" % (self.test_method, test_method_args), + setup=self.full_setup_code(setup_method_args), + number=reps); + return self.total_bytes * 1.0 / 2 ** 20 / (1.0 * t / reps * self.full_iteration) + + +if __name__ == "__main__": + results = [] + for file in args.data_files: + results.append(run_one_test(file)) + + if args.json != "no": + print(json.dumps(results)) + else: + for result in results: + print("Message %s of dataset file %s" % \ + (result["message_name"], result["filename"])) + print("Average throughput for parse_from_benchmark: %.2f MB/s" % \ + (result["benchmarks"][ \ + args.behavior_prefix + "_parse_from_benchmark"])) + print("Average throughput for serialize_to_benchmark: %.2f MB/s" % \ + (result["benchmarks"][ \ + args.behavior_prefix + "_serialize_to_benchmark"])) + print("") diff --git a/tools/env-vars-generator/protobuf/benchmarks/util/__init__.py b/tools/env-vars-generator/protobuf/benchmarks/util/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tools/env-vars-generator/protobuf/benchmarks/util/data_proto2_to_proto3_util.h b/tools/env-vars-generator/protobuf/benchmarks/util/data_proto2_to_proto3_util.h new file mode 100644 index 0000000..5eea850 --- /dev/null +++ b/tools/env-vars-generator/protobuf/benchmarks/util/data_proto2_to_proto3_util.h @@ -0,0 +1,64 @@ +#ifndef PROTOBUF_BENCHMARKS_UTIL_DATA_PROTO2_TO_PROTO3_UTIL_H_ +#define PROTOBUF_BENCHMARKS_UTIL_DATA_PROTO2_TO_PROTO3_UTIL_H_ + +#include "google/protobuf/message.h" +#include "google/protobuf/descriptor.h" + +using google::protobuf::FieldDescriptor; +using google::protobuf::Message; +using google::protobuf::Reflection; + +namespace google { +namespace protobuf { +namespace util { + +class DataStripper { + public: + void StripMessage(Message *message) { + std::vector set_fields; + const Reflection* reflection = message->GetReflection(); + reflection->ListFields(*message, &set_fields); + + for (size_t i = 0; i < set_fields.size(); i++) { + const FieldDescriptor* field = set_fields[i]; + if (ShouldBeClear(field)) { + reflection->ClearField(message, field); + continue; + } + if (field->type() == FieldDescriptor::TYPE_MESSAGE) { + if (field->is_repeated()) { + for (int j = 0; j < reflection->FieldSize(*message, field); j++) { + StripMessage(reflection->MutableRepeatedMessage(message, field, j)); + } + } else { + StripMessage(reflection->MutableMessage(message, field)); + } + } + } + + reflection->MutableUnknownFields(message)->Clear(); + } + private: + virtual bool ShouldBeClear(const FieldDescriptor *field) = 0; +}; + +class GogoDataStripper : public DataStripper { + private: + virtual bool ShouldBeClear(const FieldDescriptor *field) { + return field->type() == FieldDescriptor::TYPE_GROUP; + } +}; + +class Proto3DataStripper : public DataStripper { + private: + virtual bool ShouldBeClear(const FieldDescriptor *field) { + return field->type() == FieldDescriptor::TYPE_GROUP || + field->is_extension(); + } +}; + +} // namespace util +} // namespace protobuf +} // namespace google + +#endif // PROTOBUF_BENCHMARKS_UTIL_DATA_PROTO2_TO_PROTO3_UTIL_H_ diff --git a/tools/env-vars-generator/protobuf/cmake/CMakeLists.txt b/tools/env-vars-generator/protobuf/cmake/CMakeLists.txt new file mode 100644 index 0000000..2366d4b --- /dev/null +++ b/tools/env-vars-generator/protobuf/cmake/CMakeLists.txt @@ -0,0 +1,318 @@ +# Minimum CMake required +cmake_minimum_required(VERSION 3.1.3) + +if(protobuf_VERBOSE) + message(STATUS "Protocol Buffers Configuring...") +endif() + +# CMake policies +cmake_policy(SET CMP0022 NEW) +# On MacOS use @rpath/ for target's install name prefix path +if (POLICY CMP0042) + cmake_policy(SET CMP0042 NEW) +endif () +# Clear VERSION variables when no VERSION is given to project() +if(POLICY CMP0048) + cmake_policy(SET CMP0048 NEW) +endif() +# MSVC runtime library flags are selected by an abstraction. +if(POLICY CMP0091) + cmake_policy(SET CMP0091 NEW) +endif() + +# Project +project(protobuf C CXX) + +# Add c++11 flags +if (CYGWIN) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11") +else() + set(CMAKE_CXX_STANDARD 11) + set(CMAKE_CXX_STANDARD_REQUIRED ON) + set(CMAKE_CXX_EXTENSIONS OFF) +endif() + +# The Intel compiler isn't able to deal with noinline member functions of +# template classes defined in headers. As such it spams the output with +# warning #2196: routine is both "inline" and "noinline" +# This silences that warning. +if (CMAKE_CXX_COMPILER_ID MATCHES Intel) + string(APPEND CMAKE_CXX_FLAGS " -diag-disable=2196") +endif() + +# Options +option(protobuf_INSTALL "Install protobuf binaries and files" ON) +if(WITH_PROTOC) + set(protobuf_PROTOC_EXE ${WITH_PROTOC} CACHE FILEPATH "Protocol Buffer Compiler executable" FORCE) +endif() +option(protobuf_BUILD_TESTS "Build tests" ON) +option(protobuf_BUILD_CONFORMANCE "Build conformance tests" OFF) +option(protobuf_BUILD_EXAMPLES "Build examples" OFF) +option(protobuf_BUILD_PROTOC_BINARIES "Build libprotoc and protoc compiler" ON) +option(protobuf_BUILD_LIBPROTOC "Build libprotoc" OFF) +option(protobuf_DISABLE_RTTI "Remove runtime type information in the binaries" OFF) +if (BUILD_SHARED_LIBS) + set(protobuf_BUILD_SHARED_LIBS_DEFAULT ON) +else (BUILD_SHARED_LIBS) + set(protobuf_BUILD_SHARED_LIBS_DEFAULT OFF) +endif (BUILD_SHARED_LIBS) +option(protobuf_BUILD_SHARED_LIBS "Build Shared Libraries" ${protobuf_BUILD_SHARED_LIBS_DEFAULT}) +include(CMakeDependentOption) +cmake_dependent_option(protobuf_MSVC_STATIC_RUNTIME "Link static runtime libraries" ON + "NOT protobuf_BUILD_SHARED_LIBS" OFF) +set(protobuf_WITH_ZLIB_DEFAULT ON) +option(protobuf_WITH_ZLIB "Build with zlib support" ${protobuf_WITH_ZLIB_DEFAULT}) +set(protobuf_DEBUG_POSTFIX "d" + CACHE STRING "Default debug postfix") +mark_as_advanced(protobuf_DEBUG_POSTFIX) +# User options +include(protobuf-options.cmake) + +# Overrides for option dependencies +if (protobuf_BUILD_PROTOC_BINARIES OR protobuf_BUILD_TESTS) + set(protobuf_BUILD_LIBPROTOC ON) +endif () +# Path to main configure script +set(protobuf_CONFIGURE_SCRIPT "../configure.ac") + +# Parse configure script +set(protobuf_AC_INIT_REGEX + "^AC_INIT\\(\\[([^]]+)\\],\\[([^]]+)\\],\\[([^]]+)\\],\\[([^]]+)\\]\\)$") +file(STRINGS "${protobuf_CONFIGURE_SCRIPT}" protobuf_AC_INIT_LINE + LIMIT_COUNT 1 REGEX "^AC_INIT") +# Description +string(REGEX REPLACE "${protobuf_AC_INIT_REGEX}" "\\1" + protobuf_DESCRIPTION "${protobuf_AC_INIT_LINE}") +# Version +string(REGEX REPLACE "${protobuf_AC_INIT_REGEX}" "\\2" + protobuf_VERSION_STRING "${protobuf_AC_INIT_LINE}") +# Contact +string(REGEX REPLACE "${protobuf_AC_INIT_REGEX}" "\\3" + protobuf_CONTACT "${protobuf_AC_INIT_LINE}") +# Parse version tweaks +set(protobuf_VERSION_REGEX "^([0-9]+)\\.([0-9]+)\\.([0-9]+)([-]rc[-]|\\.)?([0-9]*)$") +string(REGEX REPLACE "${protobuf_VERSION_REGEX}" "\\1" + protobuf_VERSION_MAJOR "${protobuf_VERSION_STRING}") +string(REGEX REPLACE "${protobuf_VERSION_REGEX}" "\\2" + protobuf_VERSION_MINOR "${protobuf_VERSION_STRING}") +string(REGEX REPLACE "${protobuf_VERSION_REGEX}" "\\3" + protobuf_VERSION_PATCH "${protobuf_VERSION_STRING}") +string(REGEX REPLACE "${protobuf_VERSION_REGEX}" "\\5" + protobuf_VERSION_PRERELEASE "${protobuf_VERSION_STRING}") + +message(STATUS "${protobuf_VERSION_PRERELEASE}") + +# Package version +set(protobuf_VERSION + "${protobuf_VERSION_MAJOR}.${protobuf_VERSION_MINOR}.${protobuf_VERSION_PATCH}") + +if(protobuf_VERSION_PRERELEASE) + set(protobuf_VERSION "${protobuf_VERSION}.${protobuf_VERSION_PRERELEASE}") +else() + set(protobuf_VERSION "${protobuf_VERSION}.0") +endif() +message(STATUS "${protobuf_VERSION}") + +if(protobuf_VERBOSE) + message(STATUS "Configuration script parsing status [") + message(STATUS " Description : ${protobuf_DESCRIPTION}") + message(STATUS " Version : ${protobuf_VERSION} (${protobuf_VERSION_STRING})") + message(STATUS " Contact : ${protobuf_CONTACT}") + message(STATUS "]") +endif() + +add_definitions(-DGOOGLE_PROTOBUF_CMAKE_BUILD) + +if (protobuf_DISABLE_RTTI) + add_definitions(-DGOOGLE_PROTOBUF_NO_RTTI=1) +endif() + +find_package(Threads REQUIRED) + +set(_protobuf_FIND_ZLIB) +if (protobuf_WITH_ZLIB) + find_package(ZLIB) + if (ZLIB_FOUND) + set(HAVE_ZLIB 1) + # FindZLIB module define ZLIB_INCLUDE_DIRS variable + # Set ZLIB_INCLUDE_DIRECTORIES for compatible + set(ZLIB_INCLUDE_DIRECTORIES ${ZLIB_INCLUDE_DIRECTORIES} ${ZLIB_INCLUDE_DIRS}) + # Using imported target if exists + if (TARGET ZLIB::ZLIB) + set(ZLIB_LIBRARIES ZLIB::ZLIB) + set(_protobuf_FIND_ZLIB "if(NOT ZLIB_FOUND)\n find_package(ZLIB)\nendif()") + endif (TARGET ZLIB::ZLIB) + else (ZLIB_FOUND) + set(HAVE_ZLIB 0) + # Explicitly set these to empty (override NOT_FOUND) so cmake doesn't + # complain when we use them later. + set(ZLIB_INCLUDE_DIRECTORIES) + set(ZLIB_LIBRARIES) + endif (ZLIB_FOUND) +endif (protobuf_WITH_ZLIB) + +if (HAVE_ZLIB) + add_definitions(-DHAVE_ZLIB) +endif (HAVE_ZLIB) + +# We need to link with libatomic on systems that do not have builtin atomics, or +# don't have builtin support for 8 byte atomics +set(protobuf_LINK_LIBATOMIC false) +if (NOT MSVC) + include(CheckCXXSourceCompiles) + set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS}) + set(CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS} -std=c++11) + check_cxx_source_compiles(" + #include + int main() { + return std::atomic{}; + } + " protobuf_HAVE_BUILTIN_ATOMICS) + if (NOT protobuf_HAVE_BUILTIN_ATOMICS) + set(protobuf_LINK_LIBATOMIC true) + endif (NOT protobuf_HAVE_BUILTIN_ATOMICS) + set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS}) +endif (NOT MSVC) + +if (protobuf_BUILD_SHARED_LIBS) + set(protobuf_SHARED_OR_STATIC "SHARED") +else (protobuf_BUILD_SHARED_LIBS) + set(protobuf_SHARED_OR_STATIC "STATIC") + # The CMAKE__FLAGS(_)? is meant to be user controlled. + # Prior to CMake 3.15, the MSVC runtime library was pushed into the same flags + # making programmatic control difficult. Prefer the functionality in newer + # CMake versions when available. + if(CMAKE_VERSION VERSION_GREATER 3.15 OR CMAKE_VERSION VERSION_EQUAL 3.15) + if (protobuf_MSVC_STATIC_RUNTIME) + set(CMAKE_MSVC_RUNTIME_LIBRARY MultiThreaded$<$:Debug>) + else() + set(CMAKE_MSVC_RUNTIME_LIBRARY MultiThreaded$<$:Debug>DLL) + endif() + else() + # In case we are building static libraries, link also the runtime library statically + # so that MSVCR*.DLL is not required at runtime. + # https://msdn.microsoft.com/en-us/library/2kzt1wy3.aspx + # This is achieved by replacing msvc option /MD with /MT and /MDd with /MTd + # http://www.cmake.org/Wiki/CMake_FAQ#How_can_I_build_my_MSVC_application_with_a_static_runtime.3F + if (MSVC AND protobuf_MSVC_STATIC_RUNTIME) + foreach(flag_var + CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE + CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO) + if(${flag_var} MATCHES "/MD") + string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}") + endif(${flag_var} MATCHES "/MD") + endforeach(flag_var) + endif (MSVC AND protobuf_MSVC_STATIC_RUNTIME) + endif() +endif (protobuf_BUILD_SHARED_LIBS) + +if (MSVC) + if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") + # Build with multiple processes + add_definitions(/MP) + endif() + # Set source file and execution character sets to UTF-8 + add_definitions(/utf-8) + # MSVC warning suppressions + add_definitions( + /wd4065 # switch statement contains 'default' but no 'case' labels + /wd4244 # 'conversion' conversion from 'type1' to 'type2', possible loss of data + /wd4251 # 'identifier' : class 'type' needs to have dll-interface to be used by clients of class 'type2' + /wd4267 # 'var' : conversion from 'size_t' to 'type', possible loss of data + /wd4305 # 'identifier' : truncation from 'type1' to 'type2' + /wd4307 # 'operator' : integral constant overflow + /wd4309 # 'conversion' : truncation of constant value + /wd4334 # 'operator' : result of 32-bit shift implicitly converted to 64 bits (was 64-bit shift intended?) + /wd4355 # 'this' : used in base member initializer list + /wd4506 # no definition for inline function 'function' + /wd4800 # 'type' : forcing value to bool 'true' or 'false' (performance warning) + /wd4996 # The compiler encountered a deprecated declaration. + ) + # Allow big object + add_definitions(/bigobj) + string(REPLACE "/" "\\" PROTOBUF_SOURCE_WIN32_PATH ${protobuf_SOURCE_DIR}) + string(REPLACE "/" "\\" PROTOBUF_BINARY_WIN32_PATH ${protobuf_BINARY_DIR}) + string(REPLACE "." "," protobuf_RC_FILEVERSION "${protobuf_VERSION}") + configure_file(extract_includes.bat.in extract_includes.bat) + + # Suppress linker warnings about files with no symbols defined. + set(CMAKE_STATIC_LINKER_FLAGS "${CMAKE_STATIC_LINKER_FLAGS} /ignore:4221") + + if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") + # Configure Resource Compiler + enable_language(RC) + # use English language (0x409) in resource compiler + set(rc_flags "/l0x409") + # fix rc.exe invocations because of usage of add_definitions() + set(CMAKE_RC_COMPILE_OBJECT " ${rc_flags} /fo ") + endif() + + configure_file(version.rc.in ${CMAKE_CURRENT_BINARY_DIR}/version.rc @ONLY) +endif (MSVC) + + +get_filename_component(protobuf_source_dir ${protobuf_SOURCE_DIR} PATH) + +include_directories( + ${ZLIB_INCLUDE_DIRECTORIES} + ${protobuf_BINARY_DIR} + ${protobuf_source_dir}/src) + +if (MSVC) + # Add the "lib" prefix for generated .lib outputs. + set(LIB_PREFIX lib) +else (MSVC) + # When building with "make", "lib" prefix will be added automatically by + # the build tool. + set(LIB_PREFIX) +endif (MSVC) + +if (protobuf_UNICODE) + add_definitions(-DUNICODE -D_UNICODE) +endif (protobuf_UNICODE) + +include(libprotobuf-lite.cmake) +include(libprotobuf.cmake) +if (protobuf_BUILD_LIBPROTOC) + include(libprotoc.cmake) +endif (protobuf_BUILD_LIBPROTOC) +if (protobuf_BUILD_PROTOC_BINARIES) + include(protoc.cmake) + if (NOT DEFINED protobuf_PROTOC_EXE) + set(protobuf_PROTOC_EXE protoc) + endif (NOT DEFINED protobuf_PROTOC_EXE) +endif (protobuf_BUILD_PROTOC_BINARIES) + +# Ensure we have a protoc executable if we need one +if (protobuf_BUILD_TESTS OR protobuf_BUILD_CONFORMANCE OR protobuf_BUILD_EXAMPLES) + if (NOT DEFINED protobuf_PROTOC_EXE) + find_program(protobuf_PROTOC_EXE protoc) + if (NOT protobuf_PROTOC_EXE) + message(FATAL "Build requires 'protoc' but binary not found and not building protoc.") + endif () + endif () + if(protobuf_VERBOSE) + message(STATUS "Using protoc : ${protobuf_PROTOC_EXE}") + endif(protobuf_VERBOSE) +endif () + +if (protobuf_BUILD_TESTS) + enable_testing() + include(tests.cmake) +endif (protobuf_BUILD_TESTS) + +if (protobuf_BUILD_CONFORMANCE) + include(conformance.cmake) +endif (protobuf_BUILD_CONFORMANCE) + +if (protobuf_INSTALL) + include(install.cmake) +endif (protobuf_INSTALL) + +if (protobuf_BUILD_EXAMPLES) + include(examples.cmake) +endif (protobuf_BUILD_EXAMPLES) + +if(protobuf_VERBOSE) + message(STATUS "Protocol Buffers Configuring done") +endif(protobuf_VERBOSE) diff --git a/tools/env-vars-generator/protobuf/cmake/libprotoc.cmake b/tools/env-vars-generator/protobuf/cmake/libprotoc.cmake new file mode 100644 index 0000000..6f04331 --- /dev/null +++ b/tools/env-vars-generator/protobuf/cmake/libprotoc.cmake @@ -0,0 +1,132 @@ +set(libprotoc_files + ${protobuf_source_dir}/src/google/protobuf/compiler/code_generator.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/command_line_interface.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_enum.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_enum_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_extension.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_file.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_generator.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_helpers.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_map_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_message.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_message_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_parse_function_generator.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_service.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_string_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_doc_comment.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_enum.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_enum_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_field_base.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_generator.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_helpers.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_map_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_message.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_message_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_reflection_class.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_source_generator_base.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_context.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_doc_comment.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_enum.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_enum_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_enum_field_lite.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_enum_lite.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_extension.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_extension_lite.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_file.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_generator.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_generator_factory.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_helpers.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_kotlin_generator.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_map_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_map_field_lite.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message_builder.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message_builder_lite.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message_field_lite.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message_lite.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_name_resolver.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_primitive_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_primitive_field_lite.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_service.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_shared_code_generator.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_string_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_string_field_lite.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/js/js_generator.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/js/well_known_types_embed.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_enum.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_enum_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_extension.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_file.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_generator.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_map_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_message.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_message_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_oneof.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/php/php_generator.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/plugin.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/plugin.pb.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/python/python_generator.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/ruby/ruby_generator.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/subprocess.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/zip_writer.cc +) + +set(libprotoc_headers + ${protobuf_source_dir}/src/google/protobuf/compiler/code_generator.h + ${protobuf_source_dir}/src/google/protobuf/compiler/command_line_interface.h + ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_file.h + ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_generator.h + ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_helpers.h + ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_names.h + ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_doc_comment.h + ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_generator.h + ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_names.h + ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_options.h + ${protobuf_source_dir}/src/google/protobuf/compiler/importer.h + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_generator.h + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_kotlin_generator.h + ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_names.h + ${protobuf_source_dir}/src/google/protobuf/compiler/js/js_generator.h + ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_generator.h + ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_helpers.h + ${protobuf_source_dir}/src/google/protobuf/compiler/parser.h + ${protobuf_source_dir}/src/google/protobuf/compiler/php/php_generator.h + ${protobuf_source_dir}/src/google/protobuf/compiler/plugin.h + ${protobuf_source_dir}/src/google/protobuf/compiler/plugin.pb.h + ${protobuf_source_dir}/src/google/protobuf/compiler/python/python_generator.h + ${protobuf_source_dir}/src/google/protobuf/compiler/ruby/ruby_generator.h +) + +if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") +set(libprotoc_rc_files + ${CMAKE_CURRENT_BINARY_DIR}/version.rc +) +endif() + +add_library(libprotoc ${protobuf_SHARED_OR_STATIC} + ${libprotoc_files} ${libprotoc_headers} ${libprotoc_rc_files}) +target_link_libraries(libprotoc libprotobuf) +if(MSVC AND protobuf_BUILD_SHARED_LIBS) + target_compile_definitions(libprotoc + PUBLIC PROTOBUF_USE_DLLS + PRIVATE LIBPROTOC_EXPORTS) +endif() +set_target_properties(libprotoc PROPERTIES + COMPILE_DEFINITIONS LIBPROTOC_EXPORTS + VERSION ${protobuf_VERSION} + OUTPUT_NAME ${LIB_PREFIX}protoc + DEBUG_POSTFIX "${protobuf_DEBUG_POSTFIX}") +add_library(protobuf::libprotoc ALIAS libprotoc) diff --git a/tools/env-vars-generator/protobuf/cmake/protobuf-lite.pc.cmake b/tools/env-vars-generator/protobuf/cmake/protobuf-lite.pc.cmake new file mode 100644 index 0000000..9745cb8 --- /dev/null +++ b/tools/env-vars-generator/protobuf/cmake/protobuf-lite.pc.cmake @@ -0,0 +1,11 @@ +prefix=@CMAKE_INSTALL_PREFIX@ +exec_prefix=@CMAKE_INSTALL_PREFIX@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ + +Name: Protocol Buffers +Description: Google's Data Interchange Format +Version: @protobuf_VERSION@ +Libs: -L${libdir} -lprotobuf-lite @CMAKE_THREAD_LIBS_INIT@ +Cflags: -I${includedir} +Conflicts: protobuf diff --git a/tools/env-vars-generator/protobuf/cmake/version.rc.in b/tools/env-vars-generator/protobuf/cmake/version.rc.in new file mode 100644 index 0000000..f6e7c4a --- /dev/null +++ b/tools/env-vars-generator/protobuf/cmake/version.rc.in @@ -0,0 +1,45 @@ +#define VS_FF_DEBUG 0x1L +#define VS_VERSION_INFO 0x1L +#define VS_FFI_FILEFLAGSMASK 0x17L +#define VER_PRIVATEBUILD 0x0L +#define VER_PRERELEASE 0x0L +#define VOS__WINDOWS32 0x4L +#define VFT_DLL 0x2L +#define VFT2_UNKNOWN 0x0L + +#ifndef DEBUG +#define VER_DEBUG 0 +#else +#define VER_DEBUG VS_FF_DEBUG +#endif + + +VS_VERSION_INFO VERSIONINFO + FILEVERSION @protobuf_RC_FILEVERSION@ + PRODUCTVERSION @protobuf_RC_FILEVERSION@ + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK + FILEFLAGS VER_DEBUG + FILEOS VOS__WINDOWS32 + FILETYPE VFT_DLL +BEGIN + BLOCK "VarFileInfo" + BEGIN + // English language (0x409) and the Windows Unicode codepage (1200) + VALUE "Translation", 0x409, 1200 + END + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "FileDescription", "Compiled with @CMAKE_CXX_COMPILER_ID@ @CMAKE_CXX_COMPILER_VERSION@\0" + VALUE "ProductVersion", "@protobuf_VERSION@\0" + VALUE "FileVersion", "@protobuf_VERSION@\0" + VALUE "InternalName", "protobuf\0" + VALUE "ProductName", "Protocol Buffers - Google's Data Interchange Format\0" + VALUE "CompanyName", "Google Inc.\0" + VALUE "LegalCopyright", "Copyright 2008 Google Inc. All rights reserved.\0" + VALUE "Licence", "BSD\0" + VALUE "Info", "https://developers.google.com/protocol-buffers/\0" + END + END +END diff --git a/tools/env-vars-generator/protobuf/conformance/failure_list_objc.txt b/tools/env-vars-generator/protobuf/conformance/failure_list_objc.txt new file mode 100644 index 0000000..e34501e --- /dev/null +++ b/tools/env-vars-generator/protobuf/conformance/failure_list_objc.txt @@ -0,0 +1,2 @@ +# JSON input or output tests are skipped (in conformance_objc.m) as mobile +# platforms don't support JSON wire format to avoid code bloat. diff --git a/tools/env-vars-generator/protobuf/conformance/failure_list_php.txt b/tools/env-vars-generator/protobuf/conformance/failure_list_php.txt new file mode 100644 index 0000000..667f80c --- /dev/null +++ b/tools/env-vars-generator/protobuf/conformance/failure_list_php.txt @@ -0,0 +1,30 @@ +Recommended.FieldMaskNumbersDontRoundTrip.JsonOutput +Recommended.FieldMaskPathsDontRoundTrip.JsonOutput +Recommended.FieldMaskTooManyUnderscore.JsonOutput +Recommended.Proto2.JsonInput.FieldNameExtension.Validator +Recommended.Proto3.JsonInput.BytesFieldBase64Url.JsonOutput +Recommended.Proto3.JsonInput.BytesFieldBase64Url.ProtobufOutput +Recommended.Proto3.JsonInput.FieldMaskInvalidCharacter +Recommended.Proto3.ProtobufInput.ValidDataOneofBinary.MESSAGE.Merge.ProtobufOutput +Required.Proto2.JsonInput.StoresDefaultPrimitive.Validator +Required.Proto3.JsonInput.DoubleFieldTooSmall +Required.Proto3.JsonInput.FloatFieldTooLarge +Required.Proto3.JsonInput.FloatFieldTooSmall +Required.Proto3.JsonInput.Int32FieldNotInteger +Required.Proto3.JsonInput.Int64FieldNotInteger +Required.Proto3.JsonInput.OneofFieldDuplicate +Required.Proto3.JsonInput.OneofFieldNullSecond.JsonOutput +Required.Proto3.JsonInput.OneofFieldNullSecond.ProtobufOutput +Required.Proto3.JsonInput.RepeatedFieldWrongElementTypeExpectingStringsGotInt +Required.Proto3.JsonInput.RepeatedListValue.JsonOutput +Required.Proto3.JsonInput.RepeatedListValue.ProtobufOutput +Required.Proto3.JsonInput.StringFieldNotAString +Required.Proto3.JsonInput.Uint32FieldNotInteger +Required.Proto3.JsonInput.Uint64FieldNotInteger +Required.Proto3.ProtobufInput.RepeatedScalarMessageMerge.JsonOutput +Required.Proto3.ProtobufInput.RepeatedScalarMessageMerge.ProtobufOutput +Required.Proto3.ProtobufInput.ValidDataOneof.MESSAGE.Merge.JsonOutput +Required.Proto3.ProtobufInput.ValidDataOneof.MESSAGE.Merge.ProtobufOutput +Required.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.PackedInput.JsonOutput +Required.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.UnpackedInput.JsonOutput +Required.Proto3.ProtobufInput.ValidDataScalar.FLOAT[2].JsonOutput diff --git a/tools/env-vars-generator/protobuf/conformance/failure_list_python-post26.txt b/tools/env-vars-generator/protobuf/conformance/failure_list_python-post26.txt new file mode 100644 index 0000000..19d99b0 --- /dev/null +++ b/tools/env-vars-generator/protobuf/conformance/failure_list_python-post26.txt @@ -0,0 +1,2 @@ +JsonInput.StringFieldSurrogateInWrongOrder +JsonInput.StringFieldUnpairedHighSurrogate diff --git a/tools/env-vars-generator/protobuf/conformance/failure_list_ruby.txt b/tools/env-vars-generator/protobuf/conformance/failure_list_ruby.txt new file mode 100644 index 0000000..4938202 --- /dev/null +++ b/tools/env-vars-generator/protobuf/conformance/failure_list_ruby.txt @@ -0,0 +1,58 @@ +Recommended.Proto2.JsonInput.FieldNameExtension.Validator +Recommended.Proto2.ProtobufInput.ValidDataRepeated.BOOL.PackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.BOOL.UnpackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.DOUBLE.PackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.DOUBLE.UnpackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.ENUM.PackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.ENUM.UnpackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.FIXED32.PackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.FIXED32.UnpackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.FIXED64.PackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.FIXED64.UnpackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.FLOAT.PackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.FLOAT.UnpackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.INT32.PackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.INT32.UnpackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.INT64.PackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.INT64.UnpackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.SFIXED32.PackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.SFIXED32.UnpackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.SFIXED64.PackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.SFIXED64.UnpackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.SINT32.PackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.SINT32.UnpackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.SINT64.PackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.SINT64.UnpackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.UINT32.PackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.UINT32.UnpackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.UINT64.PackedInput.PackedOutput.ProtobufOutput +Recommended.Proto2.ProtobufInput.ValidDataRepeated.UINT64.UnpackedInput.PackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataOneofBinary.MESSAGE.Merge.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.BOOL.PackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.BOOL.UnpackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.DOUBLE.PackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.DOUBLE.UnpackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.ENUM.PackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.ENUM.UnpackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED32.PackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED32.UnpackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED64.PackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.FIXED64.UnpackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.PackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.UnpackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT32.PackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT32.UnpackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT64.PackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.INT64.UnpackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED32.PackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED32.UnpackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED64.PackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.SFIXED64.UnpackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT32.PackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT32.UnpackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT64.PackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.SINT64.UnpackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT32.PackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT32.UnpackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT64.PackedInput.UnpackedOutput.ProtobufOutput +Recommended.Proto3.ProtobufInput.ValidDataRepeated.UINT64.UnpackedInput.UnpackedOutput.ProtobufOutput diff --git a/tools/env-vars-generator/protobuf/conformance/text_format_conformance_suite.cc b/tools/env-vars-generator/protobuf/conformance/text_format_conformance_suite.cc new file mode 100644 index 0000000..460bc24 --- /dev/null +++ b/tools/env-vars-generator/protobuf/conformance/text_format_conformance_suite.cc @@ -0,0 +1,478 @@ +// 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. + +#include "text_format_conformance_suite.h" + +#include +#include +#include "conformance_test.h" +#include +#include + +namespace proto2_messages = protobuf_test_messages::proto2; + +using conformance::ConformanceRequest; +using conformance::ConformanceResponse; +using conformance::WireFormat; +using google::protobuf::Message; +using google::protobuf::TextFormat; +using proto2_messages::TestAllTypesProto2; +using proto2_messages::UnknownToTestAllTypes; +using protobuf_test_messages::proto3::TestAllTypesProto3; +using std::string; + +namespace google { +namespace protobuf { + +TextFormatConformanceTestSuite::TextFormatConformanceTestSuite() { + SetFailureListFlagName("--text_format_failure_list"); +} + +bool TextFormatConformanceTestSuite::ParseTextFormatResponse( + const ConformanceResponse& response, + const ConformanceRequestSetting& setting, Message* test_message) { + TextFormat::Parser parser; + const ConformanceRequest& request = setting.GetRequest(); + if (request.print_unknown_fields()) { + parser.AllowFieldNumber(true); + } + if (!parser.ParseFromString(response.text_payload(), test_message)) { + GOOGLE_LOG(ERROR) << "INTERNAL ERROR: internal text->protobuf transcode " + << "yielded unparseable proto. Text payload: " + << response.text_payload(); + return false; + } + + return true; +} + +bool TextFormatConformanceTestSuite::ParseResponse( + const ConformanceResponse& response, + const ConformanceRequestSetting& setting, Message* test_message) { + const ConformanceRequest& request = setting.GetRequest(); + WireFormat requested_output = request.requested_output_format(); + const string& test_name = setting.GetTestName(); + ConformanceLevel level = setting.GetLevel(); + + switch (response.result_case()) { + case ConformanceResponse::kProtobufPayload: { + if (requested_output != conformance::PROTOBUF) { + ReportFailure(test_name, level, request, response, + StrCat("Test was asked for ", + WireFormatToString(requested_output), + " output but provided PROTOBUF instead.") + .c_str()); + return false; + } + + if (!test_message->ParseFromString(response.protobuf_payload())) { + ReportFailure(test_name, level, request, response, + "Protobuf output we received from test was unparseable."); + return false; + } + + break; + } + + case ConformanceResponse::kTextPayload: { + if (requested_output != conformance::TEXT_FORMAT) { + ReportFailure(test_name, level, request, response, + StrCat("Test was asked for ", + WireFormatToString(requested_output), + " output but provided TEXT_FORMAT instead.") + .c_str()); + return false; + } + + if (!ParseTextFormatResponse(response, setting, test_message)) { + ReportFailure( + test_name, level, request, response, + "TEXT_FORMAT output we received from test was unparseable."); + return false; + } + + break; + } + + default: + GOOGLE_LOG(FATAL) << test_name + << ": unknown payload type: " << response.result_case(); + } + + return true; +} + +void TextFormatConformanceTestSuite::ExpectParseFailure(const string& test_name, + ConformanceLevel level, + const string& input) { + TestAllTypesProto3 prototype; + // We don't expect output, but if the program erroneously accepts the protobuf + // we let it send its response as this. We must not leave it unspecified. + ConformanceRequestSetting setting( + level, conformance::TEXT_FORMAT, conformance::TEXT_FORMAT, + conformance::TEXT_FORMAT_TEST, prototype, test_name, input); + const ConformanceRequest& request = setting.GetRequest(); + ConformanceResponse response; + string effective_test_name = + StrCat(setting.ConformanceLevelToString(level), + ".Proto3.TextFormatInput.", test_name); + + RunTest(effective_test_name, request, &response); + if (response.result_case() == ConformanceResponse::kParseError) { + ReportSuccess(effective_test_name); + } else if (response.result_case() == ConformanceResponse::kSkipped) { + ReportSkip(effective_test_name, request, response); + } else { + ReportFailure(effective_test_name, level, request, response, + "Should have failed to parse, but didn't."); + } +} + +void TextFormatConformanceTestSuite::RunValidTextFormatTest( + const string& test_name, ConformanceLevel level, const string& input_text) { + TestAllTypesProto3 prototype; + RunValidTextFormatTestWithMessage(test_name, level, input_text, prototype); +} + +void TextFormatConformanceTestSuite::RunValidTextFormatTestProto2( + const string& test_name, ConformanceLevel level, const string& input_text) { + TestAllTypesProto2 prototype; + RunValidTextFormatTestWithMessage(test_name, level, input_text, prototype); +} + +void TextFormatConformanceTestSuite::RunValidTextFormatTestWithMessage( + const string& test_name, ConformanceLevel level, const string& input_text, + const Message& prototype) { + ConformanceRequestSetting setting1( + level, conformance::TEXT_FORMAT, conformance::PROTOBUF, + conformance::TEXT_FORMAT_TEST, prototype, test_name, input_text); + RunValidInputTest(setting1, input_text); + ConformanceRequestSetting setting2( + level, conformance::TEXT_FORMAT, conformance::TEXT_FORMAT, + conformance::TEXT_FORMAT_TEST, prototype, test_name, input_text); + RunValidInputTest(setting2, input_text); +} + +void TextFormatConformanceTestSuite::RunValidUnknownTextFormatTest( + const string& test_name, const Message& message) { + string serialized_input; + message.SerializeToString(&serialized_input); + TestAllTypesProto3 prototype; + ConformanceRequestSetting setting1( + RECOMMENDED, conformance::PROTOBUF, conformance::TEXT_FORMAT, + conformance::TEXT_FORMAT_TEST, prototype, test_name + "_Drop", + serialized_input); + setting1.SetPrototypeMessageForCompare(message); + RunValidBinaryInputTest(setting1, ""); + + ConformanceRequestSetting setting2( + RECOMMENDED, conformance::PROTOBUF, conformance::TEXT_FORMAT, + conformance::TEXT_FORMAT_TEST, prototype, test_name + "_Print", + serialized_input); + setting2.SetPrototypeMessageForCompare(message); + setting2.SetPrintUnknownFields(true); + RunValidBinaryInputTest(setting2, serialized_input); +} + +void TextFormatConformanceTestSuite::RunSuiteImpl() { + RunValidTextFormatTest("HelloWorld", REQUIRED, + "optional_string: 'Hello, World!'"); + // Integer fields. + RunValidTextFormatTest("Int32FieldMaxValue", REQUIRED, + "optional_int32: 2147483647"); + RunValidTextFormatTest("Int32FieldMinValue", REQUIRED, + "optional_int32: -2147483648"); + RunValidTextFormatTest("Uint32FieldMaxValue", REQUIRED, + "optional_uint32: 4294967295"); + RunValidTextFormatTest("Int64FieldMaxValue", REQUIRED, + "optional_int64: 9223372036854775807"); + RunValidTextFormatTest("Int64FieldMinValue", REQUIRED, + "optional_int64: -9223372036854775808"); + RunValidTextFormatTest("Uint64FieldMaxValue", REQUIRED, + "optional_uint64: 18446744073709551615"); + + // Parsers reject out-of-bound integer values. + ExpectParseFailure("Int32FieldTooLarge", REQUIRED, + "optional_int32: 2147483648"); + ExpectParseFailure("Int32FieldTooSmall", REQUIRED, + "optional_int32: -2147483649"); + ExpectParseFailure("Uint32FieldTooLarge", REQUIRED, + "optional_uint32: 4294967296"); + ExpectParseFailure("Int64FieldTooLarge", REQUIRED, + "optional_int64: 9223372036854775808"); + ExpectParseFailure("Int64FieldTooSmall", REQUIRED, + "optional_int64: -9223372036854775809"); + ExpectParseFailure("Uint64FieldTooLarge", REQUIRED, + "optional_uint64: 18446744073709551616"); + + // Floating point fields + RunValidTextFormatTest("FloatField", REQUIRED, + "optional_float: 3.192837"); + RunValidTextFormatTest("FloatFieldWithVeryPreciseNumber", REQUIRED, + "optional_float: 3.123456789123456789"); + RunValidTextFormatTest("FloatFieldMaxValue", REQUIRED, + "optional_float: 3.4028235e+38"); + RunValidTextFormatTest("FloatFieldMinValue", REQUIRED, + "optional_float: 1.17549e-38"); + RunValidTextFormatTest("FloatFieldNaNValue", REQUIRED, + "optional_float: NaN"); + RunValidTextFormatTest("FloatFieldPosInfValue", REQUIRED, + "optional_float: inf"); + RunValidTextFormatTest("FloatFieldNegInfValue", REQUIRED, + "optional_float: -inf"); + RunValidTextFormatTest("FloatFieldWithInt32Max", REQUIRED, + "optional_float: 4294967296"); + RunValidTextFormatTest("FloatFieldLargerThanInt64", REQUIRED, + "optional_float: 9223372036854775808"); + RunValidTextFormatTest("FloatFieldTooLarge", REQUIRED, + "optional_float: 3.4028235e+39"); + RunValidTextFormatTest("FloatFieldTooSmall", REQUIRED, + "optional_float: 1.17549e-39"); + RunValidTextFormatTest("FloatFieldLargerThanUint64", REQUIRED, + "optional_float: 18446744073709551616"); + + // String literals x {Strings, Bytes} + for (const auto& field_type : std::vector{"String", "Bytes"}) { + const std::string field_name = + field_type == "String" ? "optional_string" : "optional_bytes"; + RunValidTextFormatTest( + StrCat("StringLiteralConcat", field_type), REQUIRED, + StrCat(field_name, ": 'first' \"second\"\n'third'")); + RunValidTextFormatTest( + StrCat("StringLiteralBasicEscapes", field_type), REQUIRED, + StrCat(field_name, ": '\\a\\b\\f\\n\\r\\t\\v\\?\\\\\\'\\\"'")); + RunValidTextFormatTest( + StrCat("StringLiteralOctalEscapes", field_type), REQUIRED, + StrCat(field_name, ": '\\341\\210\\264'")); + RunValidTextFormatTest(StrCat("StringLiteralHexEscapes", field_type), + REQUIRED, + StrCat(field_name, ": '\\xe1\\x88\\xb4'")); + RunValidTextFormatTest( + StrCat("StringLiteralShortUnicodeEscape", field_type), + RECOMMENDED, StrCat(field_name, ": '\\u1234'")); + RunValidTextFormatTest( + StrCat("StringLiteralLongUnicodeEscapes", field_type), + RECOMMENDED, StrCat(field_name, ": '\\U00001234\\U00010437'")); + // String literals don't include line feeds. + ExpectParseFailure(StrCat("StringLiteralIncludesLF", field_type), + REQUIRED, + StrCat(field_name, ": 'first line\nsecond line'")); + // Unicode escapes don't include code points that lie beyond the planes + // (> 0x10ffff). + ExpectParseFailure( + StrCat("StringLiteralLongUnicodeEscapeTooLarge", field_type), + REQUIRED, StrCat(field_name, ": '\\U00110000'")); + // Unicode escapes don't include surrogates. + ExpectParseFailure( + StrCat("StringLiteralShortUnicodeEscapeSurrogatePair", + field_type), + RECOMMENDED, StrCat(field_name, ": '\\ud801\\udc37'")); + ExpectParseFailure( + StrCat("StringLiteralShortUnicodeEscapeSurrogateFirstOnly", + field_type), + RECOMMENDED, StrCat(field_name, ": '\\ud800'")); + ExpectParseFailure( + StrCat("StringLiteralShortUnicodeEscapeSurrogateSecondOnly", + field_type), + RECOMMENDED, StrCat(field_name, ": '\\udc00'")); + ExpectParseFailure( + StrCat("StringLiteralLongUnicodeEscapeSurrogateFirstOnly", + field_type), + RECOMMENDED, StrCat(field_name, ": '\\U0000d800'")); + ExpectParseFailure( + StrCat("StringLiteralLongUnicodeEscapeSurrogateSecondOnly", + field_type), + RECOMMENDED, StrCat(field_name, ": '\\U0000dc00'")); + ExpectParseFailure( + StrCat("StringLiteralLongUnicodeEscapeSurrogatePair", field_type), + RECOMMENDED, StrCat(field_name, ": '\\U0000d801\\U00000dc37'")); + ExpectParseFailure( + StrCat("StringLiteralUnicodeEscapeSurrogatePairLongShort", + field_type), + RECOMMENDED, StrCat(field_name, ": '\\U0000d801\\udc37'")); + ExpectParseFailure( + StrCat("StringLiteralUnicodeEscapeSurrogatePairShortLong", + field_type), + RECOMMENDED, StrCat(field_name, ": '\\ud801\\U0000dc37'")); + + // The following method depend on the type of field, as strings have extra + // validation. + const auto test_method = + field_type == "String" + ? &TextFormatConformanceTestSuite::ExpectParseFailure + : &TextFormatConformanceTestSuite::RunValidTextFormatTest; + + // String fields reject invalid UTF-8 byte sequences; bytes fields don't. + (this->*test_method)(StrCat(field_type, "FieldBadUTF8Octal"), + REQUIRED, StrCat(field_name, ": '\\300'")); + (this->*test_method)(StrCat(field_type, "FieldBadUTF8Hex"), REQUIRED, + StrCat(field_name, ": '\\xc0'")); + } + + // Group fields + RunValidTextFormatTestProto2("GroupFieldNoColon", REQUIRED, + "Data { group_int32: 1 }"); + RunValidTextFormatTestProto2("GroupFieldWithColon", REQUIRED, + "Data: { group_int32: 1 }"); + RunValidTextFormatTestProto2("GroupFieldEmpty", REQUIRED, + "Data {}"); + + + // Unknown Fields + UnknownToTestAllTypes message; + // Unable to print unknown Fixed32/Fixed64 fields as if they are known. + // Fixed32/Fixed64 fields are not added in the tests. + message.set_optional_int32(123); + message.set_optional_string("hello"); + message.set_optional_bool(true); + RunValidUnknownTextFormatTest("ScalarUnknownFields", message); + + message.Clear(); + message.mutable_nested_message()->set_c(111); + RunValidUnknownTextFormatTest("MessageUnknownFields", message); + + message.Clear(); + message.mutable_optionalgroup()->set_a(321); + RunValidUnknownTextFormatTest("GroupUnknownFields", message); + + message.add_repeated_int32(1); + message.add_repeated_int32(2); + message.add_repeated_int32(3); + RunValidUnknownTextFormatTest("RepeatedUnknownFields", message); + + // Any fields + RunValidTextFormatTest("AnyField", REQUIRED, + R"( + optional_any: { + [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] { + optional_int32: 12345 + } + } + )"); + RunValidTextFormatTest("AnyFieldWithRawBytes", REQUIRED, + R"( + optional_any: { + type_url: "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3" + value: "\b\271`" + } + )"); + ExpectParseFailure("AnyFieldWithInvalidType", REQUIRED, + R"( + optional_any: { + [type.googleapis.com/unknown] { + optional_int32: 12345 + } + } + )"); + + // Map fields + TestAllTypesProto3 prototype; + (*prototype.mutable_map_string_string())["c"] = "value"; + (*prototype.mutable_map_string_string())["b"] = "value"; + (*prototype.mutable_map_string_string())["a"] = "value"; + RunValidTextFormatTestWithMessage("AlphabeticallySortedMapStringKeys", + REQUIRED, + R"( + map_string_string { + key: "a" + value: "value" + } + map_string_string { + key: "b" + value: "value" + } + map_string_string { + key: "c" + value: "value" + } + )", + prototype); + + prototype.Clear(); + (*prototype.mutable_map_int32_int32())[3] = 0; + (*prototype.mutable_map_int32_int32())[2] = 0; + (*prototype.mutable_map_int32_int32())[1] = 0; + RunValidTextFormatTestWithMessage("AlphabeticallySortedMapIntKeys", REQUIRED, + R"( + map_int32_int32 { + key: 1 + value: 0 + } + map_int32_int32 { + key: 2 + value: 0 + } + map_int32_int32 { + key: 3 + value: 0 + } + )", + prototype); + + prototype.Clear(); + (*prototype.mutable_map_bool_bool())[true] = false; + (*prototype.mutable_map_bool_bool())[false] = false; + RunValidTextFormatTestWithMessage("AlphabeticallySortedMapBoolKeys", REQUIRED, + R"( + map_bool_bool { + key: false + value: false + } + map_bool_bool { + key: true + value: false + } + )", + prototype); + + prototype.Clear(); + ConformanceRequestSetting setting_map( + REQUIRED, conformance::TEXT_FORMAT, conformance::PROTOBUF, + conformance::TEXT_FORMAT_TEST, prototype, "DuplicateMapKey", R"( + map_string_nested_message { + key: "duplicate" + value: { a: 123 } + } + map_string_nested_message { + key: "duplicate" + value: { corecursive: {} } + } + )"); + // The last-specified value will be retained in a parsed map + RunValidInputTest(setting_map, R"( + map_string_nested_message { + key: "duplicate" + value: { corecursive: {} } + } + )"); +} + +} // namespace protobuf +} // namespace google diff --git a/tools/env-vars-generator/protobuf/conformance/third_party/jsoncpp/json.h b/tools/env-vars-generator/protobuf/conformance/third_party/jsoncpp/json.h new file mode 100644 index 0000000..373ec98 --- /dev/null +++ b/tools/env-vars-generator/protobuf/conformance/third_party/jsoncpp/json.h @@ -0,0 +1,2075 @@ +/// Json-cpp amalgated header (http://jsoncpp.sourceforge.net/). +/// It is intended to be used with #include "json/json.h" + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: LICENSE +// ////////////////////////////////////////////////////////////////////// + +/* +The JsonCpp library's source code, including accompanying documentation, +tests and demonstration applications, are licensed under the following +conditions... + +The author (Baptiste Lepilleur) explicitly disclaims copyright in all +jurisdictions which recognize such a disclaimer. In such jurisdictions, +this software is released into the Public Domain. + +In jurisdictions which do not recognize Public Domain property (e.g. Germany as of +2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is +released under the terms of the MIT License (see below). + +In jurisdictions which recognize Public Domain property, the user of this +software may choose to accept it either as 1) Public Domain, 2) under the +conditions of the MIT License (see below), or 3) under the terms of dual +Public Domain/MIT License conditions described here, as they choose. + +The MIT License is about as close to Public Domain as a license can get, and is +described in clear, concise terms at: + + http://en.wikipedia.org/wiki/MIT_License + +The full text of the MIT License follows: + +======================================================================== +Copyright (c) 2007-2010 Baptiste Lepilleur + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, copy, +modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +======================================================================== +(END LICENSE TEXT) + +The MIT license is compatible with both the GPL and commercial +software, affording one all of the rights of Public Domain with the +minor nuisance of being required to keep the above copyright notice +and license text in the source code. Note also that by accepting the +Public Domain "license" you can re-license your copy using whatever +license you like. + +*/ + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: LICENSE +// ////////////////////////////////////////////////////////////////////// + + + + + +#ifndef JSON_AMALGATED_H_INCLUDED +# define JSON_AMALGATED_H_INCLUDED +/// If defined, indicates that the source file is amalgated +/// to prevent private header inclusion. +#define JSON_IS_AMALGAMATION + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/version.h +// ////////////////////////////////////////////////////////////////////// + +// DO NOT EDIT. This file (and "version") is generated by CMake. +// Run CMake configure step to update it. +#ifndef JSON_VERSION_H_INCLUDED +# define JSON_VERSION_H_INCLUDED + +# define JSONCPP_VERSION_STRING "1.6.5" +# define JSONCPP_VERSION_MAJOR 1 +# define JSONCPP_VERSION_MINOR 6 +# define JSONCPP_VERSION_PATCH 5 +# define JSONCPP_VERSION_QUALIFIER +# define JSONCPP_VERSION_HEXA ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | (JSONCPP_VERSION_PATCH << 8)) + +#endif // JSON_VERSION_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/version.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/config.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef JSON_CONFIG_H_INCLUDED +#define JSON_CONFIG_H_INCLUDED + +/// If defined, indicates that json library is embedded in CppTL library. +//# define JSON_IN_CPPTL 1 + +/// If defined, indicates that json may leverage CppTL library +//# define JSON_USE_CPPTL 1 +/// If defined, indicates that cpptl vector based map should be used instead of +/// std::map +/// as Value container. +//# define JSON_USE_CPPTL_SMALLMAP 1 + +// If non-zero, the library uses exceptions to report bad input instead of C +// assertion macros. The default is to use exceptions. +#ifndef JSON_USE_EXCEPTION +#define JSON_USE_EXCEPTION 1 +#endif + +/// If defined, indicates that the source file is amalgated +/// to prevent private header inclusion. +/// Remarks: it is automatically defined in the generated amalgated header. +// #define JSON_IS_AMALGAMATION + +#ifdef JSON_IN_CPPTL +#include +#ifndef JSON_USE_CPPTL +#define JSON_USE_CPPTL 1 +#endif +#endif + +#ifdef JSON_IN_CPPTL +#define JSON_API CPPTL_API +#elif defined(JSON_DLL_BUILD) +#if defined(_MSC_VER) +#define JSON_API __declspec(dllexport) +#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING +#endif // if defined(_MSC_VER) +#elif defined(JSON_DLL) +#if defined(_MSC_VER) +#define JSON_API __declspec(dllimport) +#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING +#endif // if defined(_MSC_VER) +#endif // ifdef JSON_IN_CPPTL +#if !defined(JSON_API) +#define JSON_API +#endif + +// If JSON_NO_INT64 is defined, then Json only support C++ "int" type for +// integer +// Storages, and 64 bits integer support is disabled. +// #define JSON_NO_INT64 1 + +#if defined(_MSC_VER) // MSVC +# if _MSC_VER <= 1200 // MSVC 6 + // Microsoft Visual Studio 6 only support conversion from __int64 to double + // (no conversion from unsigned __int64). +# define JSON_USE_INT64_DOUBLE_CONVERSION 1 + // Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255' + // characters in the debug information) + // All projects I've ever seen with VS6 were using this globally (not bothering + // with pragma push/pop). +# pragma warning(disable : 4786) +# endif // MSVC 6 + +# if _MSC_VER >= 1500 // MSVC 2008 + /// Indicates that the following function is deprecated. +# define JSONCPP_DEPRECATED(message) __declspec(deprecated(message)) +# endif + +#endif // defined(_MSC_VER) + + +#ifndef JSON_HAS_RVALUE_REFERENCES + +#if defined(_MSC_VER) && _MSC_VER >= 1600 // MSVC >= 2010 +#define JSON_HAS_RVALUE_REFERENCES 1 +#endif // MSVC >= 2010 + +#ifdef __clang__ +#if __has_feature(cxx_rvalue_references) +#define JSON_HAS_RVALUE_REFERENCES 1 +#endif // has_feature + +#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc) +#if defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103L) +#define JSON_HAS_RVALUE_REFERENCES 1 +#endif // GXX_EXPERIMENTAL + +#endif // __clang__ || __GNUC__ + +#endif // not defined JSON_HAS_RVALUE_REFERENCES + +#ifndef JSON_HAS_RVALUE_REFERENCES +#define JSON_HAS_RVALUE_REFERENCES 0 +#endif + +#ifdef __clang__ +#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc) +# if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)) +# define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message))) +# elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) +# define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__)) +# endif // GNUC version +#endif // __clang__ || __GNUC__ + +#if !defined(JSONCPP_DEPRECATED) +#define JSONCPP_DEPRECATED(message) +#endif // if !defined(JSONCPP_DEPRECATED) + +namespace Json { +typedef int Int; +typedef unsigned int UInt; +#if defined(JSON_NO_INT64) +typedef int LargestInt; +typedef unsigned int LargestUInt; +#undef JSON_HAS_INT64 +#else // if defined(JSON_NO_INT64) +// For Microsoft Visual use specific types as long long is not supported +#if defined(_MSC_VER) // Microsoft Visual Studio +typedef __int64 Int64; +typedef unsigned __int64 UInt64; +#else // if defined(_MSC_VER) // Other platforms, use long long +typedef long long int Int64; +typedef unsigned long long int UInt64; +#endif // if defined(_MSC_VER) +typedef Int64 LargestInt; +typedef UInt64 LargestUInt; +#define JSON_HAS_INT64 +#endif // if defined(JSON_NO_INT64) +} // end namespace Json + +#endif // JSON_CONFIG_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/config.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/forwards.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef JSON_FORWARDS_H_INCLUDED +#define JSON_FORWARDS_H_INCLUDED + +#if !defined(JSON_IS_AMALGAMATION) +#include "config.h" +#endif // if !defined(JSON_IS_AMALGAMATION) + +namespace Json { + +// writer.h +class FastWriter; +class StyledWriter; + +// reader.h +class Reader; + +// features.h +class Features; + +// value.h +typedef unsigned int ArrayIndex; +class StaticString; +class Path; +class PathArgument; +class Value; +class ValueIteratorBase; +class ValueIterator; +class ValueConstIterator; + +} // namespace Json + +#endif // JSON_FORWARDS_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/forwards.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/features.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef CPPTL_JSON_FEATURES_H_INCLUDED +#define CPPTL_JSON_FEATURES_H_INCLUDED + +#if !defined(JSON_IS_AMALGAMATION) +#include "forwards.h" +#endif // if !defined(JSON_IS_AMALGAMATION) + +namespace Json { + +/** \brief Configuration passed to reader and writer. + * This configuration object can be used to force the Reader or Writer + * to behave in a standard conforming way. + */ +class JSON_API Features { +public: + /** \brief A configuration that allows all features and assumes all strings + * are UTF-8. + * - C & C++ comments are allowed + * - Root object can be any JSON value + * - Assumes Value strings are encoded in UTF-8 + */ + static Features all(); + + /** \brief A configuration that is strictly compatible with the JSON + * specification. + * - Comments are forbidden. + * - Root object must be either an array or an object value. + * - Assumes Value strings are encoded in UTF-8 + */ + static Features strictMode(); + + /** \brief Initialize the configuration like JsonConfig::allFeatures; + */ + Features(); + + /// \c true if comments are allowed. Default: \c true. + bool allowComments_; + + /// \c true if root must be either an array or an object value. Default: \c + /// false. + bool strictRoot_; + + /// \c true if dropped null placeholders are allowed. Default: \c false. + bool allowDroppedNullPlaceholders_; + + /// \c true if numeric object key are allowed. Default: \c false. + bool allowNumericKeys_; +}; + +} // namespace Json + +#endif // CPPTL_JSON_FEATURES_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/features.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/value.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef CPPTL_JSON_H_INCLUDED +#define CPPTL_JSON_H_INCLUDED + +#if !defined(JSON_IS_AMALGAMATION) +#include "forwards.h" +#endif // if !defined(JSON_IS_AMALGAMATION) +#include +#include +#include + +#ifndef JSON_USE_CPPTL_SMALLMAP +#include +#else +#include +#endif +#ifdef JSON_USE_CPPTL +#include +#endif + +// Disable warning C4251: : needs to have dll-interface to +// be used by... +#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) +#pragma warning(push) +#pragma warning(disable : 4251) +#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) + +/** \brief JSON (JavaScript Object Notation). + */ +namespace Json { + +/** Base class for all exceptions we throw. + * + * We use nothing but these internally. Of course, STL can throw others. + */ +class JSON_API Exception : public std::exception { +public: + Exception(std::string const& msg); + ~Exception() throw() override; + char const* what() const throw() override; +protected: + std::string msg_; +}; + +/** Exceptions which the user cannot easily avoid. + * + * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input + * + * \remark derived from Json::Exception + */ +class JSON_API RuntimeError : public Exception { +public: + RuntimeError(std::string const& msg); +}; + +/** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros. + * + * These are precondition-violations (user bugs) and internal errors (our bugs). + * + * \remark derived from Json::Exception + */ +class JSON_API LogicError : public Exception { +public: + LogicError(std::string const& msg); +}; + +/// used internally +void throwRuntimeError(std::string const& msg); +/// used internally +void throwLogicError(std::string const& msg); + +/** \brief Type of the value held by a Value object. + */ +enum ValueType { + nullValue = 0, ///< 'null' value + intValue, ///< signed integer value + uintValue, ///< unsigned integer value + realValue, ///< double value + stringValue, ///< UTF-8 string value + booleanValue, ///< bool value + arrayValue, ///< array value (ordered list) + objectValue ///< object value (collection of name/value pairs). +}; + +enum CommentPlacement { + commentBefore = 0, ///< a comment placed on the line before a value + commentAfterOnSameLine, ///< a comment just after a value on the same line + commentAfter, ///< a comment on the line after a value (only make sense for + /// root value) + numberOfCommentPlacement +}; + +//# ifdef JSON_USE_CPPTL +// typedef CppTL::AnyEnumerator EnumMemberNames; +// typedef CppTL::AnyEnumerator EnumValues; +//# endif + +/** \brief Lightweight wrapper to tag static string. + * + * Value constructor and objectValue member assignement takes advantage of the + * StaticString and avoid the cost of string duplication when storing the + * string or the member name. + * + * Example of usage: + * \code + * Json::Value aValue( StaticString("some text") ); + * Json::Value object; + * static const StaticString code("code"); + * object[code] = 1234; + * \endcode + */ +class JSON_API StaticString { +public: + explicit StaticString(const char* czstring) : c_str_(czstring) {} + + operator const char*() const { return c_str_; } + + const char* c_str() const { return c_str_; } + +private: + const char* c_str_; +}; + +/** \brief Represents a JSON value. + * + * This class is a discriminated union wrapper that can represents a: + * - signed integer [range: Value::minInt - Value::maxInt] + * - unsigned integer (range: 0 - Value::maxUInt) + * - double + * - UTF-8 string + * - boolean + * - 'null' + * - an ordered list of Value + * - collection of name/value pairs (javascript object) + * + * The type of the held value is represented by a #ValueType and + * can be obtained using type(). + * + * Values of an #objectValue or #arrayValue can be accessed using operator[]() + * methods. + * Non-const methods will automatically create the a #nullValue element + * if it does not exist. + * The sequence of an #arrayValue will be automatically resized and initialized + * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue. + * + * The get() methods can be used to obtain default value in the case the + * required element does not exist. + * + * It is possible to iterate over the list of a #objectValue values using + * the getMemberNames() method. + * + * \note #Value string-length fit in size_t, but keys must be < 2^30. + * (The reason is an implementation detail.) A #CharReader will raise an + * exception if a bound is exceeded to avoid security holes in your app, + * but the Value API does *not* check bounds. That is the responsibility + * of the caller. + */ +class JSON_API Value { + friend class ValueIteratorBase; +public: + typedef std::vector Members; + typedef ValueIterator iterator; + typedef ValueConstIterator const_iterator; + typedef Json::UInt UInt; + typedef Json::Int Int; +#if defined(JSON_HAS_INT64) + typedef Json::UInt64 UInt64; + typedef Json::Int64 Int64; +#endif // defined(JSON_HAS_INT64) + typedef Json::LargestInt LargestInt; + typedef Json::LargestUInt LargestUInt; + typedef Json::ArrayIndex ArrayIndex; + + static const Value& null; ///< We regret this reference to a global instance; prefer the simpler Value(). + static const Value& nullRef; ///< just a kludge for binary-compatibility; same as null + /// Minimum signed integer value that can be stored in a Json::Value. + static const LargestInt minLargestInt; + /// Maximum signed integer value that can be stored in a Json::Value. + static const LargestInt maxLargestInt; + /// Maximum unsigned integer value that can be stored in a Json::Value. + static const LargestUInt maxLargestUInt; + + /// Minimum signed int value that can be stored in a Json::Value. + static const Int minInt; + /// Maximum signed int value that can be stored in a Json::Value. + static const Int maxInt; + /// Maximum unsigned int value that can be stored in a Json::Value. + static const UInt maxUInt; + +#if defined(JSON_HAS_INT64) + /// Minimum signed 64 bits int value that can be stored in a Json::Value. + static const Int64 minInt64; + /// Maximum signed 64 bits int value that can be stored in a Json::Value. + static const Int64 maxInt64; + /// Maximum unsigned 64 bits int value that can be stored in a Json::Value. + static const UInt64 maxUInt64; +#endif // defined(JSON_HAS_INT64) + +private: +#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + class CZString { + public: + enum DuplicationPolicy { + noDuplication = 0, + duplicate, + duplicateOnCopy + }; + CZString(ArrayIndex index); + CZString(char const* str, unsigned length, DuplicationPolicy allocate); + CZString(CZString const& other); +#if JSON_HAS_RVALUE_REFERENCES + CZString(CZString&& other); +#endif + ~CZString(); + CZString& operator=(CZString other); + bool operator<(CZString const& other) const; + bool operator==(CZString const& other) const; + ArrayIndex index() const; + //const char* c_str() const; ///< \deprecated + char const* data() const; + unsigned length() const; + bool isStaticString() const; + + private: + void swap(CZString& other); + + struct StringStorage { + unsigned policy_: 2; + unsigned length_: 30; // 1GB max + }; + + char const* cstr_; // actually, a prefixed string, unless policy is noDup + union { + ArrayIndex index_; + StringStorage storage_; + }; + }; + +public: +#ifndef JSON_USE_CPPTL_SMALLMAP + typedef std::map ObjectValues; +#else + typedef CppTL::SmallMap ObjectValues; +#endif // ifndef JSON_USE_CPPTL_SMALLMAP +#endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION + +public: + /** \brief Create a default Value of the given type. + + This is a very useful constructor. + To create an empty array, pass arrayValue. + To create an empty object, pass objectValue. + Another Value can then be set to this one by assignment. +This is useful since clear() and resize() will not alter types. + + Examples: +\code +Json::Value null_value; // null +Json::Value arr_value(Json::arrayValue); // [] +Json::Value obj_value(Json::objectValue); // {} +\endcode + */ + Value(ValueType type = nullValue); + Value(Int value); + Value(UInt value); +#if defined(JSON_HAS_INT64) + Value(Int64 value); + Value(UInt64 value); +#endif // if defined(JSON_HAS_INT64) + Value(double value); + Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.) + Value(const char* begin, const char* end); ///< Copy all, incl zeroes. + /** \brief Constructs a value from a static string. + + * Like other value string constructor but do not duplicate the string for + * internal storage. The given string must remain alive after the call to this + * constructor. + * \note This works only for null-terminated strings. (We cannot change the + * size of this class, so we have nowhere to store the length, + * which might be computed later for various operations.) + * + * Example of usage: + * \code + * static StaticString foo("some text"); + * Json::Value aValue(foo); + * \endcode + */ + Value(const StaticString& value); + Value(const std::string& value); ///< Copy data() til size(). Embedded zeroes too. +#ifdef JSON_USE_CPPTL + Value(const CppTL::ConstString& value); +#endif + Value(bool value); + /// Deep copy. + Value(const Value& other); +#if JSON_HAS_RVALUE_REFERENCES + /// Move constructor + Value(Value&& other); +#endif + ~Value(); + + /// Deep copy, then swap(other). + /// \note Over-write existing comments. To preserve comments, use #swapPayload(). + Value& operator=(Value other); + /// Swap everything. + void swap(Value& other); + /// Swap values but leave comments and source offsets in place. + void swapPayload(Value& other); + + ValueType type() const; + + /// Compare payload only, not comments etc. + bool operator<(const Value& other) const; + bool operator<=(const Value& other) const; + bool operator>=(const Value& other) const; + bool operator>(const Value& other) const; + bool operator==(const Value& other) const; + bool operator!=(const Value& other) const; + int compare(const Value& other) const; + + const char* asCString() const; ///< Embedded zeroes could cause you trouble! + std::string asString() const; ///< Embedded zeroes are possible. + /** Get raw char* of string-value. + * \return false if !string. (Seg-fault if str or end are NULL.) + */ + bool getString( + char const** begin, char const** end) const; +#ifdef JSON_USE_CPPTL + CppTL::ConstString asConstString() const; +#endif + Int asInt() const; + UInt asUInt() const; +#if defined(JSON_HAS_INT64) + Int64 asInt64() const; + UInt64 asUInt64() const; +#endif // if defined(JSON_HAS_INT64) + LargestInt asLargestInt() const; + LargestUInt asLargestUInt() const; + float asFloat() const; + double asDouble() const; + bool asBool() const; + + bool isNull() const; + bool isBool() const; + bool isInt() const; + bool isInt64() const; + bool isUInt() const; + bool isUInt64() const; + bool isIntegral() const; + bool isDouble() const; + bool isNumeric() const; + bool isString() const; + bool isArray() const; + bool isObject() const; + + bool isConvertibleTo(ValueType other) const; + + /// Number of values in array or object + ArrayIndex size() const; + + /// \brief Return true if empty array, empty object, or null; + /// otherwise, false. + bool empty() const; + + /// Return isNull() + bool operator!() const; + + /// Remove all object members and array elements. + /// \pre type() is arrayValue, objectValue, or nullValue + /// \post type() is unchanged + void clear(); + + /// Resize the array to size elements. + /// New elements are initialized to null. + /// May only be called on nullValue or arrayValue. + /// \pre type() is arrayValue or nullValue + /// \post type() is arrayValue + void resize(ArrayIndex size); + + /// Access an array element (zero based index ). + /// If the array contains less than index element, then null value are + /// inserted + /// in the array so that its size is index+1. + /// (You may need to say 'value[0u]' to get your compiler to distinguish + /// this from the operator[] which takes a string.) + Value& operator[](ArrayIndex index); + + /// Access an array element (zero based index ). + /// If the array contains less than index element, then null value are + /// inserted + /// in the array so that its size is index+1. + /// (You may need to say 'value[0u]' to get your compiler to distinguish + /// this from the operator[] which takes a string.) + Value& operator[](int index); + + /// Access an array element (zero based index ) + /// (You may need to say 'value[0u]' to get your compiler to distinguish + /// this from the operator[] which takes a string.) + const Value& operator[](ArrayIndex index) const; + + /// Access an array element (zero based index ) + /// (You may need to say 'value[0u]' to get your compiler to distinguish + /// this from the operator[] which takes a string.) + const Value& operator[](int index) const; + + /// If the array contains at least index+1 elements, returns the element + /// value, + /// otherwise returns defaultValue. + Value get(ArrayIndex index, const Value& defaultValue) const; + /// Return true if index < size(). + bool isValidIndex(ArrayIndex index) const; + /// \brief Append value to array at the end. + /// + /// Equivalent to jsonvalue[jsonvalue.size()] = value; + Value& append(const Value& value); + + /// Access an object value by name, create a null member if it does not exist. + /// \note Because of our implementation, keys are limited to 2^30 -1 chars. + /// Exceeding that will cause an exception. + Value& operator[](const char* key); + /// Access an object value by name, returns null if there is no member with + /// that name. + const Value& operator[](const char* key) const; + /// Access an object value by name, create a null member if it does not exist. + /// \param key may contain embedded nulls. + Value& operator[](const std::string& key); + /// Access an object value by name, returns null if there is no member with + /// that name. + /// \param key may contain embedded nulls. + const Value& operator[](const std::string& key) const; + /** \brief Access an object value by name, create a null member if it does not + exist. + + * If the object has no entry for that name, then the member name used to store + * the new entry is not duplicated. + * Example of use: + * \code + * Json::Value object; + * static const StaticString code("code"); + * object[code] = 1234; + * \endcode + */ + Value& operator[](const StaticString& key); +#ifdef JSON_USE_CPPTL + /// Access an object value by name, create a null member if it does not exist. + Value& operator[](const CppTL::ConstString& key); + /// Access an object value by name, returns null if there is no member with + /// that name. + const Value& operator[](const CppTL::ConstString& key) const; +#endif + /// Return the member named key if it exist, defaultValue otherwise. + /// \note deep copy + Value get(const char* key, const Value& defaultValue) const; + /// Return the member named key if it exist, defaultValue otherwise. + /// \note deep copy + /// \note key may contain embedded nulls. + Value get(const char* begin, const char* end, const Value& defaultValue) const; + /// Return the member named key if it exist, defaultValue otherwise. + /// \note deep copy + /// \param key may contain embedded nulls. + Value get(const std::string& key, const Value& defaultValue) const; +#ifdef JSON_USE_CPPTL + /// Return the member named key if it exist, defaultValue otherwise. + /// \note deep copy + Value get(const CppTL::ConstString& key, const Value& defaultValue) const; +#endif + /// Most general and efficient version of isMember()const, get()const, + /// and operator[]const + /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30 + Value const* find(char const* begin, char const* end) const; + /// Most general and efficient version of object-mutators. + /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30 + /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue. + Value const* demand(char const* begin, char const* end); + /// \brief Remove and return the named member. + /// + /// Do nothing if it did not exist. + /// \return the removed Value, or null. + /// \pre type() is objectValue or nullValue + /// \post type() is unchanged + /// \deprecated + Value removeMember(const char* key); + /// Same as removeMember(const char*) + /// \param key may contain embedded nulls. + /// \deprecated + Value removeMember(const std::string& key); + /// Same as removeMember(const char* begin, const char* end, Value* removed), + /// but 'key' is null-terminated. + bool removeMember(const char* key, Value* removed); + /** \brief Remove the named map member. + + Update 'removed' iff removed. + \param key may contain embedded nulls. + \return true iff removed (no exceptions) + */ + bool removeMember(std::string const& key, Value* removed); + /// Same as removeMember(std::string const& key, Value* removed) + bool removeMember(const char* begin, const char* end, Value* removed); + /** \brief Remove the indexed array element. + + O(n) expensive operations. + Update 'removed' iff removed. + \return true iff removed (no exceptions) + */ + bool removeIndex(ArrayIndex i, Value* removed); + + /// Return true if the object has a member named key. + /// \note 'key' must be null-terminated. + bool isMember(const char* key) const; + /// Return true if the object has a member named key. + /// \param key may contain embedded nulls. + bool isMember(const std::string& key) const; + /// Same as isMember(std::string const& key)const + bool isMember(const char* begin, const char* end) const; +#ifdef JSON_USE_CPPTL + /// Return true if the object has a member named key. + bool isMember(const CppTL::ConstString& key) const; +#endif + + /// \brief Return a list of the member names. + /// + /// If null, return an empty list. + /// \pre type() is objectValue or nullValue + /// \post if type() was nullValue, it remains nullValue + Members getMemberNames() const; + + //# ifdef JSON_USE_CPPTL + // EnumMemberNames enumMemberNames() const; + // EnumValues enumValues() const; + //# endif + + /// \deprecated Always pass len. + JSONCPP_DEPRECATED("Use setComment(std::string const&) instead.") + void setComment(const char* comment, CommentPlacement placement); + /// Comments must be //... or /* ... */ + void setComment(const char* comment, size_t len, CommentPlacement placement); + /// Comments must be //... or /* ... */ + void setComment(const std::string& comment, CommentPlacement placement); + bool hasComment(CommentPlacement placement) const; + /// Include delimiters and embedded newlines. + std::string getComment(CommentPlacement placement) const; + + std::string toStyledString() const; + + const_iterator begin() const; + const_iterator end() const; + + iterator begin(); + iterator end(); + + // Accessors for the [start, limit) range of bytes within the JSON text from + // which this value was parsed, if any. + void setOffsetStart(size_t start); + void setOffsetLimit(size_t limit); + size_t getOffsetStart() const; + size_t getOffsetLimit() const; + +private: + void initBasic(ValueType type, bool allocated = false); + + Value& resolveReference(const char* key); + Value& resolveReference(const char* key, const char* end); + + struct CommentInfo { + CommentInfo(); + ~CommentInfo(); + + void setComment(const char* text, size_t len); + + char* comment_; + }; + + // struct MemberNamesTransform + //{ + // typedef const char *result_type; + // const char *operator()( const CZString &name ) const + // { + // return name.c_str(); + // } + //}; + + union ValueHolder { + LargestInt int_; + LargestUInt uint_; + double real_; + bool bool_; + char* string_; // actually ptr to unsigned, followed by str, unless !allocated_ + ObjectValues* map_; + } value_; + ValueType type_ : 8; + unsigned int allocated_ : 1; // Notes: if declared as bool, bitfield is useless. + // If not allocated_, string_ must be null-terminated. + CommentInfo* comments_; + + // [start, limit) byte offsets in the source JSON text from which this Value + // was extracted. + size_t start_; + size_t limit_; +}; + +/** \brief Experimental and untested: represents an element of the "path" to + * access a node. + */ +class JSON_API PathArgument { +public: + friend class Path; + + PathArgument(); + PathArgument(ArrayIndex index); + PathArgument(const char* key); + PathArgument(const std::string& key); + +private: + enum Kind { + kindNone = 0, + kindIndex, + kindKey + }; + std::string key_; + ArrayIndex index_; + Kind kind_; +}; + +/** \brief Experimental and untested: represents a "path" to access a node. + * + * Syntax: + * - "." => root node + * - ".[n]" => elements at index 'n' of root node (an array value) + * - ".name" => member named 'name' of root node (an object value) + * - ".name1.name2.name3" + * - ".[0][1][2].name1[3]" + * - ".%" => member name is provided as parameter + * - ".[%]" => index is provided as parameter + */ +class JSON_API Path { +public: + Path(const std::string& path, + const PathArgument& a1 = PathArgument(), + const PathArgument& a2 = PathArgument(), + const PathArgument& a3 = PathArgument(), + const PathArgument& a4 = PathArgument(), + const PathArgument& a5 = PathArgument()); + + const Value& resolve(const Value& root) const; + Value resolve(const Value& root, const Value& defaultValue) const; + /// Creates the "path" to access the specified node and returns a reference on + /// the node. + Value& make(Value& root) const; + +private: + typedef std::vector InArgs; + typedef std::vector Args; + + void makePath(const std::string& path, const InArgs& in); + void addPathInArg(const std::string& path, + const InArgs& in, + InArgs::const_iterator& itInArg, + PathArgument::Kind kind); + void invalidPath(const std::string& path, int location); + + Args args_; +}; + +/** \brief base class for Value iterators. + * + */ +class JSON_API ValueIteratorBase { +public: + typedef std::bidirectional_iterator_tag iterator_category; + typedef unsigned int size_t; + typedef int difference_type; + typedef ValueIteratorBase SelfType; + + bool operator==(const SelfType& other) const { return isEqual(other); } + + bool operator!=(const SelfType& other) const { return !isEqual(other); } + + difference_type operator-(const SelfType& other) const { + return other.computeDistance(*this); + } + + /// Return either the index or the member name of the referenced value as a + /// Value. + Value key() const; + + /// Return the index of the referenced Value, or -1 if it is not an arrayValue. + UInt index() const; + + /// Return the member name of the referenced Value, or "" if it is not an + /// objectValue. + /// \note Avoid `c_str()` on result, as embedded zeroes are possible. + std::string name() const; + + /// Return the member name of the referenced Value. "" if it is not an + /// objectValue. + /// \deprecated This cannot be used for UTF-8 strings, since there can be embedded nulls. + JSONCPP_DEPRECATED("Use `key = name();` instead.") + char const* memberName() const; + /// Return the member name of the referenced Value, or NULL if it is not an + /// objectValue. + /// \note Better version than memberName(). Allows embedded nulls. + char const* memberName(char const** end) const; + +protected: + Value& deref() const; + + void increment(); + + void decrement(); + + difference_type computeDistance(const SelfType& other) const; + + bool isEqual(const SelfType& other) const; + + void copy(const SelfType& other); + +private: + Value::ObjectValues::iterator current_; + // Indicates that iterator is for a null value. + bool isNull_; + +public: + // For some reason, BORLAND needs these at the end, rather + // than earlier. No idea why. + ValueIteratorBase(); + explicit ValueIteratorBase(const Value::ObjectValues::iterator& current); +}; + +/** \brief const iterator for object and array value. + * + */ +class JSON_API ValueConstIterator : public ValueIteratorBase { + friend class Value; + +public: + typedef const Value value_type; + //typedef unsigned int size_t; + //typedef int difference_type; + typedef const Value& reference; + typedef const Value* pointer; + typedef ValueConstIterator SelfType; + + ValueConstIterator(); + ValueConstIterator(ValueIterator const& other); + +private: +/*! \internal Use by Value to create an iterator. + */ + explicit ValueConstIterator(const Value::ObjectValues::iterator& current); +public: + SelfType& operator=(const ValueIteratorBase& other); + + SelfType operator++(int) { + SelfType temp(*this); + ++*this; + return temp; + } + + SelfType operator--(int) { + SelfType temp(*this); + --*this; + return temp; + } + + SelfType& operator--() { + decrement(); + return *this; + } + + SelfType& operator++() { + increment(); + return *this; + } + + reference operator*() const { return deref(); } + + pointer operator->() const { return &deref(); } +}; + +/** \brief Iterator for object and array value. + */ +class JSON_API ValueIterator : public ValueIteratorBase { + friend class Value; + +public: + typedef Value value_type; + typedef unsigned int size_t; + typedef int difference_type; + typedef Value& reference; + typedef Value* pointer; + typedef ValueIterator SelfType; + + ValueIterator(); + explicit ValueIterator(const ValueConstIterator& other); + ValueIterator(const ValueIterator& other); + +private: +/*! \internal Use by Value to create an iterator. + */ + explicit ValueIterator(const Value::ObjectValues::iterator& current); +public: + SelfType& operator=(const SelfType& other); + + SelfType operator++(int) { + SelfType temp(*this); + ++*this; + return temp; + } + + SelfType operator--(int) { + SelfType temp(*this); + --*this; + return temp; + } + + SelfType& operator--() { + decrement(); + return *this; + } + + SelfType& operator++() { + increment(); + return *this; + } + + reference operator*() const { return deref(); } + + pointer operator->() const { return &deref(); } +}; + +} // namespace Json + + +namespace std { +/// Specialize std::swap() for Json::Value. +template<> +inline void swap(Json::Value& a, Json::Value& b) { a.swap(b); } +} + + +#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) +#pragma warning(pop) +#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) + +#endif // CPPTL_JSON_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/value.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/reader.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef CPPTL_JSON_READER_H_INCLUDED +#define CPPTL_JSON_READER_H_INCLUDED + +#if !defined(JSON_IS_AMALGAMATION) +#include "features.h" +#include "value.h" +#endif // if !defined(JSON_IS_AMALGAMATION) +#include +#include +#include +#include +#include + +// Disable warning C4251: : needs to have dll-interface to +// be used by... +#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) +#pragma warning(push) +#pragma warning(disable : 4251) +#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) + +namespace Json { + +/** \brief Unserialize a JSON document into a + *Value. + * + * \deprecated Use CharReader and CharReaderBuilder. + */ +class JSON_API Reader { +public: + typedef char Char; + typedef const Char* Location; + + /** \brief An error tagged with where in the JSON text it was encountered. + * + * The offsets give the [start, limit) range of bytes within the text. Note + * that this is bytes, not codepoints. + * + */ + struct StructuredError { + size_t offset_start; + size_t offset_limit; + std::string message; + }; + + /** \brief Constructs a Reader allowing all features + * for parsing. + */ + Reader(); + + /** \brief Constructs a Reader allowing the specified feature set + * for parsing. + */ + Reader(const Features& features); + + /** \brief Read a Value from a JSON + * document. + * \param document UTF-8 encoded string containing the document to read. + * \param root [out] Contains the root value of the document if it was + * successfully parsed. + * \param collectComments \c true to collect comment and allow writing them + * back during + * serialization, \c false to discard comments. + * This parameter is ignored if + * Features::allowComments_ + * is \c false. + * \return \c true if the document was successfully parsed, \c false if an + * error occurred. + */ + bool + parse(const std::string& document, Value& root, bool collectComments = true); + + /** \brief Read a Value from a JSON + document. + * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the + document to read. + * \param endDoc Pointer on the end of the UTF-8 encoded string of the + document to read. + * Must be >= beginDoc. + * \param root [out] Contains the root value of the document if it was + * successfully parsed. + * \param collectComments \c true to collect comment and allow writing them + back during + * serialization, \c false to discard comments. + * This parameter is ignored if + Features::allowComments_ + * is \c false. + * \return \c true if the document was successfully parsed, \c false if an + error occurred. + */ + bool parse(const char* beginDoc, + const char* endDoc, + Value& root, + bool collectComments = true); + + /// \brief Parse from input stream. + /// \see Json::operator>>(std::istream&, Json::Value&). + bool parse(std::istream& is, Value& root, bool collectComments = true); + + /** \brief Returns a user friendly string that list errors in the parsed + * document. + * \return Formatted error message with the list of errors with their location + * in + * the parsed document. An empty string is returned if no error + * occurred + * during parsing. + * \deprecated Use getFormattedErrorMessages() instead (typo fix). + */ + JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.") + std::string getFormatedErrorMessages() const; + + /** \brief Returns a user friendly string that list errors in the parsed + * document. + * \return Formatted error message with the list of errors with their location + * in + * the parsed document. An empty string is returned if no error + * occurred + * during parsing. + */ + std::string getFormattedErrorMessages() const; + + /** \brief Returns a vector of structured errors encountered while parsing. + * \return A (possibly empty) vector of StructuredError objects. Currently + * only one error can be returned, but the caller should tolerate + * multiple + * errors. This can occur if the parser recovers from a non-fatal + * parse error and then encounters additional errors. + */ + std::vector getStructuredErrors() const; + + /** \brief Add a semantic error message. + * \param value JSON Value location associated with the error + * \param message The error message. + * \return \c true if the error was successfully added, \c false if the + * Value offset exceeds the document size. + */ + bool pushError(const Value& value, const std::string& message); + + /** \brief Add a semantic error message with extra context. + * \param value JSON Value location associated with the error + * \param message The error message. + * \param extra Additional JSON Value location to contextualize the error + * \return \c true if the error was successfully added, \c false if either + * Value offset exceeds the document size. + */ + bool pushError(const Value& value, const std::string& message, const Value& extra); + + /** \brief Return whether there are any errors. + * \return \c true if there are no errors to report \c false if + * errors have occurred. + */ + bool good() const; + +private: + enum TokenType { + tokenEndOfStream = 0, + tokenObjectBegin, + tokenObjectEnd, + tokenArrayBegin, + tokenArrayEnd, + tokenString, + tokenNumber, + tokenTrue, + tokenFalse, + tokenNull, + tokenArraySeparator, + tokenMemberSeparator, + tokenComment, + tokenError + }; + + class Token { + public: + TokenType type_; + Location start_; + Location end_; + }; + + class ErrorInfo { + public: + Token token_; + std::string message_; + Location extra_; + }; + + typedef std::deque Errors; + + bool readToken(Token& token); + void skipSpaces(); + bool match(Location pattern, int patternLength); + bool readComment(); + bool readCStyleComment(); + bool readCppStyleComment(); + bool readString(); + void readNumber(); + bool readValue(); + bool readObject(Token& token); + bool readArray(Token& token); + bool decodeNumber(Token& token); + bool decodeNumber(Token& token, Value& decoded); + bool decodeString(Token& token); + bool decodeString(Token& token, std::string& decoded); + bool decodeDouble(Token& token); + bool decodeDouble(Token& token, Value& decoded); + bool decodeUnicodeCodePoint(Token& token, + Location& current, + Location end, + unsigned int& unicode); + bool decodeUnicodeEscapeSequence(Token& token, + Location& current, + Location end, + unsigned int& unicode); + bool addError(const std::string& message, Token& token, Location extra = 0); + bool recoverFromError(TokenType skipUntilToken); + bool addErrorAndRecover(const std::string& message, + Token& token, + TokenType skipUntilToken); + void skipUntilSpace(); + Value& currentValue(); + Char getNextChar(); + void + getLocationLineAndColumn(Location location, int& line, int& column) const; + std::string getLocationLineAndColumn(Location location) const; + void addComment(Location begin, Location end, CommentPlacement placement); + void skipCommentTokens(Token& token); + + typedef std::stack Nodes; + Nodes nodes_; + Errors errors_; + std::string document_; + Location begin_; + Location end_; + Location current_; + Location lastValueEnd_; + Value* lastValue_; + std::string commentsBefore_; + Features features_; + bool collectComments_; +}; // Reader + +/** Interface for reading JSON from a char array. + */ +class JSON_API CharReader { +public: + virtual ~CharReader() {} + /** \brief Read a Value from a JSON + document. + * The document must be a UTF-8 encoded string containing the document to read. + * + * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the + document to read. + * \param endDoc Pointer on the end of the UTF-8 encoded string of the + document to read. + * Must be >= beginDoc. + * \param root [out] Contains the root value of the document if it was + * successfully parsed. + * \param errs [out] Formatted error messages (if not NULL) + * a user friendly string that lists errors in the parsed + * document. + * \return \c true if the document was successfully parsed, \c false if an + error occurred. + */ + virtual bool parse( + char const* beginDoc, char const* endDoc, + Value* root, std::string* errs) = 0; + + class JSON_API Factory { + public: + virtual ~Factory() {} + /** \brief Allocate a CharReader via operator new(). + * \throw std::exception if something goes wrong (e.g. invalid settings) + */ + virtual CharReader* newCharReader() const = 0; + }; // Factory +}; // CharReader + +/** \brief Build a CharReader implementation. + +Usage: +\code + using namespace Json; + CharReaderBuilder builder; + builder["collectComments"] = false; + Value value; + std::string errs; + bool ok = parseFromStream(builder, std::cin, &value, &errs); +\endcode +*/ +class JSON_API CharReaderBuilder : public CharReader::Factory { +public: + // Note: We use a Json::Value so that we can add data-members to this class + // without a major version bump. + /** Configuration of this builder. + These are case-sensitive. + Available settings (case-sensitive): + - `"collectComments": false or true` + - true to collect comment and allow writing them + back during serialization, false to discard comments. + This parameter is ignored if allowComments is false. + - `"allowComments": false or true` + - true if comments are allowed. + - `"strictRoot": false or true` + - true if root must be either an array or an object value + - `"allowDroppedNullPlaceholders": false or true` + - true if dropped null placeholders are allowed. (See StreamWriterBuilder.) + - `"allowNumericKeys": false or true` + - true if numeric object keys are allowed. + - `"allowSingleQuotes": false or true` + - true if '' are allowed for strings (both keys and values) + - `"stackLimit": integer` + - Exceeding stackLimit (recursive depth of `readValue()`) will + cause an exception. + - This is a security issue (seg-faults caused by deeply nested JSON), + so the default is low. + - `"failIfExtra": false or true` + - If true, `parse()` returns false when extra non-whitespace trails + the JSON value in the input string. + - `"rejectDupKeys": false or true` + - If true, `parse()` returns false when a key is duplicated within an object. + - `"allowSpecialFloats": false or true` + - If true, special float values (NaNs and infinities) are allowed + and their values are lossfree restorable. + + You can examine 'settings_` yourself + to see the defaults. You can also write and read them just like any + JSON Value. + \sa setDefaults() + */ + Json::Value settings_; + + CharReaderBuilder(); + ~CharReaderBuilder() override; + + CharReader* newCharReader() const override; + + /** \return true if 'settings' are legal and consistent; + * otherwise, indicate bad settings via 'invalid'. + */ + bool validate(Json::Value* invalid) const; + + /** A simple way to update a specific setting. + */ + Value& operator[](std::string key); + + /** Called by ctor, but you can use this to reset settings_. + * \pre 'settings' != NULL (but Json::null is fine) + * \remark Defaults: + * \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults + */ + static void setDefaults(Json::Value* settings); + /** Same as old Features::strictMode(). + * \pre 'settings' != NULL (but Json::null is fine) + * \remark Defaults: + * \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode + */ + static void strictMode(Json::Value* settings); +}; + +/** Consume entire stream and use its begin/end. + * Someday we might have a real StreamReader, but for now this + * is convenient. + */ +bool JSON_API parseFromStream( + CharReader::Factory const&, + std::istream&, + Value* root, std::string* errs); + +/** \brief Read from 'sin' into 'root'. + + Always keep comments from the input JSON. + + This can be used to read a file into a particular sub-object. + For example: + \code + Json::Value root; + cin >> root["dir"]["file"]; + cout << root; + \endcode + Result: + \verbatim + { + "dir": { + "file": { + // The input stream JSON would be nested here. + } + } + } + \endverbatim + \throw std::exception on parse error. + \see Json::operator<<() +*/ +JSON_API std::istream& operator>>(std::istream&, Value&); + +} // namespace Json + +#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) +#pragma warning(pop) +#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) + +#endif // CPPTL_JSON_READER_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/reader.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/writer.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef JSON_WRITER_H_INCLUDED +#define JSON_WRITER_H_INCLUDED + +#if !defined(JSON_IS_AMALGAMATION) +#include "value.h" +#endif // if !defined(JSON_IS_AMALGAMATION) +#include +#include +#include + +// Disable warning C4251: : needs to have dll-interface to +// be used by... +#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) +#pragma warning(push) +#pragma warning(disable : 4251) +#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) + +namespace Json { + +class Value; + +/** + +Usage: +\code + using namespace Json; + void writeToStdout(StreamWriter::Factory const& factory, Value const& value) { + std::unique_ptr const writer( + factory.newStreamWriter()); + writer->write(value, &std::cout); + std::cout << std::endl; // add lf and flush + } +\endcode +*/ +class JSON_API StreamWriter { +protected: + std::ostream* sout_; // not owned; will not delete +public: + StreamWriter(); + virtual ~StreamWriter(); + /** Write Value into document as configured in sub-class. + Do not take ownership of sout, but maintain a reference during function. + \pre sout != NULL + \return zero on success (For now, we always return zero, so check the stream instead.) + \throw std::exception possibly, depending on configuration + */ + virtual int write(Value const& root, std::ostream* sout) = 0; + + /** \brief A simple abstract factory. + */ + class JSON_API Factory { + public: + virtual ~Factory(); + /** \brief Allocate a CharReader via operator new(). + * \throw std::exception if something goes wrong (e.g. invalid settings) + */ + virtual StreamWriter* newStreamWriter() const = 0; + }; // Factory +}; // StreamWriter + +/** \brief Write into stringstream, then return string, for convenience. + * A StreamWriter will be created from the factory, used, and then deleted. + */ +std::string JSON_API writeString(StreamWriter::Factory const& factory, Value const& root); + + +/** \brief Build a StreamWriter implementation. + +Usage: +\code + using namespace Json; + Value value = ...; + StreamWriterBuilder builder; + builder["commentStyle"] = "None"; + builder["indentation"] = " "; // or whatever you like + std::unique_ptr writer( + builder.newStreamWriter()); + writer->write(value, &std::cout); + std::cout << std::endl; // add lf and flush +\endcode +*/ +class JSON_API StreamWriterBuilder : public StreamWriter::Factory { +public: + // Note: We use a Json::Value so that we can add data-members to this class + // without a major version bump. + /** Configuration of this builder. + Available settings (case-sensitive): + - "commentStyle": "None" or "All" + - "indentation": "" + - "enableYAMLCompatibility": false or true + - slightly change the whitespace around colons + - "dropNullPlaceholders": false or true + - Drop the "null" string from the writer's output for nullValues. + Strictly speaking, this is not valid JSON. But when the output is being + fed to a browser's Javascript, it makes for smaller output and the + browser can handle the output just fine. + - "useSpecialFloats": false or true + - If true, outputs non-finite floating point values in the following way: + NaN values as "NaN", positive infinity as "Infinity", and negative infinity + as "-Infinity". + + You can examine 'settings_` yourself + to see the defaults. You can also write and read them just like any + JSON Value. + \sa setDefaults() + */ + Json::Value settings_; + + StreamWriterBuilder(); + ~StreamWriterBuilder() override; + + /** + * \throw std::exception if something goes wrong (e.g. invalid settings) + */ + StreamWriter* newStreamWriter() const override; + + /** \return true if 'settings' are legal and consistent; + * otherwise, indicate bad settings via 'invalid'. + */ + bool validate(Json::Value* invalid) const; + /** A simple way to update a specific setting. + */ + Value& operator[](std::string key); + + /** Called by ctor, but you can use this to reset settings_. + * \pre 'settings' != NULL (but Json::null is fine) + * \remark Defaults: + * \snippet src/lib_json/json_writer.cpp StreamWriterBuilderDefaults + */ + static void setDefaults(Json::Value* settings); +}; + +/** \brief Abstract class for writers. + * \deprecated Use StreamWriter. (And really, this is an implementation detail.) + */ +class JSON_API Writer { +public: + virtual ~Writer(); + + virtual std::string write(const Value& root) = 0; +}; + +/** \brief Outputs a Value in JSON format + *without formatting (not human friendly). + * + * The JSON document is written in a single line. It is not intended for 'human' + *consumption, + * but may be useful to support feature such as RPC where bandwidth is limited. + * \sa Reader, Value + * \deprecated Use StreamWriterBuilder. + */ +class JSON_API FastWriter : public Writer { + +public: + FastWriter(); + ~FastWriter() override {} + + void enableYAMLCompatibility(); + + /** \brief Drop the "null" string from the writer's output for nullValues. + * Strictly speaking, this is not valid JSON. But when the output is being + * fed to a browser's Javascript, it makes for smaller output and the + * browser can handle the output just fine. + */ + void dropNullPlaceholders(); + + void omitEndingLineFeed(); + +public: // overridden from Writer + std::string write(const Value& root) override; + +private: + void writeValue(const Value& value); + + std::string document_; + bool yamlCompatiblityEnabled_; + bool dropNullPlaceholders_; + bool omitEndingLineFeed_; +}; + +/** \brief Writes a Value in JSON format in a + *human friendly way. + * + * The rules for line break and indent are as follow: + * - Object value: + * - if empty then print {} without indent and line break + * - if not empty the print '{', line break & indent, print one value per + *line + * and then unindent and line break and print '}'. + * - Array value: + * - if empty then print [] without indent and line break + * - if the array contains no object value, empty array or some other value + *types, + * and all the values fit on one lines, then print the array on a single + *line. + * - otherwise, it the values do not fit on one line, or the array contains + * object or non empty array, then print one value per line. + * + * If the Value have comments then they are outputted according to their + *#CommentPlacement. + * + * \sa Reader, Value, Value::setComment() + * \deprecated Use StreamWriterBuilder. + */ +class JSON_API StyledWriter : public Writer { +public: + StyledWriter(); + ~StyledWriter() override {} + +public: // overridden from Writer + /** \brief Serialize a Value in JSON format. + * \param root Value to serialize. + * \return String containing the JSON document that represents the root value. + */ + std::string write(const Value& root) override; + +private: + void writeValue(const Value& value); + void writeArrayValue(const Value& value); + bool isMultineArray(const Value& value); + void pushValue(const std::string& value); + void writeIndent(); + void writeWithIndent(const std::string& value); + void indent(); + void unindent(); + void writeCommentBeforeValue(const Value& root); + void writeCommentAfterValueOnSameLine(const Value& root); + bool hasCommentForValue(const Value& value); + static std::string normalizeEOL(const std::string& text); + + typedef std::vector ChildValues; + + ChildValues childValues_; + std::string document_; + std::string indentString_; + int rightMargin_; + int indentSize_; + bool addChildValues_; +}; + +/** \brief Writes a Value in JSON format in a + human friendly way, + to a stream rather than to a string. + * + * The rules for line break and indent are as follow: + * - Object value: + * - if empty then print {} without indent and line break + * - if not empty the print '{', line break & indent, print one value per + line + * and then unindent and line break and print '}'. + * - Array value: + * - if empty then print [] without indent and line break + * - if the array contains no object value, empty array or some other value + types, + * and all the values fit on one lines, then print the array on a single + line. + * - otherwise, it the values do not fit on one line, or the array contains + * object or non empty array, then print one value per line. + * + * If the Value have comments then they are outputted according to their + #CommentPlacement. + * + * \param indentation Each level will be indented by this amount extra. + * \sa Reader, Value, Value::setComment() + * \deprecated Use StreamWriterBuilder. + */ +class JSON_API StyledStreamWriter { +public: + StyledStreamWriter(std::string indentation = "\t"); + ~StyledStreamWriter() {} + +public: + /** \brief Serialize a Value in JSON format. + * \param out Stream to write to. (Can be ostringstream, e.g.) + * \param root Value to serialize. + * \note There is no point in deriving from Writer, since write() should not + * return a value. + */ + void write(std::ostream& out, const Value& root); + +private: + void writeValue(const Value& value); + void writeArrayValue(const Value& value); + bool isMultineArray(const Value& value); + void pushValue(const std::string& value); + void writeIndent(); + void writeWithIndent(const std::string& value); + void indent(); + void unindent(); + void writeCommentBeforeValue(const Value& root); + void writeCommentAfterValueOnSameLine(const Value& root); + bool hasCommentForValue(const Value& value); + static std::string normalizeEOL(const std::string& text); + + typedef std::vector ChildValues; + + ChildValues childValues_; + std::ostream* document_; + std::string indentString_; + int rightMargin_; + std::string indentation_; + bool addChildValues_ : 1; + bool indented_ : 1; +}; + +#if defined(JSON_HAS_INT64) +std::string JSON_API valueToString(Int value); +std::string JSON_API valueToString(UInt value); +#endif // if defined(JSON_HAS_INT64) +std::string JSON_API valueToString(LargestInt value); +std::string JSON_API valueToString(LargestUInt value); +std::string JSON_API valueToString(double value); +std::string JSON_API valueToString(bool value); +std::string JSON_API valueToQuotedString(const char* value); + +/// \brief Output using the StyledStreamWriter. +/// \see Json::operator>>() +JSON_API std::ostream& operator<<(std::ostream&, const Value& root); + +} // namespace Json + +#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) +#pragma warning(pop) +#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) + +#endif // JSON_WRITER_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/writer.h +// ////////////////////////////////////////////////////////////////////// + + + + + + +// ////////////////////////////////////////////////////////////////////// +// Beginning of content of file: include/json/assertions.h +// ////////////////////////////////////////////////////////////////////// + +// Copyright 2007-2010 Baptiste Lepilleur +// Distributed under MIT license, or public domain if desired and +// recognized in your jurisdiction. +// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE + +#ifndef CPPTL_JSON_ASSERTIONS_H_INCLUDED +#define CPPTL_JSON_ASSERTIONS_H_INCLUDED + +#include +#include + +#if !defined(JSON_IS_AMALGAMATION) +#include "config.h" +#endif // if !defined(JSON_IS_AMALGAMATION) + +/** It should not be possible for a maliciously designed file to + * cause an abort() or seg-fault, so these macros are used only + * for pre-condition violations and internal logic errors. + */ +#if JSON_USE_EXCEPTION + +// @todo <= add detail about condition in exception +# define JSON_ASSERT(condition) \ + {if (!(condition)) {Json::throwLogicError( "assert json failed" );}} + +# define JSON_FAIL_MESSAGE(message) \ + { \ + std::ostringstream oss; oss << message; \ + Json::throwLogicError(oss.str()); \ + abort(); \ + } + +#else // JSON_USE_EXCEPTION + +# define JSON_ASSERT(condition) assert(condition) + +// The call to assert() will show the failure message in debug builds. In +// release builds we abort, for a core-dump or debugger. +# define JSON_FAIL_MESSAGE(message) \ + { \ + std::ostringstream oss; oss << message; \ + assert(false && oss.str().c_str()); \ + abort(); \ + } + + +#endif + +#define JSON_ASSERT_MESSAGE(condition, message) \ + if (!(condition)) { \ + JSON_FAIL_MESSAGE(message); \ + } + +#endif // CPPTL_JSON_ASSERTIONS_H_INCLUDED + +// ////////////////////////////////////////////////////////////////////// +// End of content of file: include/json/assertions.h +// ////////////////////////////////////////////////////////////////////// + + + + + +#endif //ifndef JSON_AMALGATED_H_INCLUDED diff --git a/tools/env-vars-generator/protobuf/csharp/Google.Protobuf.Tools.nuspec b/tools/env-vars-generator/protobuf/csharp/Google.Protobuf.Tools.nuspec new file mode 100644 index 0000000..098d79d --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/Google.Protobuf.Tools.nuspec @@ -0,0 +1,38 @@ + + + + Google.Protobuf.Tools + Google Protocol Buffers tools + Tools for Protocol Buffers - Google's data interchange format. + See project site for more info. + 3.19.4 + Google Inc. + protobuf-packages + https://github.com/protocolbuffers/protobuf/blob/master/LICENSE + https://github.com/protocolbuffers/protobuf + false + Tools for Protocol Buffers + Copyright 2015, Google Inc. + Protocol Buffers Binary Serialization Format Google proto proto3 + + + + + + + + + + + + + + + + + + + + + + diff --git a/tools/env-vars-generator/protobuf/csharp/compatibility_tests/v3.0.0/protos/csharp/protos/unittest_issues.proto b/tools/env-vars-generator/protobuf/csharp/compatibility_tests/v3.0.0/protos/csharp/protos/unittest_issues.proto new file mode 100644 index 0000000..b6178bf --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/compatibility_tests/v3.0.0/protos/csharp/protos/unittest_issues.proto @@ -0,0 +1,126 @@ +syntax = "proto3"; + +// These proto descriptors have at one time been reported as an issue or defect. +// They are kept here to replicate the issue, and continue to verify the fix. + +// Issue: Non-"Google.Protobuffers" namespace will ensure that protobuffer library types are qualified +option csharp_namespace = "UnitTest.Issues.TestProtos"; + +package unittest_issues; +option optimize_for = SPEED; + +// Issue 307: when generating doubly-nested types, any references +// should be of the form A.Types.B.Types.C. +message Issue307 { + message NestedOnce { + message NestedTwice { + } + } +} + +// Old issue 13: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=13 +// New issue 309: https://github.com/protocolbuffers/protobuf/issues/309 + +// message A { +// optional int32 _A = 1; +// } + +// message B { +// optional int32 B_ = 1; +// } + +//message AB { +// optional int32 a_b = 1; +//} + +// Similar issue with numeric names +// Java code failed too, so probably best for this to be a restriction. +// See https://github.com/protocolbuffers/protobuf/issues/308 +// message NumberField { +// optional int32 _01 = 1; +// } + +// issue 19 - negative enum values + +enum NegativeEnum { + NEGATIVE_ENUM_ZERO = 0; + FiveBelow = -5; + MinusOne = -1; +} + +message NegativeEnumMessage { + NegativeEnum value = 1; + repeated NegativeEnum values = 2 [packed = false]; + repeated NegativeEnum packed_values = 3 [packed=true]; +} + +// Issue 21: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=21 +// Decorate fields with [deprecated=true] as [System.Obsolete] + +message DeprecatedChild { +} + +enum DeprecatedEnum { + DEPRECATED_ZERO = 0; + one = 1; +} + +message DeprecatedFieldsMessage { + int32 PrimitiveValue = 1 [deprecated = true]; + repeated int32 PrimitiveArray = 2 [deprecated = true]; + + DeprecatedChild MessageValue = 3 [deprecated = true]; + repeated DeprecatedChild MessageArray = 4 [deprecated = true]; + + DeprecatedEnum EnumValue = 5 [deprecated = true]; + repeated DeprecatedEnum EnumArray = 6 [deprecated = true]; +} + +// Issue 45: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=45 +message ItemField { + int32 item = 1; +} + +message ReservedNames { + // Force a nested type called Types + message SomeNestedType { + } + + int32 types = 1; + int32 descriptor = 2; +} + +message TestJsonFieldOrdering { + // These fields are deliberately not declared in numeric + // order, and the oneof fields aren't contiguous either. + // This allows for reasonably robust tests of JSON output + // ordering. + // TestFieldOrderings in unittest_proto3.proto is similar, + // but doesn't include oneofs. + // TODO: Consider adding oneofs to TestFieldOrderings, although + // that will require fixing other tests in multiple platforms. + // Alternatively, consider just adding this to + // unittest_proto3.proto if multiple platforms want it. + + int32 plain_int32 = 4; + + oneof o1 { + string o1_string = 2; + int32 o1_int32 = 5; + } + + string plain_string = 1; + + oneof o2 { + int32 o2_int32 = 6; + string o2_string = 3; + } + +} + +message TestJsonName { + // Message for testing the effects for of the json_name option + string name = 1; + string description = 2 [json_name = "desc"]; + string guid = 3 [json_name = "exid"]; +} diff --git a/tools/env-vars-generator/protobuf/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/ByteStringTest.cs b/tools/env-vars-generator/protobuf/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/ByteStringTest.cs new file mode 100644 index 0000000..685e130 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/ByteStringTest.cs @@ -0,0 +1,171 @@ +#region Copyright notice and license +// 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. +#endregion + +using System; +using System.Text; +using NUnit.Framework; + +namespace Google.Protobuf +{ + public class ByteStringTest + { + [Test] + public void Equality() + { + ByteString b1 = ByteString.CopyFrom(1, 2, 3); + ByteString b2 = ByteString.CopyFrom(1, 2, 3); + ByteString b3 = ByteString.CopyFrom(1, 2, 4); + ByteString b4 = ByteString.CopyFrom(1, 2, 3, 4); + EqualityTester.AssertEquality(b1, b1); + EqualityTester.AssertEquality(b1, b2); + EqualityTester.AssertInequality(b1, b3); + EqualityTester.AssertInequality(b1, b4); + EqualityTester.AssertInequality(b1, null); +#pragma warning disable 1718 // Deliberately calling ==(b1, b1) and !=(b1, b1) + Assert.IsTrue(b1 == b1); + Assert.IsTrue(b1 == b2); + Assert.IsFalse(b1 == b3); + Assert.IsFalse(b1 == b4); + Assert.IsFalse(b1 == null); + Assert.IsTrue((ByteString) null == null); + Assert.IsFalse(b1 != b1); + Assert.IsFalse(b1 != b2); +#pragma warning disable 1718 + Assert.IsTrue(b1 != b3); + Assert.IsTrue(b1 != b4); + Assert.IsTrue(b1 != null); + Assert.IsFalse((ByteString) null != null); + } + + [Test] + public void EmptyByteStringHasZeroSize() + { + Assert.AreEqual(0, ByteString.Empty.Length); + } + + [Test] + public void CopyFromStringWithExplicitEncoding() + { + ByteString bs = ByteString.CopyFrom("AB", Encoding.Unicode); + Assert.AreEqual(4, bs.Length); + Assert.AreEqual(65, bs[0]); + Assert.AreEqual(0, bs[1]); + Assert.AreEqual(66, bs[2]); + Assert.AreEqual(0, bs[3]); + } + + [Test] + public void IsEmptyWhenEmpty() + { + Assert.IsTrue(ByteString.CopyFromUtf8("").IsEmpty); + } + + [Test] + public void IsEmptyWhenNotEmpty() + { + Assert.IsFalse(ByteString.CopyFromUtf8("X").IsEmpty); + } + + [Test] + public void CopyFromByteArrayCopiesContents() + { + byte[] data = new byte[1]; + data[0] = 10; + ByteString bs = ByteString.CopyFrom(data); + Assert.AreEqual(10, bs[0]); + data[0] = 5; + Assert.AreEqual(10, bs[0]); + } + + [Test] + public void ToByteArrayCopiesContents() + { + ByteString bs = ByteString.CopyFromUtf8("Hello"); + byte[] data = bs.ToByteArray(); + Assert.AreEqual((byte)'H', data[0]); + Assert.AreEqual((byte)'H', bs[0]); + data[0] = 0; + Assert.AreEqual(0, data[0]); + Assert.AreEqual((byte)'H', bs[0]); + } + + [Test] + public void CopyFromUtf8UsesUtf8() + { + ByteString bs = ByteString.CopyFromUtf8("\u20ac"); + Assert.AreEqual(3, bs.Length); + Assert.AreEqual(0xe2, bs[0]); + Assert.AreEqual(0x82, bs[1]); + Assert.AreEqual(0xac, bs[2]); + } + + [Test] + public void CopyFromPortion() + { + byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6}; + ByteString bs = ByteString.CopyFrom(data, 2, 3); + Assert.AreEqual(3, bs.Length); + Assert.AreEqual(2, bs[0]); + Assert.AreEqual(3, bs[1]); + } + + [Test] + public void ToStringUtf8() + { + ByteString bs = ByteString.CopyFromUtf8("\u20ac"); + Assert.AreEqual("\u20ac", bs.ToStringUtf8()); + } + + [Test] + public void ToStringWithExplicitEncoding() + { + ByteString bs = ByteString.CopyFrom("\u20ac", Encoding.Unicode); + Assert.AreEqual("\u20ac", bs.ToString(Encoding.Unicode)); + } + + [Test] + public void FromBase64_WithText() + { + byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6}; + string base64 = Convert.ToBase64String(data); + ByteString bs = ByteString.FromBase64(base64); + Assert.AreEqual(data, bs.ToByteArray()); + } + + [Test] + public void FromBase64_Empty() + { + // Optimization which also fixes issue 61. + Assert.AreSame(ByteString.Empty, ByteString.FromBase64("")); + } + } +} \ No newline at end of file diff --git a/tools/env-vars-generator/protobuf/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Collections/RepeatedFieldTest.cs b/tools/env-vars-generator/protobuf/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Collections/RepeatedFieldTest.cs new file mode 100644 index 0000000..6852f75 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Collections/RepeatedFieldTest.cs @@ -0,0 +1,746 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using Google.Protobuf.TestProtos; +using Google.Protobuf.WellKnownTypes; +using NUnit.Framework; + +namespace Google.Protobuf.Collections +{ + public class RepeatedFieldTest + { + [Test] + public void NullValuesRejected() + { + var list = new RepeatedField(); + Assert.Throws(() => list.Add((string)null)); + Assert.Throws(() => list.Add((IEnumerable)null)); + Assert.Throws(() => list.Add((RepeatedField)null)); + Assert.Throws(() => list.Contains(null)); + Assert.Throws(() => list.IndexOf(null)); + } + + [Test] + public void Add_SingleItem() + { + var list = new RepeatedField(); + list.Add("foo"); + Assert.AreEqual(1, list.Count); + Assert.AreEqual("foo", list[0]); + } + + [Test] + public void Add_Sequence() + { + var list = new RepeatedField(); + list.Add(new[] { "foo", "bar" }); + Assert.AreEqual(2, list.Count); + Assert.AreEqual("foo", list[0]); + Assert.AreEqual("bar", list[1]); + } + + [Test] + public void AddRange_SlowPath() + { + var list = new RepeatedField(); + list.AddRange(new[] { "foo", "bar" }.Select(x => x)); + Assert.AreEqual(2, list.Count); + Assert.AreEqual("foo", list[0]); + Assert.AreEqual("bar", list[1]); + } + + [Test] + public void AddRange_SlowPath_NullsProhibited_ReferenceType() + { + var list = new RepeatedField(); + // It's okay for this to throw ArgumentNullException if necessary. + // It's not ideal, but not awful. + Assert.Catch(() => list.AddRange(new[] { "foo", null }.Select(x => x))); + } + + [Test] + public void AddRange_SlowPath_NullsProhibited_NullableValueType() + { + var list = new RepeatedField(); + // It's okay for this to throw ArgumentNullException if necessary. + // It's not ideal, but not awful. + Assert.Catch(() => list.AddRange(new[] { 20, (int?)null }.Select(x => x))); + } + + [Test] + public void AddRange_Optimized_NonNullableValueType() + { + var list = new RepeatedField(); + list.AddRange(new List { 20, 30 }); + Assert.AreEqual(2, list.Count); + Assert.AreEqual(20, list[0]); + Assert.AreEqual(30, list[1]); + } + + [Test] + public void AddRange_Optimized_ReferenceType() + { + var list = new RepeatedField(); + list.AddRange(new List { "foo", "bar" }); + Assert.AreEqual(2, list.Count); + Assert.AreEqual("foo", list[0]); + Assert.AreEqual("bar", list[1]); + } + + [Test] + public void AddRange_Optimized_NullableValueType() + { + var list = new RepeatedField(); + list.AddRange(new List { 20, 30 }); + Assert.AreEqual(2, list.Count); + Assert.AreEqual((int?) 20, list[0]); + Assert.AreEqual((int?) 30, list[1]); + } + + [Test] + public void AddRange_Optimized_NullsProhibited_ReferenceType() + { + // We don't just trust that a collection with a nullable element type doesn't contain nulls + var list = new RepeatedField(); + // It's okay for this to throw ArgumentNullException if necessary. + // It's not ideal, but not awful. + Assert.Catch(() => list.AddRange(new List { "foo", null })); + } + + [Test] + public void AddRange_Optimized_NullsProhibited_NullableValueType() + { + // We don't just trust that a collection with a nullable element type doesn't contain nulls + var list = new RepeatedField(); + // It's okay for this to throw ArgumentNullException if necessary. + // It's not ideal, but not awful. + Assert.Catch(() => list.AddRange(new List { 20, null })); + } + + [Test] + public void AddRange_AlreadyNotEmpty() + { + var list = new RepeatedField { 1, 2, 3 }; + list.AddRange(new List { 4, 5, 6 }); + CollectionAssert.AreEqual(new[] { 1, 2, 3, 4, 5, 6 }, list); + } + + [Test] + public void AddRange_RepeatedField() + { + var list = new RepeatedField { "original" }; + list.AddRange(new RepeatedField { "foo", "bar" }); + Assert.AreEqual(3, list.Count); + Assert.AreEqual("original", list[0]); + Assert.AreEqual("foo", list[1]); + Assert.AreEqual("bar", list[2]); + } + + [Test] + public void RemoveAt_Valid() + { + var list = new RepeatedField { "first", "second", "third" }; + list.RemoveAt(1); + CollectionAssert.AreEqual(new[] { "first", "third" }, list); + // Just check that these don't throw... + list.RemoveAt(list.Count - 1); // Now the count will be 1... + list.RemoveAt(0); + Assert.AreEqual(0, list.Count); + } + + [Test] + public void RemoveAt_Invalid() + { + var list = new RepeatedField { "first", "second", "third" }; + Assert.Throws(() => list.RemoveAt(-1)); + Assert.Throws(() => list.RemoveAt(3)); + } + + [Test] + public void Insert_Valid() + { + var list = new RepeatedField { "first", "second" }; + list.Insert(1, "middle"); + CollectionAssert.AreEqual(new[] { "first", "middle", "second" }, list); + list.Insert(3, "end"); + CollectionAssert.AreEqual(new[] { "first", "middle", "second", "end" }, list); + list.Insert(0, "start"); + CollectionAssert.AreEqual(new[] { "start", "first", "middle", "second", "end" }, list); + } + + [Test] + public void Insert_Invalid() + { + var list = new RepeatedField { "first", "second" }; + Assert.Throws(() => list.Insert(-1, "foo")); + Assert.Throws(() => list.Insert(3, "foo")); + Assert.Throws(() => list.Insert(0, null)); + } + + [Test] + public void Equals_RepeatedField() + { + var list = new RepeatedField { "first", "second" }; + Assert.IsFalse(list.Equals((RepeatedField) null)); + Assert.IsTrue(list.Equals(list)); + Assert.IsFalse(list.Equals(new RepeatedField { "first", "third" })); + Assert.IsFalse(list.Equals(new RepeatedField { "first" })); + Assert.IsTrue(list.Equals(new RepeatedField { "first", "second" })); + } + + [Test] + public void Equals_Object() + { + var list = new RepeatedField { "first", "second" }; + Assert.IsFalse(list.Equals((object) null)); + Assert.IsTrue(list.Equals((object) list)); + Assert.IsFalse(list.Equals((object) new RepeatedField { "first", "third" })); + Assert.IsFalse(list.Equals((object) new RepeatedField { "first" })); + Assert.IsTrue(list.Equals((object) new RepeatedField { "first", "second" })); + Assert.IsFalse(list.Equals(new object())); + } + + [Test] + public void GetEnumerator_GenericInterface() + { + IEnumerable list = new RepeatedField { "first", "second" }; + // Select gets rid of the optimizations in ToList... + CollectionAssert.AreEqual(new[] { "first", "second" }, list.Select(x => x).ToList()); + } + + [Test] + public void GetEnumerator_NonGenericInterface() + { + IEnumerable list = new RepeatedField { "first", "second" }; + CollectionAssert.AreEqual(new[] { "first", "second" }, list.Cast().ToList()); + } + + [Test] + public void CopyTo() + { + var list = new RepeatedField { "first", "second" }; + string[] stringArray = new string[4]; + list.CopyTo(stringArray, 1); + CollectionAssert.AreEqual(new[] { null, "first", "second", null }, stringArray); + } + + [Test] + public void Indexer_Get() + { + var list = new RepeatedField { "first", "second" }; + Assert.AreEqual("first", list[0]); + Assert.AreEqual("second", list[1]); + Assert.Throws(() => list[-1].GetHashCode()); + Assert.Throws(() => list[2].GetHashCode()); + } + + [Test] + public void Indexer_Set() + { + var list = new RepeatedField { "first", "second" }; + list[0] = "changed"; + Assert.AreEqual("changed", list[0]); + Assert.Throws(() => list[0] = null); + Assert.Throws(() => list[-1] = "bad"); + Assert.Throws(() => list[2] = "bad"); + } + + [Test] + public void Clone_ReturnsMutable() + { + var list = new RepeatedField { 0 }; + var clone = list.Clone(); + clone[0] = 1; + } + + [Test] + public void Enumerator() + { + var list = new RepeatedField { "first", "second" }; + using (var enumerator = list.GetEnumerator()) + { + Assert.IsTrue(enumerator.MoveNext()); + Assert.AreEqual("first", enumerator.Current); + Assert.IsTrue(enumerator.MoveNext()); + Assert.AreEqual("second", enumerator.Current); + Assert.IsFalse(enumerator.MoveNext()); + Assert.IsFalse(enumerator.MoveNext()); + } + } + + [Test] + public void AddEntriesFrom_PackedInt32() + { + uint packedTag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited); + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + var length = CodedOutputStream.ComputeInt32Size(10) + + CodedOutputStream.ComputeInt32Size(999) + + CodedOutputStream.ComputeInt32Size(-1000); + output.WriteTag(packedTag); + output.WriteRawVarint32((uint) length); + output.WriteInt32(10); + output.WriteInt32(999); + output.WriteInt32(-1000); + output.Flush(); + stream.Position = 0; + + // Deliberately "expecting" a non-packed tag, but we detect that the data is + // actually packed. + uint nonPackedTag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited); + var field = new RepeatedField(); + var input = new CodedInputStream(stream); + input.AssertNextTag(packedTag); + field.AddEntriesFrom(input, FieldCodec.ForInt32(nonPackedTag)); + CollectionAssert.AreEqual(new[] { 10, 999, -1000 }, field); + Assert.IsTrue(input.IsAtEnd); + } + + [Test] + public void AddEntriesFrom_NonPackedInt32() + { + uint nonPackedTag = WireFormat.MakeTag(10, WireFormat.WireType.Varint); + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + output.WriteTag(nonPackedTag); + output.WriteInt32(10); + output.WriteTag(nonPackedTag); + output.WriteInt32(999); + output.WriteTag(nonPackedTag); + output.WriteInt32(-1000); // Just for variety... + output.Flush(); + stream.Position = 0; + + // Deliberately "expecting" a packed tag, but we detect that the data is + // actually not packed. + uint packedTag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited); + var field = new RepeatedField(); + var input = new CodedInputStream(stream); + input.AssertNextTag(nonPackedTag); + field.AddEntriesFrom(input, FieldCodec.ForInt32(packedTag)); + CollectionAssert.AreEqual(new[] { 10, 999, -1000 }, field); + Assert.IsTrue(input.IsAtEnd); + } + + [Test] + public void AddEntriesFrom_String() + { + uint tag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited); + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + output.WriteTag(tag); + output.WriteString("Foo"); + output.WriteTag(tag); + output.WriteString(""); + output.WriteTag(tag); + output.WriteString("Bar"); + output.Flush(); + stream.Position = 0; + + var field = new RepeatedField(); + var input = new CodedInputStream(stream); + input.AssertNextTag(tag); + field.AddEntriesFrom(input, FieldCodec.ForString(tag)); + CollectionAssert.AreEqual(new[] { "Foo", "", "Bar" }, field); + Assert.IsTrue(input.IsAtEnd); + } + + [Test] + public void AddEntriesFrom_Message() + { + var message1 = new ForeignMessage { C = 2000 }; + var message2 = new ForeignMessage { C = -250 }; + + uint tag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited); + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + output.WriteTag(tag); + output.WriteMessage(message1); + output.WriteTag(tag); + output.WriteMessage(message2); + output.Flush(); + stream.Position = 0; + + var field = new RepeatedField(); + var input = new CodedInputStream(stream); + input.AssertNextTag(tag); + field.AddEntriesFrom(input, FieldCodec.ForMessage(tag, ForeignMessage.Parser)); + CollectionAssert.AreEqual(new[] { message1, message2}, field); + Assert.IsTrue(input.IsAtEnd); + } + + [Test] + public void WriteTo_PackedInt32() + { + uint tag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited); + var field = new RepeatedField { 10, 1000, 1000000 }; + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + field.WriteTo(output, FieldCodec.ForInt32(tag)); + output.Flush(); + stream.Position = 0; + + var input = new CodedInputStream(stream); + input.AssertNextTag(tag); + var length = input.ReadLength(); + Assert.AreEqual(10, input.ReadInt32()); + Assert.AreEqual(1000, input.ReadInt32()); + Assert.AreEqual(1000000, input.ReadInt32()); + Assert.IsTrue(input.IsAtEnd); + Assert.AreEqual(1 + CodedOutputStream.ComputeLengthSize(length) + length, stream.Length); + } + + [Test] + public void WriteTo_NonPackedInt32() + { + uint tag = WireFormat.MakeTag(10, WireFormat.WireType.Varint); + var field = new RepeatedField { 10, 1000, 1000000}; + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + field.WriteTo(output, FieldCodec.ForInt32(tag)); + output.Flush(); + stream.Position = 0; + + var input = new CodedInputStream(stream); + input.AssertNextTag(tag); + Assert.AreEqual(10, input.ReadInt32()); + input.AssertNextTag(tag); + Assert.AreEqual(1000, input.ReadInt32()); + input.AssertNextTag(tag); + Assert.AreEqual(1000000, input.ReadInt32()); + Assert.IsTrue(input.IsAtEnd); + } + + [Test] + public void WriteTo_String() + { + uint tag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited); + var field = new RepeatedField { "Foo", "", "Bar" }; + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + field.WriteTo(output, FieldCodec.ForString(tag)); + output.Flush(); + stream.Position = 0; + + var input = new CodedInputStream(stream); + input.AssertNextTag(tag); + Assert.AreEqual("Foo", input.ReadString()); + input.AssertNextTag(tag); + Assert.AreEqual("", input.ReadString()); + input.AssertNextTag(tag); + Assert.AreEqual("Bar", input.ReadString()); + Assert.IsTrue(input.IsAtEnd); + } + + [Test] + public void WriteTo_Message() + { + var message1 = new ForeignMessage { C = 20 }; + var message2 = new ForeignMessage { C = 25 }; + uint tag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited); + var field = new RepeatedField { message1, message2 }; + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + field.WriteTo(output, FieldCodec.ForMessage(tag, ForeignMessage.Parser)); + output.Flush(); + stream.Position = 0; + + var input = new CodedInputStream(stream); + input.AssertNextTag(tag); + Assert.AreEqual(message1, input.ReadMessage(ForeignMessage.Parser)); + input.AssertNextTag(tag); + Assert.AreEqual(message2, input.ReadMessage(ForeignMessage.Parser)); + Assert.IsTrue(input.IsAtEnd); + } + + [Test] + public void CalculateSize_VariableSizeNonPacked() + { + var list = new RepeatedField { 1, 500, 1 }; + var tag = WireFormat.MakeTag(1, WireFormat.WireType.Varint); + // 2 bytes for the first entry, 3 bytes for the second, 2 bytes for the third + Assert.AreEqual(7, list.CalculateSize(FieldCodec.ForInt32(tag))); + } + + [Test] + public void CalculateSize_FixedSizeNonPacked() + { + var list = new RepeatedField { 1, 500, 1 }; + var tag = WireFormat.MakeTag(1, WireFormat.WireType.Fixed32); + // 5 bytes for the each entry + Assert.AreEqual(15, list.CalculateSize(FieldCodec.ForSFixed32(tag))); + } + + [Test] + public void CalculateSize_VariableSizePacked() + { + var list = new RepeatedField { 1, 500, 1}; + var tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); + // 1 byte for the tag, 1 byte for the length, + // 1 byte for the first entry, 2 bytes for the second, 1 byte for the third + Assert.AreEqual(6, list.CalculateSize(FieldCodec.ForInt32(tag))); + } + + [Test] + public void CalculateSize_FixedSizePacked() + { + var list = new RepeatedField { 1, 500, 1 }; + var tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); + // 1 byte for the tag, 1 byte for the length, 4 bytes per entry + Assert.AreEqual(14, list.CalculateSize(FieldCodec.ForSFixed32(tag))); + } + + [Test] + public void TestNegativeEnumArray() + { + int arraySize = 1 + 1 + (11 * 5); + int msgSize = arraySize; + byte[] bytes = new byte[msgSize]; + CodedOutputStream output = new CodedOutputStream(bytes); + uint tag = WireFormat.MakeTag(8, WireFormat.WireType.Varint); + for (int i = 0; i >= -5; i--) + { + output.WriteTag(tag); + output.WriteEnum(i); + } + + Assert.AreEqual(0, output.SpaceLeft); + + CodedInputStream input = new CodedInputStream(bytes); + tag = input.ReadTag(); + + RepeatedField values = new RepeatedField(); + values.AddEntriesFrom(input, FieldCodec.ForEnum(tag, x => (int)x, x => (SampleEnum)x)); + + Assert.AreEqual(6, values.Count); + Assert.AreEqual(SampleEnum.None, values[0]); + Assert.AreEqual(((SampleEnum)(-1)), values[1]); + Assert.AreEqual(SampleEnum.NegativeValue, values[2]); + Assert.AreEqual(((SampleEnum)(-3)), values[3]); + Assert.AreEqual(((SampleEnum)(-4)), values[4]); + Assert.AreEqual(((SampleEnum)(-5)), values[5]); + } + + + [Test] + public void TestNegativeEnumPackedArray() + { + int arraySize = 1 + (10 * 5); + int msgSize = 1 + 1 + arraySize; + byte[] bytes = new byte[msgSize]; + CodedOutputStream output = new CodedOutputStream(bytes); + // Length-delimited to show we want the packed representation + uint tag = WireFormat.MakeTag(8, WireFormat.WireType.LengthDelimited); + output.WriteTag(tag); + int size = 0; + for (int i = 0; i >= -5; i--) + { + size += CodedOutputStream.ComputeEnumSize(i); + } + output.WriteRawVarint32((uint)size); + for (int i = 0; i >= -5; i--) + { + output.WriteEnum(i); + } + Assert.AreEqual(0, output.SpaceLeft); + + CodedInputStream input = new CodedInputStream(bytes); + tag = input.ReadTag(); + + RepeatedField values = new RepeatedField(); + values.AddEntriesFrom(input, FieldCodec.ForEnum(tag, x => (int)x, x => (SampleEnum)x)); + + Assert.AreEqual(6, values.Count); + Assert.AreEqual(SampleEnum.None, values[0]); + Assert.AreEqual(((SampleEnum)(-1)), values[1]); + Assert.AreEqual(SampleEnum.NegativeValue, values[2]); + Assert.AreEqual(((SampleEnum)(-3)), values[3]); + Assert.AreEqual(((SampleEnum)(-4)), values[4]); + Assert.AreEqual(((SampleEnum)(-5)), values[5]); + } + + // Fairly perfunctory tests for the non-generic IList implementation + [Test] + public void IList_Indexer() + { + var field = new RepeatedField { "first", "second" }; + IList list = field; + Assert.AreEqual("first", list[0]); + list[1] = "changed"; + Assert.AreEqual("changed", field[1]); + } + + [Test] + public void IList_Contains() + { + IList list = new RepeatedField { "first", "second" }; + Assert.IsTrue(list.Contains("second")); + Assert.IsFalse(list.Contains("third")); + Assert.IsFalse(list.Contains(new object())); + } + + [Test] + public void IList_Add() + { + IList list = new RepeatedField { "first", "second" }; + list.Add("third"); + CollectionAssert.AreEqual(new[] { "first", "second", "third" }, list); + } + + [Test] + public void IList_Remove() + { + IList list = new RepeatedField { "first", "second" }; + list.Remove("third"); // No-op, no exception + list.Remove(new object()); // No-op, no exception + list.Remove("first"); + CollectionAssert.AreEqual(new[] { "second" }, list); + } + + [Test] + public void IList_IsFixedSize() + { + var field = new RepeatedField { "first", "second" }; + IList list = field; + Assert.IsFalse(list.IsFixedSize); + } + + [Test] + public void IList_IndexOf() + { + IList list = new RepeatedField { "first", "second" }; + Assert.AreEqual(1, list.IndexOf("second")); + Assert.AreEqual(-1, list.IndexOf("third")); + Assert.AreEqual(-1, list.IndexOf(new object())); + } + + [Test] + public void IList_SyncRoot() + { + IList list = new RepeatedField { "first", "second" }; + Assert.AreSame(list, list.SyncRoot); + } + + [Test] + public void IList_CopyTo() + { + IList list = new RepeatedField { "first", "second" }; + string[] stringArray = new string[4]; + list.CopyTo(stringArray, 1); + CollectionAssert.AreEqual(new[] { null, "first", "second", null }, stringArray); + + object[] objectArray = new object[4]; + list.CopyTo(objectArray, 1); + CollectionAssert.AreEqual(new[] { null, "first", "second", null }, objectArray); + + Assert.Throws(() => list.CopyTo(new StringBuilder[4], 1)); + Assert.Throws(() => list.CopyTo(new int[4], 1)); + } + + [Test] + public void IList_IsSynchronized() + { + IList list = new RepeatedField { "first", "second" }; + Assert.IsFalse(list.IsSynchronized); + } + + [Test] + public void IList_Insert() + { + IList list = new RepeatedField { "first", "second" }; + list.Insert(1, "middle"); + CollectionAssert.AreEqual(new[] { "first", "middle", "second" }, list); + } + + [Test] + public void ToString_Integers() + { + var list = new RepeatedField { 5, 10, 20 }; + var text = list.ToString(); + Assert.AreEqual("[ 5, 10, 20 ]", text); + } + + [Test] + public void ToString_Strings() + { + var list = new RepeatedField { "x", "y", "z" }; + var text = list.ToString(); + Assert.AreEqual("[ \"x\", \"y\", \"z\" ]", text); + } + + [Test] + public void ToString_Messages() + { + var list = new RepeatedField { new TestAllTypes { SingleDouble = 1.5 }, new TestAllTypes { SingleInt32 = 10 } }; + var text = list.ToString(); + Assert.AreEqual("[ { \"singleDouble\": 1.5 }, { \"singleInt32\": 10 } ]", text); + } + + [Test] + public void ToString_Empty() + { + var list = new RepeatedField { }; + var text = list.ToString(); + Assert.AreEqual("[ ]", text); + } + + [Test] + public void ToString_InvalidElementType() + { + var list = new RepeatedField { 15m }; + Assert.Throws(() => list.ToString()); + } + + [Test] + public void ToString_Timestamp() + { + var list = new RepeatedField { Timestamp.FromDateTime(new DateTime(2015, 10, 1, 12, 34, 56, DateTimeKind.Utc)) }; + var text = list.ToString(); + Assert.AreEqual("[ \"2015-10-01T12:34:56Z\" ]", text); + } + + [Test] + public void ToString_Struct() + { + var message = new Struct { Fields = { { "foo", new Value { NumberValue = 20 } } } }; + var list = new RepeatedField { message }; + var text = list.ToString(); + Assert.AreEqual(text, "[ { \"foo\": 20 } ]", message.ToString()); + } + } +} diff --git a/tools/env-vars-generator/protobuf/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/TestProtos/ForeignMessagePartial.cs b/tools/env-vars-generator/protobuf/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/TestProtos/ForeignMessagePartial.cs new file mode 100644 index 0000000..5663a69 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/TestProtos/ForeignMessagePartial.cs @@ -0,0 +1,45 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2016 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. +#endregion + +namespace Google.Protobuf.TestProtos +{ + /// + /// A message with custom diagnostics (to test that they work). + /// + public partial class ForeignMessage : ICustomDiagnosticMessage + { + public string ToDiagnosticString() + { + return $"{{ \"c\": {C}, \"@cInHex\": \"{C:x}\" }}"; + } + } +} diff --git a/tools/env-vars-generator/protobuf/csharp/generate_protos.sh b/tools/env-vars-generator/protobuf/csharp/generate_protos.sh new file mode 100755 index 0000000..b663138 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/generate_protos.sh @@ -0,0 +1,87 @@ +#!/bin/bash +# Generates C# source files from .proto files. +# You first need to make sure protoc has been built (see instructions on +# building protoc in root of this repository) + +set -e + +# cd to repository root +pushd $(dirname $0)/.. + +# Protocol buffer compiler to use. If the PROTOC variable is set, +# use that. Otherwise, probe for expected locations under both +# Windows and Unix. +if [ -z "$PROTOC" ]; then + # TODO(jonskeet): Use an array and a for loop instead? + if [ -x cmake/build/Debug/protoc.exe ]; then + PROTOC=cmake/build/Debug/protoc.exe + elif [ -x cmake/build/Release/protoc.exe ]; then + PROTOC=cmake/build/Release/protoc.exe + elif [ -x src/protoc ]; then + PROTOC=src/protoc + else + echo "Unable to find protocol buffer compiler." + exit 1 + fi +fi + +# descriptor.proto and well-known types +$PROTOC -Isrc --csharp_out=csharp/src/Google.Protobuf \ + --csharp_opt=base_namespace=Google.Protobuf \ + src/google/protobuf/descriptor.proto \ + src/google/protobuf/any.proto \ + src/google/protobuf/api.proto \ + src/google/protobuf/duration.proto \ + src/google/protobuf/empty.proto \ + src/google/protobuf/field_mask.proto \ + src/google/protobuf/source_context.proto \ + src/google/protobuf/struct.proto \ + src/google/protobuf/timestamp.proto \ + src/google/protobuf/type.proto \ + src/google/protobuf/wrappers.proto + +# Test protos +# Note that this deliberately does *not* include old_extensions1.proto +# and old_extensions2.proto, which are generated with an older version +# of protoc. +$PROTOC -Isrc -Icsharp/protos \ + --experimental_allow_proto3_optional \ + --csharp_out=csharp/src/Google.Protobuf.Test.TestProtos \ + --descriptor_set_out=csharp/src/Google.Protobuf.Test/testprotos.pb \ + --include_source_info \ + --include_imports \ + csharp/protos/map_unittest_proto3.proto \ + csharp/protos/unittest_issues.proto \ + csharp/protos/unittest_custom_options_proto3.proto \ + csharp/protos/unittest_proto3.proto \ + csharp/protos/unittest_import_proto3.proto \ + csharp/protos/unittest_import_public_proto3.proto \ + csharp/protos/unittest.proto \ + csharp/protos/unittest_import.proto \ + csharp/protos/unittest_import_public.proto \ + csharp/protos/unittest_issue6936_a.proto \ + csharp/protos/unittest_issue6936_b.proto \ + csharp/protos/unittest_issue6936_c.proto \ + csharp/protos/unittest_selfreferential_options.proto \ + src/google/protobuf/unittest_well_known_types.proto \ + src/google/protobuf/test_messages_proto3.proto \ + src/google/protobuf/test_messages_proto2.proto \ + src/google/protobuf/unittest_proto3_optional.proto + +# AddressBook sample protos +$PROTOC -Iexamples -Isrc --csharp_out=csharp/src/AddressBook \ + examples/addressbook.proto + +$PROTOC -Iconformance -Isrc --csharp_out=csharp/src/Google.Protobuf.Conformance \ + conformance/conformance.proto + +# Benchmark protos +$PROTOC -Ibenchmarks \ + benchmarks/datasets/google_message1/proto3/*.proto \ + benchmarks/benchmarks.proto \ + --csharp_out=csharp/src/Google.Protobuf.Benchmarks + +# C# only benchmark protos +$PROTOC -Isrc -Icsharp/src/Google.Protobuf.Benchmarks \ + csharp/src/Google.Protobuf.Benchmarks/*.proto \ + --csharp_out=csharp/src/Google.Protobuf.Benchmarks diff --git a/tools/env-vars-generator/protobuf/csharp/protos/old_extensions2.proto b/tools/env-vars-generator/protobuf/csharp/protos/old_extensions2.proto new file mode 100644 index 0000000..78f732a --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/protos/old_extensions2.proto @@ -0,0 +1,50 @@ +// 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. +// +// A proto file we will use for unit testing. +// +// LINT: ALLOW_GROUPS, LEGACY_NAMES + +// This file is part of the unit test for issue #6822. It is +// generated with protoc from version 3.10.1. + +syntax = "proto3"; + +import "google/protobuf/descriptor.proto"; + +option csharp_namespace = "Google.Protobuf.TestProtos.OldGenerator"; + +extend google.protobuf.MethodOptions { + string method_ext = 1234567; +} \ No newline at end of file diff --git a/tools/env-vars-generator/protobuf/csharp/protos/unittest.proto b/tools/env-vars-generator/protobuf/csharp/protos/unittest.proto new file mode 100644 index 0000000..9628b9e --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/protos/unittest.proto @@ -0,0 +1,1113 @@ +// 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. +// +// A proto file we will use for unit testing. +// +// LINT: ALLOW_GROUPS, LEGACY_NAMES + +syntax = "proto2"; + +// Some generic_services option(s) added automatically. +// See: http://go/proto2-generic-services-default +option cc_generic_services = true; // auto-added +option java_generic_services = true; // auto-added +option py_generic_services = true; // auto-added +option cc_enable_arenas = true; + +import "unittest_import.proto"; + +// We don't put this in a package within proto2 because we need to make sure +// that the generated code doesn't depend on being in the proto2 namespace. +// In test_util.h we do "using namespace unittest = protobuf_unittest". +package protobuf_unittest_proto2; + +// Protos optimized for SPEED use a strict superset of the generated code +// of equivalent ones optimized for CODE_SIZE, so we should optimize all our +// tests for speed unless explicitly testing code size optimization. +option optimize_for = SPEED; + +option csharp_namespace = "Google.Protobuf.TestProtos.Proto2"; + +// This proto includes every type of field in both singular and repeated +// forms. +message TestAllTypes { + message NestedMessage { + // The field name "b" fails to compile in proto1 because it conflicts with + // a local variable named "b" in one of the generated methods. Doh. + // This file needs to compile in proto1 to test backwards-compatibility. + optional int32 bb = 1; + } + + enum NestedEnum { + FOO = 1; + BAR = 2; + BAZ = 3; + NEG = -1; // Intentionally negative. + } + + // Singular + optional int32 optional_int32 = 1; + optional int64 optional_int64 = 2; + optional uint32 optional_uint32 = 3; + optional uint64 optional_uint64 = 4; + optional sint32 optional_sint32 = 5; + optional sint64 optional_sint64 = 6; + optional fixed32 optional_fixed32 = 7; + optional fixed64 optional_fixed64 = 8; + optional sfixed32 optional_sfixed32 = 9; + optional sfixed64 optional_sfixed64 = 10; + optional float optional_float = 11; + optional double optional_double = 12; + optional bool optional_bool = 13; + optional string optional_string = 14; + optional bytes optional_bytes = 15; + + optional group OptionalGroup = 16 { + optional int32 a = 17; + } + + optional NestedMessage optional_nested_message = 18; + optional ForeignMessage optional_foreign_message = 19; + optional protobuf_unittest_import_proto2.ImportMessage optional_import_message = 20; + + optional NestedEnum optional_nested_enum = 21; + optional ForeignEnum optional_foreign_enum = 22; + optional protobuf_unittest_import_proto2.ImportEnum optional_import_enum = 23; + + optional string optional_string_piece = 24 [ctype=STRING_PIECE]; + optional string optional_cord = 25 [ctype=CORD]; + + // Defined in unittest_import_public.proto + optional protobuf_unittest_import_proto2.PublicImportMessage + optional_public_import_message = 26; + + optional NestedMessage optional_lazy_message = 27 [lazy=true]; + + // Repeated + repeated int32 repeated_int32 = 31; + repeated int64 repeated_int64 = 32; + repeated uint32 repeated_uint32 = 33; + repeated uint64 repeated_uint64 = 34; + repeated sint32 repeated_sint32 = 35; + repeated sint64 repeated_sint64 = 36; + repeated fixed32 repeated_fixed32 = 37; + repeated fixed64 repeated_fixed64 = 38; + repeated sfixed32 repeated_sfixed32 = 39; + repeated sfixed64 repeated_sfixed64 = 40; + repeated float repeated_float = 41; + repeated double repeated_double = 42; + repeated bool repeated_bool = 43; + repeated string repeated_string = 44; + repeated bytes repeated_bytes = 45; + + repeated group RepeatedGroup = 46 { + optional int32 a = 47; + } + + repeated NestedMessage repeated_nested_message = 48; + repeated ForeignMessage repeated_foreign_message = 49; + repeated protobuf_unittest_import_proto2.ImportMessage repeated_import_message = 50; + + repeated NestedEnum repeated_nested_enum = 51; + repeated ForeignEnum repeated_foreign_enum = 52; + repeated protobuf_unittest_import_proto2.ImportEnum repeated_import_enum = 53; + + repeated string repeated_string_piece = 54 [ctype=STRING_PIECE]; + repeated string repeated_cord = 55 [ctype=CORD]; + + repeated NestedMessage repeated_lazy_message = 57 [lazy=true]; + + // Singular with defaults + optional int32 default_int32 = 61 [default = 41 ]; + optional int64 default_int64 = 62 [default = 42 ]; + optional uint32 default_uint32 = 63 [default = 43 ]; + optional uint64 default_uint64 = 64 [default = 44 ]; + optional sint32 default_sint32 = 65 [default = -45 ]; + optional sint64 default_sint64 = 66 [default = 46 ]; + optional fixed32 default_fixed32 = 67 [default = 47 ]; + optional fixed64 default_fixed64 = 68 [default = 48 ]; + optional sfixed32 default_sfixed32 = 69 [default = 49 ]; + optional sfixed64 default_sfixed64 = 70 [default = -50 ]; + optional float default_float = 71 [default = 51.5 ]; + optional double default_double = 72 [default = 52e3 ]; + optional bool default_bool = 73 [default = true ]; + optional string default_string = 74 [default = "hello"]; + optional bytes default_bytes = 75 [default = "world"]; + + optional NestedEnum default_nested_enum = 81 [default = BAR ]; + optional ForeignEnum default_foreign_enum = 82 [default = FOREIGN_BAR]; + optional protobuf_unittest_import_proto2.ImportEnum + default_import_enum = 83 [default = IMPORT_BAR]; + + optional string default_string_piece = 84 [ctype=STRING_PIECE,default="abc"]; + optional string default_cord = 85 [ctype=CORD,default="123"]; + + // For oneof test + oneof oneof_field { + uint32 oneof_uint32 = 111; + NestedMessage oneof_nested_message = 112; + string oneof_string = 113; + bytes oneof_bytes = 114; + } +} + +// This proto includes a recursively nested message. +message NestedTestAllTypes { + optional NestedTestAllTypes child = 1; + optional TestAllTypes payload = 2; + repeated NestedTestAllTypes repeated_child = 3; +} + +message TestDeprecatedFields { + optional int32 deprecated_int32 = 1 [deprecated=true]; + oneof oneof_fields { + int32 deprecated_int32_in_oneof = 2 [deprecated=true]; + } +} + +message TestDeprecatedMessage { + option deprecated = true; +} + +// Define these after TestAllTypes to make sure the compiler can handle +// that. +message ForeignMessage { + optional int32 c = 1; + optional int32 d = 2; +} + +enum ForeignEnum { + FOREIGN_FOO = 4; + FOREIGN_BAR = 5; + FOREIGN_BAZ = 6; +} + +message TestReservedFields { + reserved 2, 15, 9 to 11; + reserved "bar", "baz"; +} + +message TestAllExtensions { + extensions 1 to max; +} + +extend TestAllExtensions { + // Singular + optional int32 optional_int32_extension = 1; + optional int64 optional_int64_extension = 2; + optional uint32 optional_uint32_extension = 3; + optional uint64 optional_uint64_extension = 4; + optional sint32 optional_sint32_extension = 5; + optional sint64 optional_sint64_extension = 6; + optional fixed32 optional_fixed32_extension = 7; + optional fixed64 optional_fixed64_extension = 8; + optional sfixed32 optional_sfixed32_extension = 9; + optional sfixed64 optional_sfixed64_extension = 10; + optional float optional_float_extension = 11; + optional double optional_double_extension = 12; + optional bool optional_bool_extension = 13; + optional string optional_string_extension = 14; + optional bytes optional_bytes_extension = 15; + + optional group OptionalGroup_extension = 16 { + optional int32 a = 17; + } + + optional TestAllTypes.NestedMessage optional_nested_message_extension = 18; + optional ForeignMessage optional_foreign_message_extension = 19; + optional protobuf_unittest_import_proto2.ImportMessage + optional_import_message_extension = 20; + + optional TestAllTypes.NestedEnum optional_nested_enum_extension = 21; + optional ForeignEnum optional_foreign_enum_extension = 22; + optional protobuf_unittest_import_proto2.ImportEnum + optional_import_enum_extension = 23; + + optional string optional_string_piece_extension = 24 [ctype=STRING_PIECE]; + optional string optional_cord_extension = 25 [ctype=CORD]; + + optional protobuf_unittest_import_proto2.PublicImportMessage + optional_public_import_message_extension = 26; + + optional TestAllTypes.NestedMessage + optional_lazy_message_extension = 27 [lazy=true]; + + // Repeated + repeated int32 repeated_int32_extension = 31; + repeated int64 repeated_int64_extension = 32; + repeated uint32 repeated_uint32_extension = 33; + repeated uint64 repeated_uint64_extension = 34; + repeated sint32 repeated_sint32_extension = 35; + repeated sint64 repeated_sint64_extension = 36; + repeated fixed32 repeated_fixed32_extension = 37; + repeated fixed64 repeated_fixed64_extension = 38; + repeated sfixed32 repeated_sfixed32_extension = 39; + repeated sfixed64 repeated_sfixed64_extension = 40; + repeated float repeated_float_extension = 41; + repeated double repeated_double_extension = 42; + repeated bool repeated_bool_extension = 43; + repeated string repeated_string_extension = 44; + repeated bytes repeated_bytes_extension = 45; + + repeated group RepeatedGroup_extension = 46 { + optional int32 a = 47; + } + + repeated TestAllTypes.NestedMessage repeated_nested_message_extension = 48; + repeated ForeignMessage repeated_foreign_message_extension = 49; + repeated protobuf_unittest_import_proto2.ImportMessage + repeated_import_message_extension = 50; + + repeated TestAllTypes.NestedEnum repeated_nested_enum_extension = 51; + repeated ForeignEnum repeated_foreign_enum_extension = 52; + repeated protobuf_unittest_import_proto2.ImportEnum + repeated_import_enum_extension = 53; + + repeated string repeated_string_piece_extension = 54 [ctype=STRING_PIECE]; + repeated string repeated_cord_extension = 55 [ctype=CORD]; + + repeated TestAllTypes.NestedMessage + repeated_lazy_message_extension = 57 [lazy=true]; + + // Singular with defaults + optional int32 default_int32_extension = 61 [default = 41 ]; + optional int64 default_int64_extension = 62 [default = 42 ]; + optional uint32 default_uint32_extension = 63 [default = 43 ]; + optional uint64 default_uint64_extension = 64 [default = 44 ]; + optional sint32 default_sint32_extension = 65 [default = -45 ]; + optional sint64 default_sint64_extension = 66 [default = 46 ]; + optional fixed32 default_fixed32_extension = 67 [default = 47 ]; + optional fixed64 default_fixed64_extension = 68 [default = 48 ]; + optional sfixed32 default_sfixed32_extension = 69 [default = 49 ]; + optional sfixed64 default_sfixed64_extension = 70 [default = -50 ]; + optional float default_float_extension = 71 [default = 51.5 ]; + optional double default_double_extension = 72 [default = 52e3 ]; + optional bool default_bool_extension = 73 [default = true ]; + optional string default_string_extension = 74 [default = "hello"]; + optional bytes default_bytes_extension = 75 [default = "world"]; + + optional TestAllTypes.NestedEnum + default_nested_enum_extension = 81 [default = BAR]; + optional ForeignEnum + default_foreign_enum_extension = 82 [default = FOREIGN_BAR]; + optional protobuf_unittest_import_proto2.ImportEnum + default_import_enum_extension = 83 [default = IMPORT_BAR]; + + optional string default_string_piece_extension = 84 [ctype=STRING_PIECE, + default="abc"]; + optional string default_cord_extension = 85 [ctype=CORD, default="123"]; + + // For oneof test + optional uint32 oneof_uint32_extension = 111; + optional TestAllTypes.NestedMessage oneof_nested_message_extension = 112; + optional string oneof_string_extension = 113; + optional bytes oneof_bytes_extension = 114; +} + +message TestGroup { + optional group OptionalGroup = 16 { + optional int32 a = 17; + } + optional ForeignEnum optional_foreign_enum = 22; +} + +message TestGroupExtension { + extensions 1 to max; +} + +message TestNestedExtension { + extend TestAllExtensions { + // Check for bug where string extensions declared in tested scope did not + // compile. + optional string test = 1002 [default="test"]; + // Used to test if generated extension name is correct when there are + // underscores. + optional string nested_string_extension = 1003; + } + + extend TestGroupExtension { + optional group OptionalGroup_extension = 16 { + optional int32 a = 17; + } + optional ForeignEnum optional_foreign_enum_extension = 22; + } +} + +// We have separate messages for testing required fields because it's +// annoying to have to fill in required fields in TestProto in order to +// do anything with it. Note that we don't need to test every type of +// required filed because the code output is basically identical to +// optional fields for all types. +message TestRequired { + required int32 a = 1; + optional int32 dummy2 = 2; + required int32 b = 3; + + extend TestAllExtensions { + optional TestRequired single = 1000; + repeated TestRequired multi = 1001; + } + + // Pad the field count to 32 so that we can test that IsInitialized() + // properly checks multiple elements of has_bits_. + optional int32 dummy4 = 4; + optional int32 dummy5 = 5; + optional int32 dummy6 = 6; + optional int32 dummy7 = 7; + optional int32 dummy8 = 8; + optional int32 dummy9 = 9; + optional int32 dummy10 = 10; + optional int32 dummy11 = 11; + optional int32 dummy12 = 12; + optional int32 dummy13 = 13; + optional int32 dummy14 = 14; + optional int32 dummy15 = 15; + optional int32 dummy16 = 16; + optional int32 dummy17 = 17; + optional int32 dummy18 = 18; + optional int32 dummy19 = 19; + optional int32 dummy20 = 20; + optional int32 dummy21 = 21; + optional int32 dummy22 = 22; + optional int32 dummy23 = 23; + optional int32 dummy24 = 24; + optional int32 dummy25 = 25; + optional int32 dummy26 = 26; + optional int32 dummy27 = 27; + optional int32 dummy28 = 28; + optional int32 dummy29 = 29; + optional int32 dummy30 = 30; + optional int32 dummy31 = 31; + optional int32 dummy32 = 32; + + required int32 c = 33; +} + +message TestRequiredForeign { + optional TestRequired optional_message = 1; + repeated TestRequired repeated_message = 2; + optional int32 dummy = 3; +} + +message TestRequiredMessage { + optional TestRequired optional_message = 1; + repeated TestRequired repeated_message = 2; + required TestRequired required_message = 3; +} + +// Test that we can use NestedMessage from outside TestAllTypes. +message TestForeignNested { + optional TestAllTypes.NestedMessage foreign_nested = 1; +} + +// TestEmptyMessage is used to test unknown field support. +message TestEmptyMessage { +} + +// Like above, but declare all field numbers as potential extensions. No +// actual extensions should ever be defined for this type. +message TestEmptyMessageWithExtensions { + extensions 1 to max; +} + +message TestMultipleExtensionRanges { + extensions 42; + extensions 4143 to 4243; + extensions 65536 to max; +} + +// Test that really large tag numbers don't break anything. +message TestReallyLargeTagNumber { + // The largest possible tag number is 2^28 - 1, since the wire format uses + // three bits to communicate wire type. + optional int32 a = 1; + optional int32 bb = 268435455; +} + +message TestRecursiveMessage { + optional TestRecursiveMessage a = 1; + optional int32 i = 2; +} + +// Test that mutual recursion works. +message TestMutualRecursionA { + message SubMessage { + optional TestMutualRecursionB b = 1; + } + optional TestMutualRecursionB bb = 1; + optional group SubGroup = 2 { + optional SubMessage sub_message = 3; // Needed because of bug in javatest + optional TestAllTypes not_in_this_scc = 4; + } +} + +message TestMutualRecursionB { + optional TestMutualRecursionA a = 1; + optional int32 optional_int32 = 2; +} + +message TestIsInitialized { + message SubMessage { + optional group SubGroup = 1 { + required int32 i = 2; + } + } + optional SubMessage sub_message = 1; +} + +// Test that groups have disjoint field numbers from their siblings and +// parents. This is NOT possible in proto1; only google.protobuf. When attempting +// to compile with proto1, this will emit an error; so we only include it +// in protobuf_unittest_proto. +message TestDupFieldNumber { // NO_PROTO1 + optional int32 a = 1; // NO_PROTO1 + optional group Foo = 2 { optional int32 a = 1; } // NO_PROTO1 + optional group Bar = 3 { optional int32 a = 1; } // NO_PROTO1 +} // NO_PROTO1 + +// Additional messages for testing lazy fields. +message TestEagerMessage { + optional TestAllTypes sub_message = 1 [lazy=false]; +} +message TestLazyMessage { + optional TestAllTypes sub_message = 1 [lazy=true]; +} + +// Needed for a Python test. +message TestNestedMessageHasBits { + message NestedMessage { + repeated int32 nestedmessage_repeated_int32 = 1; + repeated ForeignMessage nestedmessage_repeated_foreignmessage = 2; + } + optional NestedMessage optional_nested_message = 1; +} + + +// Test an enum that has multiple values with the same number. +enum TestEnumWithDupValue { + option allow_alias = true; + + FOO1 = 1; + BAR1 = 2; + BAZ = 3; + FOO2 = 1; + BAR2 = 2; +} + +// Test an enum with large, unordered values. +enum TestSparseEnum { + SPARSE_A = 123; + SPARSE_B = 62374; + SPARSE_C = 12589234; + SPARSE_D = -15; + SPARSE_E = -53452; + SPARSE_F = 0; + SPARSE_G = 2; +} + +// Test message with CamelCase field names. This violates Protocol Buffer +// standard style. +message TestCamelCaseFieldNames { + optional int32 PrimitiveField = 1; + optional string StringField = 2; + optional ForeignEnum EnumField = 3; + optional ForeignMessage MessageField = 4; + optional string StringPieceField = 5 [ctype=STRING_PIECE]; + optional string CordField = 6 [ctype=CORD]; + + repeated int32 RepeatedPrimitiveField = 7; + repeated string RepeatedStringField = 8; + repeated ForeignEnum RepeatedEnumField = 9; + repeated ForeignMessage RepeatedMessageField = 10; + repeated string RepeatedStringPieceField = 11 [ctype=STRING_PIECE]; + repeated string RepeatedCordField = 12 [ctype=CORD]; +} + + +// We list fields out of order, to ensure that we're using field number and not +// field index to determine serialization order. +message TestFieldOrderings { + optional string my_string = 11; + extensions 2 to 10; + optional int64 my_int = 1; + extensions 12 to 100; + optional float my_float = 101; + message NestedMessage { + optional int64 oo = 2; + // The field name "b" fails to compile in proto1 because it conflicts with + // a local variable named "b" in one of the generated methods. Doh. + // This file needs to compile in proto1 to test backwards-compatibility. + optional int32 bb = 1; + } + + optional NestedMessage optional_nested_message = 200; +} + +extend TestFieldOrderings { + optional string my_extension_string = 50; + optional int32 my_extension_int = 5; +} + +message TestExtensionOrderings1 { + extend TestFieldOrderings { + optional TestExtensionOrderings1 test_ext_orderings1 = 13; + } + optional string my_string = 1; +} + +message TestExtensionOrderings2 { + extend TestFieldOrderings { + optional TestExtensionOrderings2 test_ext_orderings2 = 12; + } + message TestExtensionOrderings3 { + extend TestFieldOrderings { + optional TestExtensionOrderings3 test_ext_orderings3 = 14; + } + optional string my_string = 1; + } + optional string my_string = 1; +} + +message TestExtremeDefaultValues { + optional bytes escaped_bytes = 1 [default = "\0\001\a\b\f\n\r\t\v\\\'\"\xfe"]; + optional uint32 large_uint32 = 2 [default = 0xFFFFFFFF]; + optional uint64 large_uint64 = 3 [default = 0xFFFFFFFFFFFFFFFF]; + optional int32 small_int32 = 4 [default = -0x7FFFFFFF]; + optional int64 small_int64 = 5 [default = -0x7FFFFFFFFFFFFFFF]; + optional int32 really_small_int32 = 21 [default = -0x80000000]; + optional int64 really_small_int64 = 22 [default = -0x8000000000000000]; + + // The default value here is UTF-8 for "\u1234". (We could also just type + // the UTF-8 text directly into this text file rather than escape it, but + // lots of people use editors that would be confused by this.) + optional string utf8_string = 6 [default = "\341\210\264"]; + + // Tests for single-precision floating-point values. + optional float zero_float = 7 [default = 0]; + optional float one_float = 8 [default = 1]; + optional float small_float = 9 [default = 1.5]; + optional float negative_one_float = 10 [default = -1]; + optional float negative_float = 11 [default = -1.5]; + // Using exponents + optional float large_float = 12 [default = 2E8]; + optional float small_negative_float = 13 [default = -8e-28]; + + // Text for nonfinite floating-point values. + optional double inf_double = 14 [default = inf]; + optional double neg_inf_double = 15 [default = -inf]; + optional double nan_double = 16 [default = nan]; + optional float inf_float = 17 [default = inf]; + optional float neg_inf_float = 18 [default = -inf]; + optional float nan_float = 19 [default = nan]; + + // Tests for C++ trigraphs. + // Trigraphs should be escaped in C++ generated files, but they should not be + // escaped for other languages. + // Note that in .proto file, "\?" is a valid way to escape ? in string + // literals. + optional string cpp_trigraph = 20 [default = "? \? ?? \?? \??? ??/ ?\?-"]; + + // String defaults containing the character '\000' + optional string string_with_zero = 23 [default = "hel\000lo"]; + optional bytes bytes_with_zero = 24 [default = "wor\000ld"]; + optional string string_piece_with_zero = 25 [ctype=STRING_PIECE, + default="ab\000c"]; + optional string cord_with_zero = 26 [ctype=CORD, + default="12\0003"]; + optional string replacement_string = 27 [default="${unknown}"]; +} + +message SparseEnumMessage { + optional TestSparseEnum sparse_enum = 1; +} + +// Test String and Bytes: string is for valid UTF-8 strings +message OneString { + optional string data = 1; +} + +message MoreString { + repeated string data = 1; +} + +message OneBytes { + optional bytes data = 1; +} + +message MoreBytes { + repeated bytes data = 1; +} + +// Test int32, uint32, int64, uint64, and bool are all compatible +message Int32Message { + optional int32 data = 1; +} + +message Uint32Message { + optional uint32 data = 1; +} + +message Int64Message { + optional int64 data = 1; +} + +message Uint64Message { + optional uint64 data = 1; +} + +message BoolMessage { + optional bool data = 1; +} + +// Test oneofs. +message TestOneof { + oneof foo { + int32 foo_int = 1; + string foo_string = 2; + TestAllTypes foo_message = 3; + group FooGroup = 4 { + optional int32 a = 5; + optional string b = 6; + } + } +} + +message TestOneofBackwardsCompatible { + optional int32 foo_int = 1; + optional string foo_string = 2; + optional TestAllTypes foo_message = 3; + optional group FooGroup = 4 { + optional int32 a = 5; + optional string b = 6; + } +} + +message TestOneof2 { + oneof foo { + int32 foo_int = 1; + string foo_string = 2; + string foo_cord = 3 [ctype=CORD]; + string foo_string_piece = 4 [ctype=STRING_PIECE]; + bytes foo_bytes = 5; + NestedEnum foo_enum = 6; + NestedMessage foo_message = 7; + group FooGroup = 8 { + optional int32 a = 9; + optional string b = 10; + } + NestedMessage foo_lazy_message = 11 [lazy=true]; + } + + oneof bar { + int32 bar_int = 12 [default = 5]; + string bar_string = 13 [default = "STRING"]; + string bar_cord = 14 [ctype=CORD, default = "CORD"]; + string bar_string_piece = 15 [ctype=STRING_PIECE, default = "SPIECE"]; + bytes bar_bytes = 16 [default = "BYTES"]; + NestedEnum bar_enum = 17 [default = BAR]; + } + + optional int32 baz_int = 18; + optional string baz_string = 19 [default = "BAZ"]; + + message NestedMessage { + optional int64 qux_int = 1; + repeated int32 corge_int = 2; + } + + enum NestedEnum { + FOO = 1; + BAR = 2; + BAZ = 3; + } +} + +message TestRequiredOneof { + oneof foo { + int32 foo_int = 1; + string foo_string = 2; + NestedMessage foo_message = 3; + } + message NestedMessage { + required double required_double = 1; + } +} + +message TestRequiredMap { + map foo = 1; + message NestedMessage { + required int32 required_int32 = 1; + } +} + +// Test messages for packed fields + +message TestPackedTypes { + repeated int32 packed_int32 = 90 [packed = true]; + repeated int64 packed_int64 = 91 [packed = true]; + repeated uint32 packed_uint32 = 92 [packed = true]; + repeated uint64 packed_uint64 = 93 [packed = true]; + repeated sint32 packed_sint32 = 94 [packed = true]; + repeated sint64 packed_sint64 = 95 [packed = true]; + repeated fixed32 packed_fixed32 = 96 [packed = true]; + repeated fixed64 packed_fixed64 = 97 [packed = true]; + repeated sfixed32 packed_sfixed32 = 98 [packed = true]; + repeated sfixed64 packed_sfixed64 = 99 [packed = true]; + repeated float packed_float = 100 [packed = true]; + repeated double packed_double = 101 [packed = true]; + repeated bool packed_bool = 102 [packed = true]; + repeated ForeignEnum packed_enum = 103 [packed = true]; +} + +// A message with the same fields as TestPackedTypes, but without packing. Used +// to test packed <-> unpacked wire compatibility. +message TestUnpackedTypes { + repeated int32 unpacked_int32 = 90 [packed = false]; + repeated int64 unpacked_int64 = 91 [packed = false]; + repeated uint32 unpacked_uint32 = 92 [packed = false]; + repeated uint64 unpacked_uint64 = 93 [packed = false]; + repeated sint32 unpacked_sint32 = 94 [packed = false]; + repeated sint64 unpacked_sint64 = 95 [packed = false]; + repeated fixed32 unpacked_fixed32 = 96 [packed = false]; + repeated fixed64 unpacked_fixed64 = 97 [packed = false]; + repeated sfixed32 unpacked_sfixed32 = 98 [packed = false]; + repeated sfixed64 unpacked_sfixed64 = 99 [packed = false]; + repeated float unpacked_float = 100 [packed = false]; + repeated double unpacked_double = 101 [packed = false]; + repeated bool unpacked_bool = 102 [packed = false]; + repeated ForeignEnum unpacked_enum = 103 [packed = false]; +} + +message TestPackedExtensions { + extensions 1 to max; +} + +extend TestPackedExtensions { + repeated int32 packed_int32_extension = 90 [packed = true]; + repeated int64 packed_int64_extension = 91 [packed = true]; + repeated uint32 packed_uint32_extension = 92 [packed = true]; + repeated uint64 packed_uint64_extension = 93 [packed = true]; + repeated sint32 packed_sint32_extension = 94 [packed = true]; + repeated sint64 packed_sint64_extension = 95 [packed = true]; + repeated fixed32 packed_fixed32_extension = 96 [packed = true]; + repeated fixed64 packed_fixed64_extension = 97 [packed = true]; + repeated sfixed32 packed_sfixed32_extension = 98 [packed = true]; + repeated sfixed64 packed_sfixed64_extension = 99 [packed = true]; + repeated float packed_float_extension = 100 [packed = true]; + repeated double packed_double_extension = 101 [packed = true]; + repeated bool packed_bool_extension = 102 [packed = true]; + repeated ForeignEnum packed_enum_extension = 103 [packed = true]; +} + +message TestUnpackedExtensions { + extensions 1 to max; +} + +extend TestUnpackedExtensions { + repeated int32 unpacked_int32_extension = 90 [packed = false]; + repeated int64 unpacked_int64_extension = 91 [packed = false]; + repeated uint32 unpacked_uint32_extension = 92 [packed = false]; + repeated uint64 unpacked_uint64_extension = 93 [packed = false]; + repeated sint32 unpacked_sint32_extension = 94 [packed = false]; + repeated sint64 unpacked_sint64_extension = 95 [packed = false]; + repeated fixed32 unpacked_fixed32_extension = 96 [packed = false]; + repeated fixed64 unpacked_fixed64_extension = 97 [packed = false]; + repeated sfixed32 unpacked_sfixed32_extension = 98 [packed = false]; + repeated sfixed64 unpacked_sfixed64_extension = 99 [packed = false]; + repeated float unpacked_float_extension = 100 [packed = false]; + repeated double unpacked_double_extension = 101 [packed = false]; + repeated bool unpacked_bool_extension = 102 [packed = false]; + repeated ForeignEnum unpacked_enum_extension = 103 [packed = false]; +} + +// Used by ExtensionSetTest/DynamicExtensions. The test actually builds +// a set of extensions to TestAllExtensions dynamically, based on the fields +// of this message type. +message TestDynamicExtensions { + enum DynamicEnumType { + DYNAMIC_FOO = 2200; + DYNAMIC_BAR = 2201; + DYNAMIC_BAZ = 2202; + } + message DynamicMessageType { + optional int32 dynamic_field = 2100; + } + + optional fixed32 scalar_extension = 2000; + optional ForeignEnum enum_extension = 2001; + optional DynamicEnumType dynamic_enum_extension = 2002; + + optional ForeignMessage message_extension = 2003; + optional DynamicMessageType dynamic_message_extension = 2004; + + repeated string repeated_extension = 2005; + repeated sint32 packed_extension = 2006 [packed = true]; +} + +message TestRepeatedScalarDifferentTagSizes { + // Parsing repeated fixed size values used to fail. This message needs to be + // used in order to get a tag of the right size; all of the repeated fields + // in TestAllTypes didn't trigger the check. + repeated fixed32 repeated_fixed32 = 12; + // Check for a varint type, just for good measure. + repeated int32 repeated_int32 = 13; + + // These have two-byte tags. + repeated fixed64 repeated_fixed64 = 2046; + repeated int64 repeated_int64 = 2047; + + // Three byte tags. + repeated float repeated_float = 262142; + repeated uint64 repeated_uint64 = 262143; +} + +// Test that if an optional or required message/group field appears multiple +// times in the input, they need to be merged. +message TestParsingMerge { + // RepeatedFieldsGenerator defines matching field types as TestParsingMerge, + // except that all fields are repeated. In the tests, we will serialize the + // RepeatedFieldsGenerator to bytes, and parse the bytes to TestParsingMerge. + // Repeated fields in RepeatedFieldsGenerator are expected to be merged into + // the corresponding required/optional fields in TestParsingMerge. + message RepeatedFieldsGenerator { + repeated TestAllTypes field1 = 1; + repeated TestAllTypes field2 = 2; + repeated TestAllTypes field3 = 3; + repeated group Group1 = 10 { + optional TestAllTypes field1 = 11; + } + repeated group Group2 = 20 { + optional TestAllTypes field1 = 21; + } + repeated TestAllTypes ext1 = 1000; + repeated TestAllTypes ext2 = 1001; + } + required TestAllTypes required_all_types = 1; + optional TestAllTypes optional_all_types = 2; + repeated TestAllTypes repeated_all_types = 3; + optional group OptionalGroup = 10 { + optional TestAllTypes optional_group_all_types = 11; + } + repeated group RepeatedGroup = 20 { + optional TestAllTypes repeated_group_all_types = 21; + } + extensions 1000 to max; + extend TestParsingMerge { + optional TestAllTypes optional_ext = 1000; + repeated TestAllTypes repeated_ext = 1001; + } +} + +message TestCommentInjectionMessage { + // */ <- This should not close the generated doc comment + optional string a = 1 [default="*/ <- Neither should this."]; +} + + +// Test that RPC services work. +message FooRequest {} +message FooResponse {} + +message FooClientMessage {} +message FooServerMessage{} + +service TestService { + rpc Foo(FooRequest) returns (FooResponse); + rpc Bar(BarRequest) returns (BarResponse); +} + + +message BarRequest {} +message BarResponse {} + +message TestJsonName { + optional int32 field_name1 = 1; + optional int32 fieldName2 = 2; + optional int32 FieldName3 = 3; + optional int32 _field_name4 = 4; + optional int32 FIELD_NAME5 = 5; + optional int32 field_name6 = 6 [json_name = "@type"]; +} + +message TestHugeFieldNumbers { + optional int32 optional_int32 = 536870000; + optional int32 fixed_32 = 536870001; + repeated int32 repeated_int32 = 536870002 [packed = false]; + repeated int32 packed_int32 = 536870003 [packed = true]; + + optional ForeignEnum optional_enum = 536870004; + optional string optional_string = 536870005; + optional bytes optional_bytes = 536870006; + optional ForeignMessage optional_message = 536870007; + + optional group OptionalGroup = 536870008 { + optional int32 group_a = 536870009; + } + + map string_string_map = 536870010; + + oneof oneof_field { + uint32 oneof_uint32 = 536870011; + TestAllTypes oneof_test_all_types = 536870012; + string oneof_string = 536870013; + bytes oneof_bytes = 536870014; + } + + extensions 536860000 to 536869999; +} + +extend TestHugeFieldNumbers { + optional TestAllTypes test_all_types = 536860000; +} + +message TestExtensionInsideTable { + optional int32 field1 = 1; + optional int32 field2 = 2; + optional int32 field3 = 3; + optional int32 field4 = 4; + extensions 5 to 5; + optional int32 field6 = 6; + optional int32 field7 = 7; + optional int32 field8 = 8; + optional int32 field9 = 9; + optional int32 field10 = 10; +} + +extend TestExtensionInsideTable { + optional int32 test_extension_inside_table_extension = 5; +} + +enum VeryLargeEnum { + ENUM_LABEL_DEFAULT = 0; + ENUM_LABEL_1 = 1; + ENUM_LABEL_2 = 2; + ENUM_LABEL_3 = 3; + ENUM_LABEL_4 = 4; + ENUM_LABEL_5 = 5; + ENUM_LABEL_6 = 6; + ENUM_LABEL_7 = 7; + ENUM_LABEL_8 = 8; + ENUM_LABEL_9 = 9; + ENUM_LABEL_10 = 10; + ENUM_LABEL_11 = 11; + ENUM_LABEL_12 = 12; + ENUM_LABEL_13 = 13; + ENUM_LABEL_14 = 14; + ENUM_LABEL_15 = 15; + ENUM_LABEL_16 = 16; + ENUM_LABEL_17 = 17; + ENUM_LABEL_18 = 18; + ENUM_LABEL_19 = 19; + ENUM_LABEL_20 = 20; + ENUM_LABEL_21 = 21; + ENUM_LABEL_22 = 22; + ENUM_LABEL_23 = 23; + ENUM_LABEL_24 = 24; + ENUM_LABEL_25 = 25; + ENUM_LABEL_26 = 26; + ENUM_LABEL_27 = 27; + ENUM_LABEL_28 = 28; + ENUM_LABEL_29 = 29; + ENUM_LABEL_30 = 30; + ENUM_LABEL_31 = 31; + ENUM_LABEL_32 = 32; + ENUM_LABEL_33 = 33; + ENUM_LABEL_34 = 34; + ENUM_LABEL_35 = 35; + ENUM_LABEL_36 = 36; + ENUM_LABEL_37 = 37; + ENUM_LABEL_38 = 38; + ENUM_LABEL_39 = 39; + ENUM_LABEL_40 = 40; + ENUM_LABEL_41 = 41; + ENUM_LABEL_42 = 42; + ENUM_LABEL_43 = 43; + ENUM_LABEL_44 = 44; + ENUM_LABEL_45 = 45; + ENUM_LABEL_46 = 46; + ENUM_LABEL_47 = 47; + ENUM_LABEL_48 = 48; + ENUM_LABEL_49 = 49; + ENUM_LABEL_50 = 50; + ENUM_LABEL_51 = 51; + ENUM_LABEL_52 = 52; + ENUM_LABEL_53 = 53; + ENUM_LABEL_54 = 54; + ENUM_LABEL_55 = 55; + ENUM_LABEL_56 = 56; + ENUM_LABEL_57 = 57; + ENUM_LABEL_58 = 58; + ENUM_LABEL_59 = 59; + ENUM_LABEL_60 = 60; + ENUM_LABEL_61 = 61; + ENUM_LABEL_62 = 62; + ENUM_LABEL_63 = 63; + ENUM_LABEL_64 = 64; + ENUM_LABEL_65 = 65; + ENUM_LABEL_66 = 66; + ENUM_LABEL_67 = 67; + ENUM_LABEL_68 = 68; + ENUM_LABEL_69 = 69; + ENUM_LABEL_70 = 70; + ENUM_LABEL_71 = 71; + ENUM_LABEL_72 = 72; + ENUM_LABEL_73 = 73; + ENUM_LABEL_74 = 74; + ENUM_LABEL_75 = 75; + ENUM_LABEL_76 = 76; + ENUM_LABEL_77 = 77; + ENUM_LABEL_78 = 78; + ENUM_LABEL_79 = 79; + ENUM_LABEL_80 = 80; + ENUM_LABEL_81 = 81; + ENUM_LABEL_82 = 82; + ENUM_LABEL_83 = 83; + ENUM_LABEL_84 = 84; + ENUM_LABEL_85 = 85; + ENUM_LABEL_86 = 86; + ENUM_LABEL_87 = 87; + ENUM_LABEL_88 = 88; + ENUM_LABEL_89 = 89; + ENUM_LABEL_90 = 90; + ENUM_LABEL_91 = 91; + ENUM_LABEL_92 = 92; + ENUM_LABEL_93 = 93; + ENUM_LABEL_94 = 94; + ENUM_LABEL_95 = 95; + ENUM_LABEL_96 = 96; + ENUM_LABEL_97 = 97; + ENUM_LABEL_98 = 98; + ENUM_LABEL_99 = 99; + ENUM_LABEL_100 = 100; +}; diff --git a/tools/env-vars-generator/protobuf/csharp/protos/unittest_import_proto3.proto b/tools/env-vars-generator/protobuf/csharp/protos/unittest_import_proto3.proto new file mode 100644 index 0000000..2e66682 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/protos/unittest_import_proto3.proto @@ -0,0 +1,56 @@ +// 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. +// +// A proto file which is imported by unittest_proto3.proto to test importing. + +syntax = "proto3"; + +package protobuf_unittest_import; + +option csharp_namespace = "Google.Protobuf.TestProtos"; + +// Test public import +import public "unittest_import_public_proto3.proto"; + +message ImportMessage { + int32 d = 1; +} + +enum ImportEnum { + IMPORT_ENUM_UNSPECIFIED = 0; + IMPORT_FOO = 7; + IMPORT_BAR = 8; + IMPORT_BAZ = 9; +} + diff --git a/tools/env-vars-generator/protobuf/csharp/protos/unittest_import_public_proto3.proto b/tools/env-vars-generator/protobuf/csharp/protos/unittest_import_public_proto3.proto new file mode 100644 index 0000000..88c2079 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/protos/unittest_import_public_proto3.proto @@ -0,0 +1,41 @@ +// 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: liujisi@google.com (Pherl Liu) + +syntax = "proto3"; + +package protobuf_unittest_import; + +option csharp_namespace = "Google.Protobuf.TestProtos"; + +message PublicImportMessage { + int32 e = 1; +} diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Benchmarks/Google.Protobuf.Benchmarks.csproj b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Benchmarks/Google.Protobuf.Benchmarks.csproj new file mode 100644 index 0000000..ac8e009 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Benchmarks/Google.Protobuf.Benchmarks.csproj @@ -0,0 +1,26 @@ + + + + Exe + net5.0 + ../../keys/Google.Protobuf.snk + true + False + pdbonly + true + + + + + + + + + + + + + + + + diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Benchmarks/ParseMessagesBenchmark.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Benchmarks/ParseMessagesBenchmark.cs new file mode 100644 index 0000000..8e6710b --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Benchmarks/ParseMessagesBenchmark.cs @@ -0,0 +1,258 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2019 Google Inc. All rights reserved. +// https://github.com/protocolbuffers/protobuf +// +// 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. +#endregion + +using BenchmarkDotNet.Attributes; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Buffers; +using Google.Protobuf.WellKnownTypes; +using Benchmarks.Proto3; + +namespace Google.Protobuf.Benchmarks +{ + /// + /// Benchmark that tests parsing performance for various messages. + /// + [MemoryDiagnoser] + public class ParseMessagesBenchmark + { + const int MaxMessages = 100; + + SubTest manyWrapperFieldsTest = new SubTest(CreateManyWrapperFieldsMessage(), ManyWrapperFieldsMessage.Parser, () => new ManyWrapperFieldsMessage(), MaxMessages); + SubTest manyPrimitiveFieldsTest = new SubTest(CreateManyPrimitiveFieldsMessage(), ManyPrimitiveFieldsMessage.Parser, () => new ManyPrimitiveFieldsMessage(), MaxMessages); + SubTest repeatedFieldTest = new SubTest(CreateRepeatedFieldMessage(), GoogleMessage1.Parser, () => new GoogleMessage1(), MaxMessages); + SubTest emptyMessageTest = new SubTest(new Empty(), Empty.Parser, () => new Empty(), MaxMessages); + + public IEnumerable MessageCountValues => new[] { 10, 100 }; + + [GlobalSetup] + public void GlobalSetup() + { + } + + [Benchmark] + public IMessage ManyWrapperFieldsMessage_ParseFromByteArray() + { + return manyWrapperFieldsTest.ParseFromByteArray(); + } + + [Benchmark] + public IMessage ManyWrapperFieldsMessage_ParseFromReadOnlySequence() + { + return manyWrapperFieldsTest.ParseFromReadOnlySequence(); + } + + [Benchmark] + public IMessage ManyPrimitiveFieldsMessage_ParseFromByteArray() + { + return manyPrimitiveFieldsTest.ParseFromByteArray(); + } + + [Benchmark] + public IMessage ManyPrimitiveFieldsMessage_ParseFromReadOnlySequence() + { + return manyPrimitiveFieldsTest.ParseFromReadOnlySequence(); + } + + [Benchmark] + public IMessage RepeatedFieldMessage_ParseFromByteArray() + { + return repeatedFieldTest.ParseFromByteArray(); + } + + [Benchmark] + public IMessage RepeatedFieldMessage_ParseFromReadOnlySequence() + { + return repeatedFieldTest.ParseFromReadOnlySequence(); + } + + [Benchmark] + public IMessage EmptyMessage_ParseFromByteArray() + { + return emptyMessageTest.ParseFromByteArray(); + } + + [Benchmark] + public IMessage EmptyMessage_ParseFromReadOnlySequence() + { + return emptyMessageTest.ParseFromReadOnlySequence(); + } + + [Benchmark] + [ArgumentsSource(nameof(MessageCountValues))] + public void ManyWrapperFieldsMessage_ParseDelimitedMessagesFromByteArray(int messageCount) + { + manyWrapperFieldsTest.ParseDelimitedMessagesFromByteArray(messageCount); + } + + [Benchmark] + [ArgumentsSource(nameof(MessageCountValues))] + public void ManyWrapperFieldsMessage_ParseDelimitedMessagesFromReadOnlySequence(int messageCount) + { + manyWrapperFieldsTest.ParseDelimitedMessagesFromReadOnlySequence(messageCount); + } + + [Benchmark] + [ArgumentsSource(nameof(MessageCountValues))] + public void ManyPrimitiveFieldsMessage_ParseDelimitedMessagesFromByteArray(int messageCount) + { + manyPrimitiveFieldsTest.ParseDelimitedMessagesFromByteArray(messageCount); + } + + [Benchmark] + [ArgumentsSource(nameof(MessageCountValues))] + public void ManyPrimitiveFieldsMessage_ParseDelimitedMessagesFromReadOnlySequence(int messageCount) + { + manyPrimitiveFieldsTest.ParseDelimitedMessagesFromReadOnlySequence(messageCount); + } + + [Benchmark] + [ArgumentsSource(nameof(MessageCountValues))] + public void RepeatedFieldMessage_ParseDelimitedMessagesFromByteArray(int messageCount) + { + repeatedFieldTest.ParseDelimitedMessagesFromByteArray(messageCount); + } + + [Benchmark] + [ArgumentsSource(nameof(MessageCountValues))] + public void RepeatedFieldMessage_ParseDelimitedMessagesFromReadOnlySequence(int messageCount) + { + repeatedFieldTest.ParseDelimitedMessagesFromReadOnlySequence(messageCount); + } + + public static ManyWrapperFieldsMessage CreateManyWrapperFieldsMessage() + { + // Example data match data of an internal benchmarks + return new ManyWrapperFieldsMessage() + { + Int64Field19 = 123, + Int64Field37 = 1000032, + Int64Field26 = 3453524500, + DoubleField79 = 1.2, + DoubleField25 = 234, + DoubleField9 = 123.3, + DoubleField28 = 23, + DoubleField7 = 234, + DoubleField50 = 2.45 + }; + } + + public static ManyPrimitiveFieldsMessage CreateManyPrimitiveFieldsMessage() + { + // Example data match data of an internal benchmarks + return new ManyPrimitiveFieldsMessage() + { + Int64Field19 = 123, + Int64Field37 = 1000032, + Int64Field26 = 3453524500, + DoubleField79 = 1.2, + DoubleField25 = 234, + DoubleField9 = 123.3, + DoubleField28 = 23, + DoubleField7 = 234, + DoubleField50 = 2.45 + }; + } + + public static GoogleMessage1 CreateRepeatedFieldMessage() + { + // Message with a repeated fixed length item collection + var message = new GoogleMessage1(); + for (ulong i = 0; i < 1000; i++) + { + message.Field5.Add(i); + } + return message; + } + + private class SubTest + { + private readonly IMessage message; + private readonly MessageParser parser; + private readonly Func factory; + private readonly byte[] data; + private readonly byte[] multipleMessagesData; + + private ReadOnlySequence dataSequence; + private ReadOnlySequence multipleMessagesDataSequence; + + public SubTest(IMessage message, MessageParser parser, Func factory, int maxMessageCount) + { + this.message = message; + this.parser = parser; + this.factory = factory; + this.data = message.ToByteArray(); + this.multipleMessagesData = CreateBufferWithMultipleMessages(message, maxMessageCount); + this.dataSequence = new ReadOnlySequence(this.data); + this.multipleMessagesDataSequence = new ReadOnlySequence(this.multipleMessagesData); + } + + public IMessage ParseFromByteArray() => parser.ParseFrom(data); + + public IMessage ParseFromReadOnlySequence() => parser.ParseFrom(dataSequence); + + public void ParseDelimitedMessagesFromByteArray(int messageCount) + { + var input = new CodedInputStream(multipleMessagesData); + for (int i = 0; i < messageCount; i++) + { + var msg = factory(); + input.ReadMessage(msg); + } + } + + public void ParseDelimitedMessagesFromReadOnlySequence(int messageCount) + { + ParseContext.Initialize(multipleMessagesDataSequence, out ParseContext ctx); + for (int i = 0; i < messageCount; i++) + { + var msg = factory(); + ctx.ReadMessage(msg); + } + } + + private static byte[] CreateBufferWithMultipleMessages(IMessage msg, int msgCount) + { + var ms = new MemoryStream(); + var cos = new CodedOutputStream(ms); + for (int i = 0; i < msgCount; i++) + { + cos.WriteMessage(msg); + } + cos.Flush(); + return ms.ToArray(); + } + } + } +} diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Benchmarks/WriteMessagesBenchmark.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Benchmarks/WriteMessagesBenchmark.cs new file mode 100644 index 0000000..5a3bba7 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Benchmarks/WriteMessagesBenchmark.cs @@ -0,0 +1,198 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2019 Google Inc. All rights reserved. +// https://github.com/protocolbuffers/protobuf +// +// 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. +#endregion + +using BenchmarkDotNet.Attributes; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Buffers; +using Google.Protobuf.WellKnownTypes; + +namespace Google.Protobuf.Benchmarks +{ + /// + /// Benchmark that tests writing performance for various messages. + /// + [MemoryDiagnoser] + public class WriteMessagesBenchmark + { + const int MaxMessages = 100; + + SubTest manyWrapperFieldsTest = new SubTest(ParseMessagesBenchmark.CreateManyWrapperFieldsMessage(), MaxMessages); + SubTest manyPrimitiveFieldsTest = new SubTest(ParseMessagesBenchmark.CreateManyPrimitiveFieldsMessage(), MaxMessages); + SubTest emptyMessageTest = new SubTest(new Empty(), MaxMessages); + + public IEnumerable MessageCountValues => new[] { 10, 100 }; + + [GlobalSetup] + public void GlobalSetup() + { + } + + [Benchmark] + public byte[] ManyWrapperFieldsMessage_ToByteArray() + { + return manyWrapperFieldsTest.ToByteArray(); + } + + [Benchmark] + public byte[] ManyWrapperFieldsMessage_WriteToCodedOutputStream() + { + return manyWrapperFieldsTest.WriteToCodedOutputStream_PreAllocatedBuffer(); + } + + [Benchmark] + public byte[] ManyWrapperFieldsMessage_WriteToSpan() + { + return manyWrapperFieldsTest.WriteToSpan_PreAllocatedBuffer(); + } + + + [Benchmark] + public byte[] ManyPrimitiveFieldsMessage_ToByteArray() + { + return manyPrimitiveFieldsTest.ToByteArray(); + } + + [Benchmark] + public byte[] ManyPrimitiveFieldsMessage_WriteToCodedOutputStream() + { + return manyPrimitiveFieldsTest.WriteToCodedOutputStream_PreAllocatedBuffer(); + } + + [Benchmark] + public byte[] ManyPrimitiveFieldsMessage_WriteToSpan() + { + return manyPrimitiveFieldsTest.WriteToSpan_PreAllocatedBuffer(); + } + + [Benchmark] + public byte[] EmptyMessage_ToByteArray() + { + return emptyMessageTest.ToByteArray(); + } + + [Benchmark] + public byte[] EmptyMessage_WriteToCodedOutputStream() + { + return emptyMessageTest.WriteToCodedOutputStream_PreAllocatedBuffer(); + } + + [Benchmark] + public byte[] EmptyMessage_WriteToSpan() + { + return emptyMessageTest.WriteToSpan_PreAllocatedBuffer(); + } + + [Benchmark] + [ArgumentsSource(nameof(MessageCountValues))] + public void ManyWrapperFieldsMessage_WriteDelimitedMessagesToCodedOutputStream(int messageCount) + { + manyWrapperFieldsTest.WriteDelimitedMessagesToCodedOutputStream_PreAllocatedBuffer(messageCount); + } + + [Benchmark] + [ArgumentsSource(nameof(MessageCountValues))] + public void ManyWrapperFieldsMessage_WriteDelimitedMessagesToSpan(int messageCount) + { + manyWrapperFieldsTest.WriteDelimitedMessagesToSpan_PreAllocatedBuffer(messageCount); + } + + [Benchmark] + [ArgumentsSource(nameof(MessageCountValues))] + public void ManyPrimitiveFieldsMessage_WriteDelimitedMessagesToCodedOutputStream(int messageCount) + { + manyPrimitiveFieldsTest.WriteDelimitedMessagesToCodedOutputStream_PreAllocatedBuffer(messageCount); + } + + [Benchmark] + [ArgumentsSource(nameof(MessageCountValues))] + public void ManyPrimitiveFieldsMessage_WriteDelimitedMessagesToSpan(int messageCount) + { + manyPrimitiveFieldsTest.WriteDelimitedMessagesToSpan_PreAllocatedBuffer(messageCount); + } + + private class SubTest + { + private readonly IMessage message; + private readonly byte[] outputBuffer; + private readonly byte[] multipleMessagesOutputBuffer; + + public SubTest(IMessage message, int maxMessageCount) + { + this.message = message; + + int messageSize = message.CalculateSize(); + this.outputBuffer = new byte[messageSize]; + this.multipleMessagesOutputBuffer = new byte[maxMessageCount * (messageSize + CodedOutputStream.ComputeLengthSize(messageSize))]; + } + + public byte[] ToByteArray() => message.ToByteArray(); + + public byte[] WriteToCodedOutputStream_PreAllocatedBuffer() + { + var cos = new CodedOutputStream(outputBuffer); // use pre-existing output buffer + message.WriteTo(cos); + return outputBuffer; + } + + public byte[] WriteToSpan_PreAllocatedBuffer() + { + var span = new Span(outputBuffer); // use pre-existing output buffer + message.WriteTo(span); + return outputBuffer; + } + + public byte[] WriteDelimitedMessagesToCodedOutputStream_PreAllocatedBuffer(int messageCount) + { + var cos = new CodedOutputStream(multipleMessagesOutputBuffer); // use pre-existing output buffer + for (int i = 0; i < messageCount; i++) + { + cos.WriteMessage(message); + } + return multipleMessagesOutputBuffer; + } + + public byte[] WriteDelimitedMessagesToSpan_PreAllocatedBuffer(int messageCount) + { + var span = new Span(multipleMessagesOutputBuffer); // use pre-existing output buffer + WriteContext.Initialize(ref span, out WriteContext ctx); + for (int i = 0; i < messageCount; i++) + { + ctx.WriteMessage(message); + } + return multipleMessagesOutputBuffer; + } + } + } +} diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test.TestProtos/OldExtensions2.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test.TestProtos/OldExtensions2.cs new file mode 100644 index 0000000..265dd3b --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test.TestProtos/OldExtensions2.cs @@ -0,0 +1,40 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: old_extensions2.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Google.Protobuf.TestProtos.OldGenerator { + + /// Holder for reflection information generated from old_extensions2.proto + public static partial class OldExtensions2Reflection { + + #region Descriptor + /// File descriptor for old_extensions2.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static OldExtensions2Reflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "ChVvbGRfZXh0ZW5zaW9uczIucHJvdG8aIGdvb2dsZS9wcm90b2J1Zi9kZXNj", + "cmlwdG9yLnByb3RvOjQKCm1ldGhvZF9leHQSHi5nb29nbGUucHJvdG9idWYu", + "TWV0aG9kT3B0aW9ucxiHrUsgASgJQiqqAidHb29nbGUuUHJvdG9idWYuVGVz", + "dFByb3Rvcy5PbGRHZW5lcmF0b3JiBnByb3RvMw==")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { pbr::FileDescriptor.DescriptorProtoFileDescriptor, }, + new pbr::GeneratedClrTypeInfo(null, null)); + } + #endregion + + } +} + +#endregion Designer generated code diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test.TestProtos/Unittest.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test.TestProtos/Unittest.cs new file mode 100644 index 0000000..706b7c4 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test.TestProtos/Unittest.cs @@ -0,0 +1,31821 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: unittest.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Google.Protobuf.TestProtos.Proto2 { + + /// Holder for reflection information generated from unittest.proto + public static partial class UnittestReflection { + + #region Descriptor + /// File descriptor for unittest.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static UnittestReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Cg51bml0dGVzdC5wcm90bxIYcHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yGhV1", + "bml0dGVzdF9pbXBvcnQucHJvdG8igBoKDFRlc3RBbGxUeXBlcxIWCg5vcHRp", + "b25hbF9pbnQzMhgBIAEoBRIWCg5vcHRpb25hbF9pbnQ2NBgCIAEoAxIXCg9v", + "cHRpb25hbF91aW50MzIYAyABKA0SFwoPb3B0aW9uYWxfdWludDY0GAQgASgE", + "EhcKD29wdGlvbmFsX3NpbnQzMhgFIAEoERIXCg9vcHRpb25hbF9zaW50NjQY", + "BiABKBISGAoQb3B0aW9uYWxfZml4ZWQzMhgHIAEoBxIYChBvcHRpb25hbF9m", + "aXhlZDY0GAggASgGEhkKEW9wdGlvbmFsX3NmaXhlZDMyGAkgASgPEhkKEW9w", + "dGlvbmFsX3NmaXhlZDY0GAogASgQEhYKDm9wdGlvbmFsX2Zsb2F0GAsgASgC", + "EhcKD29wdGlvbmFsX2RvdWJsZRgMIAEoARIVCg1vcHRpb25hbF9ib29sGA0g", + "ASgIEhcKD29wdGlvbmFsX3N0cmluZxgOIAEoCRIWCg5vcHRpb25hbF9ieXRl", + "cxgPIAEoDBJLCg1vcHRpb25hbGdyb3VwGBAgASgKMjQucHJvdG9idWZfdW5p", + "dHRlc3RfcHJvdG8yLlRlc3RBbGxUeXBlcy5PcHRpb25hbEdyb3VwElUKF29w", + "dGlvbmFsX25lc3RlZF9tZXNzYWdlGBIgASgLMjQucHJvdG9idWZfdW5pdHRl", + "c3RfcHJvdG8yLlRlc3RBbGxUeXBlcy5OZXN0ZWRNZXNzYWdlEkoKGG9wdGlv", + "bmFsX2ZvcmVpZ25fbWVzc2FnZRgTIAEoCzIoLnByb3RvYnVmX3VuaXR0ZXN0", + "X3Byb3RvMi5Gb3JlaWduTWVzc2FnZRJPChdvcHRpb25hbF9pbXBvcnRfbWVz", + "c2FnZRgUIAEoCzIuLnByb3RvYnVmX3VuaXR0ZXN0X2ltcG9ydF9wcm90bzIu", + "SW1wb3J0TWVzc2FnZRJPChRvcHRpb25hbF9uZXN0ZWRfZW51bRgVIAEoDjIx", + "LnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0QWxsVHlwZXMuTmVzdGVk", + "RW51bRJEChVvcHRpb25hbF9mb3JlaWduX2VudW0YFiABKA4yJS5wcm90b2J1", + "Zl91bml0dGVzdF9wcm90bzIuRm9yZWlnbkVudW0SSQoUb3B0aW9uYWxfaW1w", + "b3J0X2VudW0YFyABKA4yKy5wcm90b2J1Zl91bml0dGVzdF9pbXBvcnRfcHJv", + "dG8yLkltcG9ydEVudW0SIQoVb3B0aW9uYWxfc3RyaW5nX3BpZWNlGBggASgJ", + "QgIIAhIZCg1vcHRpb25hbF9jb3JkGBkgASgJQgIIARJcCh5vcHRpb25hbF9w", + "dWJsaWNfaW1wb3J0X21lc3NhZ2UYGiABKAsyNC5wcm90b2J1Zl91bml0dGVz", + "dF9pbXBvcnRfcHJvdG8yLlB1YmxpY0ltcG9ydE1lc3NhZ2USVwoVb3B0aW9u", + "YWxfbGF6eV9tZXNzYWdlGBsgASgLMjQucHJvdG9idWZfdW5pdHRlc3RfcHJv", + "dG8yLlRlc3RBbGxUeXBlcy5OZXN0ZWRNZXNzYWdlQgIoARIWCg5yZXBlYXRl", + "ZF9pbnQzMhgfIAMoBRIWCg5yZXBlYXRlZF9pbnQ2NBggIAMoAxIXCg9yZXBl", + "YXRlZF91aW50MzIYISADKA0SFwoPcmVwZWF0ZWRfdWludDY0GCIgAygEEhcK", + "D3JlcGVhdGVkX3NpbnQzMhgjIAMoERIXCg9yZXBlYXRlZF9zaW50NjQYJCAD", + "KBISGAoQcmVwZWF0ZWRfZml4ZWQzMhglIAMoBxIYChByZXBlYXRlZF9maXhl", + "ZDY0GCYgAygGEhkKEXJlcGVhdGVkX3NmaXhlZDMyGCcgAygPEhkKEXJlcGVh", + "dGVkX3NmaXhlZDY0GCggAygQEhYKDnJlcGVhdGVkX2Zsb2F0GCkgAygCEhcK", + "D3JlcGVhdGVkX2RvdWJsZRgqIAMoARIVCg1yZXBlYXRlZF9ib29sGCsgAygI", + "EhcKD3JlcGVhdGVkX3N0cmluZxgsIAMoCRIWCg5yZXBlYXRlZF9ieXRlcxgt", + "IAMoDBJLCg1yZXBlYXRlZGdyb3VwGC4gAygKMjQucHJvdG9idWZfdW5pdHRl", + "c3RfcHJvdG8yLlRlc3RBbGxUeXBlcy5SZXBlYXRlZEdyb3VwElUKF3JlcGVh", + "dGVkX25lc3RlZF9tZXNzYWdlGDAgAygLMjQucHJvdG9idWZfdW5pdHRlc3Rf", + "cHJvdG8yLlRlc3RBbGxUeXBlcy5OZXN0ZWRNZXNzYWdlEkoKGHJlcGVhdGVk", + "X2ZvcmVpZ25fbWVzc2FnZRgxIAMoCzIoLnByb3RvYnVmX3VuaXR0ZXN0X3By", + "b3RvMi5Gb3JlaWduTWVzc2FnZRJPChdyZXBlYXRlZF9pbXBvcnRfbWVzc2Fn", + "ZRgyIAMoCzIuLnByb3RvYnVmX3VuaXR0ZXN0X2ltcG9ydF9wcm90bzIuSW1w", + "b3J0TWVzc2FnZRJPChRyZXBlYXRlZF9uZXN0ZWRfZW51bRgzIAMoDjIxLnBy", + "b3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0QWxsVHlwZXMuTmVzdGVkRW51", + "bRJEChVyZXBlYXRlZF9mb3JlaWduX2VudW0YNCADKA4yJS5wcm90b2J1Zl91", + "bml0dGVzdF9wcm90bzIuRm9yZWlnbkVudW0SSQoUcmVwZWF0ZWRfaW1wb3J0", + "X2VudW0YNSADKA4yKy5wcm90b2J1Zl91bml0dGVzdF9pbXBvcnRfcHJvdG8y", + "LkltcG9ydEVudW0SIQoVcmVwZWF0ZWRfc3RyaW5nX3BpZWNlGDYgAygJQgII", + "AhIZCg1yZXBlYXRlZF9jb3JkGDcgAygJQgIIARJXChVyZXBlYXRlZF9sYXp5", + "X21lc3NhZ2UYOSADKAsyNC5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVz", + "dEFsbFR5cGVzLk5lc3RlZE1lc3NhZ2VCAigBEhkKDWRlZmF1bHRfaW50MzIY", + "PSABKAU6AjQxEhkKDWRlZmF1bHRfaW50NjQYPiABKAM6AjQyEhoKDmRlZmF1", + "bHRfdWludDMyGD8gASgNOgI0MxIaCg5kZWZhdWx0X3VpbnQ2NBhAIAEoBDoC", + "NDQSGwoOZGVmYXVsdF9zaW50MzIYQSABKBE6Ay00NRIaCg5kZWZhdWx0X3Np", + "bnQ2NBhCIAEoEjoCNDYSGwoPZGVmYXVsdF9maXhlZDMyGEMgASgHOgI0NxIb", + "Cg9kZWZhdWx0X2ZpeGVkNjQYRCABKAY6AjQ4EhwKEGRlZmF1bHRfc2ZpeGVk", + "MzIYRSABKA86AjQ5Eh0KEGRlZmF1bHRfc2ZpeGVkNjQYRiABKBA6Ay01MBIb", + "Cg1kZWZhdWx0X2Zsb2F0GEcgASgCOgQ1MS41Eh0KDmRlZmF1bHRfZG91Ymxl", + "GEggASgBOgU1MjAwMBIaCgxkZWZhdWx0X2Jvb2wYSSABKAg6BHRydWUSHQoO", + "ZGVmYXVsdF9zdHJpbmcYSiABKAk6BWhlbGxvEhwKDWRlZmF1bHRfYnl0ZXMY", + "SyABKAw6BXdvcmxkElMKE2RlZmF1bHRfbmVzdGVkX2VudW0YUSABKA4yMS5w", + "cm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdEFsbFR5cGVzLk5lc3RlZEVu", + "dW06A0JBUhJQChRkZWZhdWx0X2ZvcmVpZ25fZW51bRhSIAEoDjIlLnByb3Rv", + "YnVmX3VuaXR0ZXN0X3Byb3RvMi5Gb3JlaWduRW51bToLRk9SRUlHTl9CQVIS", + "VAoTZGVmYXVsdF9pbXBvcnRfZW51bRhTIAEoDjIrLnByb3RvYnVmX3VuaXR0", + "ZXN0X2ltcG9ydF9wcm90bzIuSW1wb3J0RW51bToKSU1QT1JUX0JBUhIlChRk", + "ZWZhdWx0X3N0cmluZ19waWVjZRhUIAEoCToDYWJjQgIIAhIdCgxkZWZhdWx0", + "X2NvcmQYVSABKAk6AzEyM0ICCAESFgoMb25lb2ZfdWludDMyGG8gASgNSAAS", + "VAoUb25lb2ZfbmVzdGVkX21lc3NhZ2UYcCABKAsyNC5wcm90b2J1Zl91bml0", + "dGVzdF9wcm90bzIuVGVzdEFsbFR5cGVzLk5lc3RlZE1lc3NhZ2VIABIWCgxv", + "bmVvZl9zdHJpbmcYcSABKAlIABIVCgtvbmVvZl9ieXRlcxhyIAEoDEgAGhsK", + "DU5lc3RlZE1lc3NhZ2USCgoCYmIYASABKAUaGgoNT3B0aW9uYWxHcm91cBIJ", + "CgFhGBEgASgFGhoKDVJlcGVhdGVkR3JvdXASCQoBYRgvIAEoBSI5CgpOZXN0", + "ZWRFbnVtEgcKA0ZPTxABEgcKA0JBUhACEgcKA0JBWhADEhAKA05FRxD/////", + "//////8BQg0KC29uZW9mX2ZpZWxkItABChJOZXN0ZWRUZXN0QWxsVHlwZXMS", + "OwoFY2hpbGQYASABKAsyLC5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuTmVz", + "dGVkVGVzdEFsbFR5cGVzEjcKB3BheWxvYWQYAiABKAsyJi5wcm90b2J1Zl91", + "bml0dGVzdF9wcm90bzIuVGVzdEFsbFR5cGVzEkQKDnJlcGVhdGVkX2NoaWxk", + "GAMgAygLMiwucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLk5lc3RlZFRlc3RB", + "bGxUeXBlcyJtChRUZXN0RGVwcmVjYXRlZEZpZWxkcxIcChBkZXByZWNhdGVk", + "X2ludDMyGAEgASgFQgIYARInChlkZXByZWNhdGVkX2ludDMyX2luX29uZW9m", + "GAIgASgFQgIYAUgAQg4KDG9uZW9mX2ZpZWxkcyIbChVUZXN0RGVwcmVjYXRl", + "ZE1lc3NhZ2U6AhgBIiYKDkZvcmVpZ25NZXNzYWdlEgkKAWMYASABKAUSCQoB", + "ZBgCIAEoBSIwChJUZXN0UmVzZXJ2ZWRGaWVsZHNKBAgCEANKBAgPEBBKBAgJ", + "EAxSA2JhclIDYmF6Ih0KEVRlc3RBbGxFeHRlbnNpb25zKggIARCAgICAAiIk", + "ChdPcHRpb25hbEdyb3VwX2V4dGVuc2lvbhIJCgFhGBEgASgFIiQKF1JlcGVh", + "dGVkR3JvdXBfZXh0ZW5zaW9uEgkKAWEYLyABKAUitwEKCVRlc3RHcm91cBJI", + "Cg1vcHRpb25hbGdyb3VwGBAgASgKMjEucHJvdG9idWZfdW5pdHRlc3RfcHJv", + "dG8yLlRlc3RHcm91cC5PcHRpb25hbEdyb3VwEkQKFW9wdGlvbmFsX2ZvcmVp", + "Z25fZW51bRgWIAEoDjIlLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5Gb3Jl", + "aWduRW51bRoaCg1PcHRpb25hbEdyb3VwEgkKAWEYESABKAUiHgoSVGVzdEdy", + "b3VwRXh0ZW5zaW9uKggIARCAgICAAiLhAwoTVGVzdE5lc3RlZEV4dGVuc2lv", + "bhokChdPcHRpb25hbEdyb3VwX2V4dGVuc2lvbhIJCgFhGBEgASgFMkAKBHRl", + "c3QSKy5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdEFsbEV4dGVuc2lv", + "bnMY6gcgASgJOgR0ZXN0Mk0KF25lc3RlZF9zdHJpbmdfZXh0ZW5zaW9uEisu", + "cHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RBbGxFeHRlbnNpb25zGOsH", + "IAEoCTKUAQoXb3B0aW9uYWxncm91cF9leHRlbnNpb24SLC5wcm90b2J1Zl91", + "bml0dGVzdF9wcm90bzIuVGVzdEdyb3VwRXh0ZW5zaW9uGBAgASgKMkUucHJv", + "dG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3ROZXN0ZWRFeHRlbnNpb24uT3B0", + "aW9uYWxHcm91cF9leHRlbnNpb24yfAofb3B0aW9uYWxfZm9yZWlnbl9lbnVt", + "X2V4dGVuc2lvbhIsLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0R3Jv", + "dXBFeHRlbnNpb24YFiABKA4yJS5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIu", + "Rm9yZWlnbkVudW0i8QUKDFRlc3RSZXF1aXJlZBIJCgFhGAEgAigFEg4KBmR1", + "bW15MhgCIAEoBRIJCgFiGAMgAigFEg4KBmR1bW15NBgEIAEoBRIOCgZkdW1t", + "eTUYBSABKAUSDgoGZHVtbXk2GAYgASgFEg4KBmR1bW15NxgHIAEoBRIOCgZk", + "dW1teTgYCCABKAUSDgoGZHVtbXk5GAkgASgFEg8KB2R1bW15MTAYCiABKAUS", + "DwoHZHVtbXkxMRgLIAEoBRIPCgdkdW1teTEyGAwgASgFEg8KB2R1bW15MTMY", + "DSABKAUSDwoHZHVtbXkxNBgOIAEoBRIPCgdkdW1teTE1GA8gASgFEg8KB2R1", + "bW15MTYYECABKAUSDwoHZHVtbXkxNxgRIAEoBRIPCgdkdW1teTE4GBIgASgF", + "Eg8KB2R1bW15MTkYEyABKAUSDwoHZHVtbXkyMBgUIAEoBRIPCgdkdW1teTIx", + "GBUgASgFEg8KB2R1bW15MjIYFiABKAUSDwoHZHVtbXkyMxgXIAEoBRIPCgdk", + "dW1teTI0GBggASgFEg8KB2R1bW15MjUYGSABKAUSDwoHZHVtbXkyNhgaIAEo", + "BRIPCgdkdW1teTI3GBsgASgFEg8KB2R1bW15MjgYHCABKAUSDwoHZHVtbXky", + "ORgdIAEoBRIPCgdkdW1teTMwGB4gASgFEg8KB2R1bW15MzEYHyABKAUSDwoH", + "ZHVtbXkzMhggIAEoBRIJCgFjGCEgAigFMmQKBnNpbmdsZRIrLnByb3RvYnVm", + "X3VuaXR0ZXN0X3Byb3RvMi5UZXN0QWxsRXh0ZW5zaW9ucxjoByABKAsyJi5w", + "cm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdFJlcXVpcmVkMmMKBW11bHRp", + "EisucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RBbGxFeHRlbnNpb25z", + "GOkHIAMoCzImLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0UmVxdWly", + "ZWQiqAEKE1Rlc3RSZXF1aXJlZEZvcmVpZ24SQAoQb3B0aW9uYWxfbWVzc2Fn", + "ZRgBIAEoCzImLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0UmVxdWly", + "ZWQSQAoQcmVwZWF0ZWRfbWVzc2FnZRgCIAMoCzImLnByb3RvYnVmX3VuaXR0", + "ZXN0X3Byb3RvMi5UZXN0UmVxdWlyZWQSDQoFZHVtbXkYAyABKAUi2wEKE1Rl", + "c3RSZXF1aXJlZE1lc3NhZ2USQAoQb3B0aW9uYWxfbWVzc2FnZRgBIAEoCzIm", + "LnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0UmVxdWlyZWQSQAoQcmVw", + "ZWF0ZWRfbWVzc2FnZRgCIAMoCzImLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3Rv", + "Mi5UZXN0UmVxdWlyZWQSQAoQcmVxdWlyZWRfbWVzc2FnZRgDIAIoCzImLnBy", + "b3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0UmVxdWlyZWQiYQoRVGVzdEZv", + "cmVpZ25OZXN0ZWQSTAoOZm9yZWlnbl9uZXN0ZWQYASABKAsyNC5wcm90b2J1", + "Zl91bml0dGVzdF9wcm90bzIuVGVzdEFsbFR5cGVzLk5lc3RlZE1lc3NhZ2Ui", + "EgoQVGVzdEVtcHR5TWVzc2FnZSIqCh5UZXN0RW1wdHlNZXNzYWdlV2l0aEV4", + "dGVuc2lvbnMqCAgBEICAgIACIjcKG1Rlc3RNdWx0aXBsZUV4dGVuc2lvblJh", + "bmdlcyoECCoQKyoGCK8gEJQhKgoIgIAEEICAgIACIjQKGFRlc3RSZWFsbHlM", + "YXJnZVRhZ051bWJlchIJCgFhGAEgASgFEg0KAmJiGP///38gASgFIlwKFFRl", + "c3RSZWN1cnNpdmVNZXNzYWdlEjkKAWEYASABKAsyLi5wcm90b2J1Zl91bml0", + "dGVzdF9wcm90bzIuVGVzdFJlY3Vyc2l2ZU1lc3NhZ2USCQoBaRgCIAEoBSKE", + "AwoUVGVzdE11dHVhbFJlY3Vyc2lvbkESOgoCYmIYASABKAsyLi5wcm90b2J1", + "Zl91bml0dGVzdF9wcm90bzIuVGVzdE11dHVhbFJlY3Vyc2lvbkISSQoIc3Vi", + "Z3JvdXAYAiABKAoyNy5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdE11", + "dHVhbFJlY3Vyc2lvbkEuU3ViR3JvdXAaRwoKU3ViTWVzc2FnZRI5CgFiGAEg", + "ASgLMi4ucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RNdXR1YWxSZWN1", + "cnNpb25CGpsBCghTdWJHcm91cBJOCgtzdWJfbWVzc2FnZRgDIAEoCzI5LnBy", + "b3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0TXV0dWFsUmVjdXJzaW9uQS5T", + "dWJNZXNzYWdlEj8KD25vdF9pbl90aGlzX3NjYxgEIAEoCzImLnByb3RvYnVm", + "X3VuaXR0ZXN0X3Byb3RvMi5UZXN0QWxsVHlwZXMiaQoUVGVzdE11dHVhbFJl", + "Y3Vyc2lvbkISOQoBYRgBIAEoCzIuLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3Rv", + "Mi5UZXN0TXV0dWFsUmVjdXJzaW9uQRIWCg5vcHRpb25hbF9pbnQzMhgCIAEo", + "BSLYAQoRVGVzdElzSW5pdGlhbGl6ZWQSSwoLc3ViX21lc3NhZ2UYASABKAsy", + "Ni5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdElzSW5pdGlhbGl6ZWQu", + "U3ViTWVzc2FnZRp2CgpTdWJNZXNzYWdlElEKCHN1Ymdyb3VwGAEgASgKMj8u", + "cHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RJc0luaXRpYWxpemVkLlN1", + "Yk1lc3NhZ2UuU3ViR3JvdXAaFQoIU3ViR3JvdXASCQoBaRgCIAIoBSLBAQoS", + "VGVzdER1cEZpZWxkTnVtYmVyEgkKAWEYASABKAUSPQoDZm9vGAIgASgKMjAu", + "cHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3REdXBGaWVsZE51bWJlci5G", + "b28SPQoDYmFyGAMgASgKMjAucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRl", + "c3REdXBGaWVsZE51bWJlci5CYXIaEAoDRm9vEgkKAWEYASABKAUaEAoDQmFy", + "EgkKAWEYASABKAUiUwoQVGVzdEVhZ2VyTWVzc2FnZRI/CgtzdWJfbWVzc2Fn", + "ZRgBIAEoCzImLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0QWxsVHlw", + "ZXNCAigAIlIKD1Rlc3RMYXp5TWVzc2FnZRI/CgtzdWJfbWVzc2FnZRgBIAEo", + "CzImLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0QWxsVHlwZXNCAigB", + "Io4CChhUZXN0TmVzdGVkTWVzc2FnZUhhc0JpdHMSYQoXb3B0aW9uYWxfbmVz", + "dGVkX21lc3NhZ2UYASABKAsyQC5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIu", + "VGVzdE5lc3RlZE1lc3NhZ2VIYXNCaXRzLk5lc3RlZE1lc3NhZ2UajgEKDU5l", + "c3RlZE1lc3NhZ2USJAocbmVzdGVkbWVzc2FnZV9yZXBlYXRlZF9pbnQzMhgB", + "IAMoBRJXCiVuZXN0ZWRtZXNzYWdlX3JlcGVhdGVkX2ZvcmVpZ25tZXNzYWdl", + "GAIgAygLMigucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLkZvcmVpZ25NZXNz", + "YWdlIoEEChdUZXN0Q2FtZWxDYXNlRmllbGROYW1lcxIWCg5QcmltaXRpdmVG", + "aWVsZBgBIAEoBRITCgtTdHJpbmdGaWVsZBgCIAEoCRI4CglFbnVtRmllbGQY", + "AyABKA4yJS5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuRm9yZWlnbkVudW0S", + "PgoMTWVzc2FnZUZpZWxkGAQgASgLMigucHJvdG9idWZfdW5pdHRlc3RfcHJv", + "dG8yLkZvcmVpZ25NZXNzYWdlEhwKEFN0cmluZ1BpZWNlRmllbGQYBSABKAlC", + "AggCEhUKCUNvcmRGaWVsZBgGIAEoCUICCAESHgoWUmVwZWF0ZWRQcmltaXRp", + "dmVGaWVsZBgHIAMoBRIbChNSZXBlYXRlZFN0cmluZ0ZpZWxkGAggAygJEkAK", + "EVJlcGVhdGVkRW51bUZpZWxkGAkgAygOMiUucHJvdG9idWZfdW5pdHRlc3Rf", + "cHJvdG8yLkZvcmVpZ25FbnVtEkYKFFJlcGVhdGVkTWVzc2FnZUZpZWxkGAog", + "AygLMigucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLkZvcmVpZ25NZXNzYWdl", + "EiQKGFJlcGVhdGVkU3RyaW5nUGllY2VGaWVsZBgLIAMoCUICCAISHQoRUmVw", + "ZWF0ZWRDb3JkRmllbGQYDCADKAlCAggBItwBChJUZXN0RmllbGRPcmRlcmlu", + "Z3MSEQoJbXlfc3RyaW5nGAsgASgJEg4KBm15X2ludBgBIAEoAxIQCghteV9m", + "bG9hdBhlIAEoAhJcChdvcHRpb25hbF9uZXN0ZWRfbWVzc2FnZRjIASABKAsy", + "Oi5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdEZpZWxkT3JkZXJpbmdz", + "Lk5lc3RlZE1lc3NhZ2UaJwoNTmVzdGVkTWVzc2FnZRIKCgJvbxgCIAEoAxIK", + "CgJiYhgBIAEoBSoECAIQCyoECAwQZSKqAQoXVGVzdEV4dGVuc2lvbk9yZGVy", + "aW5nczESEQoJbXlfc3RyaW5nGAEgASgJMnwKE3Rlc3RfZXh0X29yZGVyaW5n", + "czESLC5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdEZpZWxkT3JkZXJp", + "bmdzGA0gASgLMjEucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RFeHRl", + "bnNpb25PcmRlcmluZ3MxIvACChdUZXN0RXh0ZW5zaW9uT3JkZXJpbmdzMhIR", + "CglteV9zdHJpbmcYASABKAkawwEKF1Rlc3RFeHRlbnNpb25PcmRlcmluZ3Mz", + "EhEKCW15X3N0cmluZxgBIAEoCTKUAQoTdGVzdF9leHRfb3JkZXJpbmdzMxIs", + "LnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0RmllbGRPcmRlcmluZ3MY", + "DiABKAsySS5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdEV4dGVuc2lv", + "bk9yZGVyaW5nczIuVGVzdEV4dGVuc2lvbk9yZGVyaW5nczMyfAoTdGVzdF9l", + "eHRfb3JkZXJpbmdzMhIsLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0", + "RmllbGRPcmRlcmluZ3MYDCABKAsyMS5wcm90b2J1Zl91bml0dGVzdF9wcm90", + "bzIuVGVzdEV4dGVuc2lvbk9yZGVyaW5nczIitgcKGFRlc3RFeHRyZW1lRGVm", + "YXVsdFZhbHVlcxI/Cg1lc2NhcGVkX2J5dGVzGAEgASgMOihcMDAwXDAwMVww", + "MDdcMDEwXDAxNFxuXHJcdFwwMTNcXFwnXCJcMzc2EiAKDGxhcmdlX3VpbnQz", + "MhgCIAEoDToKNDI5NDk2NzI5NRIqCgxsYXJnZV91aW50NjQYAyABKAQ6FDE4", + "NDQ2NzQ0MDczNzA5NTUxNjE1EiAKC3NtYWxsX2ludDMyGAQgASgFOgstMjE0", + "NzQ4MzY0NxIpCgtzbWFsbF9pbnQ2NBgFIAEoAzoULTkyMjMzNzIwMzY4NTQ3", + "NzU4MDcSJwoScmVhbGx5X3NtYWxsX2ludDMyGBUgASgFOgstMjE0NzQ4MzY0", + "OBIwChJyZWFsbHlfc21hbGxfaW50NjQYFiABKAM6FC05MjIzMzcyMDM2ODU0", + "Nzc1ODA4EhgKC3V0Zjhfc3RyaW5nGAYgASgJOgPhiLQSFQoKemVyb19mbG9h", + "dBgHIAEoAjoBMBIUCglvbmVfZmxvYXQYCCABKAI6ATESGAoLc21hbGxfZmxv", + "YXQYCSABKAI6AzEuNRIeChJuZWdhdGl2ZV9vbmVfZmxvYXQYCiABKAI6Ai0x", + "EhwKDm5lZ2F0aXZlX2Zsb2F0GAsgASgCOgQtMS41EhoKC2xhcmdlX2Zsb2F0", + "GAwgASgCOgUyZSswOBIkChRzbWFsbF9uZWdhdGl2ZV9mbG9hdBgNIAEoAjoG", + "LThlLTI4EhcKCmluZl9kb3VibGUYDiABKAE6A2luZhIcCg5uZWdfaW5mX2Rv", + "dWJsZRgPIAEoAToELWluZhIXCgpuYW5fZG91YmxlGBAgASgBOgNuYW4SFgoJ", + "aW5mX2Zsb2F0GBEgASgCOgNpbmYSGwoNbmVnX2luZl9mbG9hdBgSIAEoAjoE", + "LWluZhIWCgluYW5fZmxvYXQYEyABKAI6A25hbhIrCgxjcHBfdHJpZ3JhcGgY", + "FCABKAk6FT8gPyA/PyA/PyA/Pz8gPz8vID8/LRIgChBzdHJpbmdfd2l0aF96", + "ZXJvGBcgASgJOgZoZWwAbG8SIgoPYnl0ZXNfd2l0aF96ZXJvGBggASgMOgl3", + "b3JcMDAwbGQSKAoWc3RyaW5nX3BpZWNlX3dpdGhfemVybxgZIAEoCToEYWIA", + "Y0ICCAISIAoOY29yZF93aXRoX3plcm8YGiABKAk6BDEyADNCAggBEiYKEnJl", + "cGxhY2VtZW50X3N0cmluZxgbIAEoCToKJHt1bmtub3dufSJSChFTcGFyc2VF", + "bnVtTWVzc2FnZRI9CgtzcGFyc2VfZW51bRgBIAEoDjIoLnByb3RvYnVmX3Vu", + "aXR0ZXN0X3Byb3RvMi5UZXN0U3BhcnNlRW51bSIZCglPbmVTdHJpbmcSDAoE", + "ZGF0YRgBIAEoCSIaCgpNb3JlU3RyaW5nEgwKBGRhdGEYASADKAkiGAoIT25l", + "Qnl0ZXMSDAoEZGF0YRgBIAEoDCIZCglNb3JlQnl0ZXMSDAoEZGF0YRgBIAMo", + "DCIcCgxJbnQzMk1lc3NhZ2USDAoEZGF0YRgBIAEoBSIdCg1VaW50MzJNZXNz", + "YWdlEgwKBGRhdGEYASABKA0iHAoMSW50NjRNZXNzYWdlEgwKBGRhdGEYASAB", + "KAMiHQoNVWludDY0TWVzc2FnZRIMCgRkYXRhGAEgASgEIhsKC0Jvb2xNZXNz", + "YWdlEgwKBGRhdGEYASABKAgi3gEKCVRlc3RPbmVvZhIRCgdmb29faW50GAEg", + "ASgFSAASFAoKZm9vX3N0cmluZxgCIAEoCUgAEj0KC2Zvb19tZXNzYWdlGAMg", + "ASgLMiYucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RBbGxUeXBlc0gA", + "EkAKCGZvb2dyb3VwGAQgASgKMiwucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8y", + "LlRlc3RPbmVvZi5Gb29Hcm91cEgAGiAKCEZvb0dyb3VwEgkKAWEYBSABKAUS", + "CQoBYhgGIAEoCUIFCgNmb28i9QEKHFRlc3RPbmVvZkJhY2t3YXJkc0NvbXBh", + "dGlibGUSDwoHZm9vX2ludBgBIAEoBRISCgpmb29fc3RyaW5nGAIgASgJEjsK", + "C2Zvb19tZXNzYWdlGAMgASgLMiYucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8y", + "LlRlc3RBbGxUeXBlcxJRCghmb29ncm91cBgEIAEoCjI/LnByb3RvYnVmX3Vu", + "aXR0ZXN0X3Byb3RvMi5UZXN0T25lb2ZCYWNrd2FyZHNDb21wYXRpYmxlLkZv", + "b0dyb3VwGiAKCEZvb0dyb3VwEgkKAWEYBSABKAUSCQoBYhgGIAEoCSLBBgoK", + "VGVzdE9uZW9mMhIRCgdmb29faW50GAEgASgFSAASFAoKZm9vX3N0cmluZxgC", + "IAEoCUgAEhYKCGZvb19jb3JkGAMgASgJQgIIAUgAEh4KEGZvb19zdHJpbmdf", + "cGllY2UYBCABKAlCAggCSAASEwoJZm9vX2J5dGVzGAUgASgMSAASQwoIZm9v", + "X2VudW0YBiABKA4yLy5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdE9u", + "ZW9mMi5OZXN0ZWRFbnVtSAASSQoLZm9vX21lc3NhZ2UYByABKAsyMi5wcm90", + "b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdE9uZW9mMi5OZXN0ZWRNZXNzYWdl", + "SAASQQoIZm9vZ3JvdXAYCCABKAoyLS5wcm90b2J1Zl91bml0dGVzdF9wcm90", + "bzIuVGVzdE9uZW9mMi5Gb29Hcm91cEgAElIKEGZvb19sYXp5X21lc3NhZ2UY", + "CyABKAsyMi5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdE9uZW9mMi5O", + "ZXN0ZWRNZXNzYWdlQgIoAUgAEhQKB2Jhcl9pbnQYDCABKAU6ATVIARIcCgpi", + "YXJfc3RyaW5nGA0gASgJOgZTVFJJTkdIARIcCghiYXJfY29yZBgOIAEoCToE", + "Q09SREICCAFIARImChBiYXJfc3RyaW5nX3BpZWNlGA8gASgJOgZTUElFQ0VC", + "AggCSAESGgoJYmFyX2J5dGVzGBAgASgMOgVCWVRFU0gBEkgKCGJhcl9lbnVt", + "GBEgASgOMi8ucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RPbmVvZjIu", + "TmVzdGVkRW51bToDQkFSSAESDwoHYmF6X2ludBgSIAEoBRIXCgpiYXpfc3Ry", + "aW5nGBMgASgJOgNCQVoaIAoIRm9vR3JvdXASCQoBYRgJIAEoBRIJCgFiGAog", + "ASgJGjMKDU5lc3RlZE1lc3NhZ2USDwoHcXV4X2ludBgBIAEoAxIRCgljb3Jn", + "ZV9pbnQYAiADKAUiJwoKTmVzdGVkRW51bRIHCgNGT08QARIHCgNCQVIQAhIH", + "CgNCQVoQA0IFCgNmb29CBQoDYmFyIr8BChFUZXN0UmVxdWlyZWRPbmVvZhIR", + "Cgdmb29faW50GAEgASgFSAASFAoKZm9vX3N0cmluZxgCIAEoCUgAElAKC2Zv", + "b19tZXNzYWdlGAMgASgLMjkucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRl", + "c3RSZXF1aXJlZE9uZW9mLk5lc3RlZE1lc3NhZ2VIABooCg1OZXN0ZWRNZXNz", + "YWdlEhcKD3JlcXVpcmVkX2RvdWJsZRgBIAIoAUIFCgNmb28i4AEKD1Rlc3RS", + "ZXF1aXJlZE1hcBI/CgNmb28YASADKAsyMi5wcm90b2J1Zl91bml0dGVzdF9w", + "cm90bzIuVGVzdFJlcXVpcmVkTWFwLkZvb0VudHJ5GmMKCEZvb0VudHJ5EgsK", + "A2tleRgBIAEoBRJGCgV2YWx1ZRgCIAEoCzI3LnByb3RvYnVmX3VuaXR0ZXN0", + "X3Byb3RvMi5UZXN0UmVxdWlyZWRNYXAuTmVzdGVkTWVzc2FnZToCOAEaJwoN", + "TmVzdGVkTWVzc2FnZRIWCg5yZXF1aXJlZF9pbnQzMhgBIAIoBSKxAwoPVGVz", + "dFBhY2tlZFR5cGVzEhgKDHBhY2tlZF9pbnQzMhhaIAMoBUICEAESGAoMcGFj", + "a2VkX2ludDY0GFsgAygDQgIQARIZCg1wYWNrZWRfdWludDMyGFwgAygNQgIQ", + "ARIZCg1wYWNrZWRfdWludDY0GF0gAygEQgIQARIZCg1wYWNrZWRfc2ludDMy", + "GF4gAygRQgIQARIZCg1wYWNrZWRfc2ludDY0GF8gAygSQgIQARIaCg5wYWNr", + "ZWRfZml4ZWQzMhhgIAMoB0ICEAESGgoOcGFja2VkX2ZpeGVkNjQYYSADKAZC", + "AhABEhsKD3BhY2tlZF9zZml4ZWQzMhhiIAMoD0ICEAESGwoPcGFja2VkX3Nm", + "aXhlZDY0GGMgAygQQgIQARIYCgxwYWNrZWRfZmxvYXQYZCADKAJCAhABEhkK", + "DXBhY2tlZF9kb3VibGUYZSADKAFCAhABEhcKC3BhY2tlZF9ib29sGGYgAygI", + "QgIQARI+CgtwYWNrZWRfZW51bRhnIAMoDjIlLnByb3RvYnVmX3VuaXR0ZXN0", + "X3Byb3RvMi5Gb3JlaWduRW51bUICEAEizwMKEVRlc3RVbnBhY2tlZFR5cGVz", + "EhoKDnVucGFja2VkX2ludDMyGFogAygFQgIQABIaCg51bnBhY2tlZF9pbnQ2", + "NBhbIAMoA0ICEAASGwoPdW5wYWNrZWRfdWludDMyGFwgAygNQgIQABIbCg91", + "bnBhY2tlZF91aW50NjQYXSADKARCAhAAEhsKD3VucGFja2VkX3NpbnQzMhhe", + "IAMoEUICEAASGwoPdW5wYWNrZWRfc2ludDY0GF8gAygSQgIQABIcChB1bnBh", + "Y2tlZF9maXhlZDMyGGAgAygHQgIQABIcChB1bnBhY2tlZF9maXhlZDY0GGEg", + "AygGQgIQABIdChF1bnBhY2tlZF9zZml4ZWQzMhhiIAMoD0ICEAASHQoRdW5w", + "YWNrZWRfc2ZpeGVkNjQYYyADKBBCAhAAEhoKDnVucGFja2VkX2Zsb2F0GGQg", + "AygCQgIQABIbCg91bnBhY2tlZF9kb3VibGUYZSADKAFCAhAAEhkKDXVucGFj", + "a2VkX2Jvb2wYZiADKAhCAhAAEkAKDXVucGFja2VkX2VudW0YZyADKA4yJS5w", + "cm90b2J1Zl91bml0dGVzdF9wcm90bzIuRm9yZWlnbkVudW1CAhAAIiAKFFRl", + "c3RQYWNrZWRFeHRlbnNpb25zKggIARCAgICAAiIiChZUZXN0VW5wYWNrZWRF", + "eHRlbnNpb25zKggIARCAgICAAiK1BAoVVGVzdER5bmFtaWNFeHRlbnNpb25z", + "EhkKEHNjYWxhcl9leHRlbnNpb24Y0A8gASgHEj4KDmVudW1fZXh0ZW5zaW9u", + "GNEPIAEoDjIlLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5Gb3JlaWduRW51", + "bRJgChZkeW5hbWljX2VudW1fZXh0ZW5zaW9uGNIPIAEoDjI/LnByb3RvYnVm", + "X3VuaXR0ZXN0X3Byb3RvMi5UZXN0RHluYW1pY0V4dGVuc2lvbnMuRHluYW1p", + "Y0VudW1UeXBlEkQKEW1lc3NhZ2VfZXh0ZW5zaW9uGNMPIAEoCzIoLnByb3Rv", + "YnVmX3VuaXR0ZXN0X3Byb3RvMi5Gb3JlaWduTWVzc2FnZRJmChlkeW5hbWlj", + "X21lc3NhZ2VfZXh0ZW5zaW9uGNQPIAEoCzJCLnByb3RvYnVmX3VuaXR0ZXN0", + "X3Byb3RvMi5UZXN0RHluYW1pY0V4dGVuc2lvbnMuRHluYW1pY01lc3NhZ2VU", + "eXBlEhsKEnJlcGVhdGVkX2V4dGVuc2lvbhjVDyADKAkSHQoQcGFja2VkX2V4", + "dGVuc2lvbhjWDyADKBFCAhABGiwKEkR5bmFtaWNNZXNzYWdlVHlwZRIWCg1k", + "eW5hbWljX2ZpZWxkGLQQIAEoBSJHCg9EeW5hbWljRW51bVR5cGUSEAoLRFlO", + "QU1JQ19GT08QmBESEAoLRFlOQU1JQ19CQVIQmRESEAoLRFlOQU1JQ19CQVoQ", + "mhEiwAEKI1Rlc3RSZXBlYXRlZFNjYWxhckRpZmZlcmVudFRhZ1NpemVzEhgK", + "EHJlcGVhdGVkX2ZpeGVkMzIYDCADKAcSFgoOcmVwZWF0ZWRfaW50MzIYDSAD", + "KAUSGQoQcmVwZWF0ZWRfZml4ZWQ2NBj+DyADKAYSFwoOcmVwZWF0ZWRfaW50", + "NjQY/w8gAygDEhgKDnJlcGVhdGVkX2Zsb2F0GP7/DyADKAISGQoPcmVwZWF0", + "ZWRfdWludDY0GP//DyADKAQigwsKEFRlc3RQYXJzaW5nTWVyZ2USQgoScmVx", + "dWlyZWRfYWxsX3R5cGVzGAEgAigLMiYucHJvdG9idWZfdW5pdHRlc3RfcHJv", + "dG8yLlRlc3RBbGxUeXBlcxJCChJvcHRpb25hbF9hbGxfdHlwZXMYAiABKAsy", + "Ji5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdEFsbFR5cGVzEkIKEnJl", + "cGVhdGVkX2FsbF90eXBlcxgDIAMoCzImLnByb3RvYnVmX3VuaXR0ZXN0X3By", + "b3RvMi5UZXN0QWxsVHlwZXMSTwoNb3B0aW9uYWxncm91cBgKIAEoCjI4LnBy", + "b3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0UGFyc2luZ01lcmdlLk9wdGlv", + "bmFsR3JvdXASTwoNcmVwZWF0ZWRncm91cBgUIAMoCjI4LnByb3RvYnVmX3Vu", + "aXR0ZXN0X3Byb3RvMi5UZXN0UGFyc2luZ01lcmdlLlJlcGVhdGVkR3JvdXAa", + "6QQKF1JlcGVhdGVkRmllbGRzR2VuZXJhdG9yEjYKBmZpZWxkMRgBIAMoCzIm", + "LnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0QWxsVHlwZXMSNgoGZmll", + "bGQyGAIgAygLMiYucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RBbGxU", + "eXBlcxI2CgZmaWVsZDMYAyADKAsyJi5wcm90b2J1Zl91bml0dGVzdF9wcm90", + "bzIuVGVzdEFsbFR5cGVzElkKBmdyb3VwMRgKIAMoCjJJLnByb3RvYnVmX3Vu", + "aXR0ZXN0X3Byb3RvMi5UZXN0UGFyc2luZ01lcmdlLlJlcGVhdGVkRmllbGRz", + "R2VuZXJhdG9yLkdyb3VwMRJZCgZncm91cDIYFCADKAoySS5wcm90b2J1Zl91", + "bml0dGVzdF9wcm90bzIuVGVzdFBhcnNpbmdNZXJnZS5SZXBlYXRlZEZpZWxk", + "c0dlbmVyYXRvci5Hcm91cDISNQoEZXh0MRjoByADKAsyJi5wcm90b2J1Zl91", + "bml0dGVzdF9wcm90bzIuVGVzdEFsbFR5cGVzEjUKBGV4dDIY6QcgAygLMiYu", + "cHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RBbGxUeXBlcxpACgZHcm91", + "cDESNgoGZmllbGQxGAsgASgLMiYucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8y", + "LlRlc3RBbGxUeXBlcxpACgZHcm91cDISNgoGZmllbGQxGBUgASgLMiYucHJv", + "dG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RBbGxUeXBlcxpZCg1PcHRpb25h", + "bEdyb3VwEkgKGG9wdGlvbmFsX2dyb3VwX2FsbF90eXBlcxgLIAEoCzImLnBy", + "b3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0QWxsVHlwZXMaWQoNUmVwZWF0", + "ZWRHcm91cBJIChhyZXBlYXRlZF9ncm91cF9hbGxfdHlwZXMYFSABKAsyJi5w", + "cm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdEFsbFR5cGVzKgkI6AcQgICA", + "gAIyaQoMb3B0aW9uYWxfZXh0EioucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8y", + "LlRlc3RQYXJzaW5nTWVyZ2UY6AcgASgLMiYucHJvdG9idWZfdW5pdHRlc3Rf", + "cHJvdG8yLlRlc3RBbGxUeXBlczJpCgxyZXBlYXRlZF9leHQSKi5wcm90b2J1", + "Zl91bml0dGVzdF9wcm90bzIuVGVzdFBhcnNpbmdNZXJnZRjpByADKAsyJi5w", + "cm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdEFsbFR5cGVzIkQKG1Rlc3RD", + "b21tZW50SW5qZWN0aW9uTWVzc2FnZRIlCgFhGAEgASgJOhoqLyA8LSBOZWl0", + "aGVyIHNob3VsZCB0aGlzLiIMCgpGb29SZXF1ZXN0Ig0KC0Zvb1Jlc3BvbnNl", + "IhIKEEZvb0NsaWVudE1lc3NhZ2UiEgoQRm9vU2VydmVyTWVzc2FnZSIMCgpC", + "YXJSZXF1ZXN0Ig0KC0JhclJlc3BvbnNlIpIBCgxUZXN0SnNvbk5hbWUSEwoL", + "ZmllbGRfbmFtZTEYASABKAUSEgoKZmllbGROYW1lMhgCIAEoBRISCgpGaWVs", + "ZE5hbWUzGAMgASgFEhQKDF9maWVsZF9uYW1lNBgEIAEoBRITCgtGSUVMRF9O", + "QU1FNRgFIAEoBRIaCgtmaWVsZF9uYW1lNhgGIAEoBVIFQHR5cGUioAYKFFRl", + "c3RIdWdlRmllbGROdW1iZXJzEhoKDm9wdGlvbmFsX2ludDMyGPD4//8BIAEo", + "BRIUCghmaXhlZF8zMhjx+P//ASABKAUSHgoOcmVwZWF0ZWRfaW50MzIY8vj/", + "/wEgAygFQgIQABIcCgxwYWNrZWRfaW50MzIY8/j//wEgAygFQgIQARJACg1v", + "cHRpb25hbF9lbnVtGPT4//8BIAEoDjIlLnByb3RvYnVmX3VuaXR0ZXN0X3By", + "b3RvMi5Gb3JlaWduRW51bRIbCg9vcHRpb25hbF9zdHJpbmcY9fj//wEgASgJ", + "EhoKDm9wdGlvbmFsX2J5dGVzGPb4//8BIAEoDBJGChBvcHRpb25hbF9tZXNz", + "YWdlGPf4//8BIAEoCzIoLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5Gb3Jl", + "aWduTWVzc2FnZRJXCg1vcHRpb25hbGdyb3VwGPj4//8BIAEoCjI8LnByb3Rv", + "YnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0SHVnZUZpZWxkTnVtYmVycy5PcHRp", + "b25hbEdyb3VwEmIKEXN0cmluZ19zdHJpbmdfbWFwGPr4//8BIAMoCzJDLnBy", + "b3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0SHVnZUZpZWxkTnVtYmVycy5T", + "dHJpbmdTdHJpbmdNYXBFbnRyeRIaCgxvbmVvZl91aW50MzIY+/j//wEgASgN", + "SAASSgoUb25lb2ZfdGVzdF9hbGxfdHlwZXMY/Pj//wEgASgLMiYucHJvdG9i", + "dWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RBbGxUeXBlc0gAEhoKDG9uZW9mX3N0", + "cmluZxj9+P//ASABKAlIABIZCgtvbmVvZl9ieXRlcxj++P//ASABKAxIABok", + "Cg1PcHRpb25hbEdyb3VwEhMKB2dyb3VwX2EY+fj//wEgASgFGjYKFFN0cmlu", + "Z1N0cmluZ01hcEVudHJ5EgsKA2tleRgBIAEoCRINCgV2YWx1ZRgCIAEoCToC", + "OAEqDAjgqv//ARDw+P//AUINCgtvbmVvZl9maWVsZCKxAQoYVGVzdEV4dGVu", + "c2lvbkluc2lkZVRhYmxlEg4KBmZpZWxkMRgBIAEoBRIOCgZmaWVsZDIYAiAB", + "KAUSDgoGZmllbGQzGAMgASgFEg4KBmZpZWxkNBgEIAEoBRIOCgZmaWVsZDYY", + "BiABKAUSDgoGZmllbGQ3GAcgASgFEg4KBmZpZWxkOBgIIAEoBRIOCgZmaWVs", + "ZDkYCSABKAUSDwoHZmllbGQxMBgKIAEoBSoECAUQBipACgtGb3JlaWduRW51", + "bRIPCgtGT1JFSUdOX0ZPTxAEEg8KC0ZPUkVJR05fQkFSEAUSDwoLRk9SRUlH", + "Tl9CQVoQBipLChRUZXN0RW51bVdpdGhEdXBWYWx1ZRIICgRGT08xEAESCAoE", + "QkFSMRACEgcKA0JBWhADEggKBEZPTzIQARIICgRCQVIyEAIaAhABKokBCg5U", + "ZXN0U3BhcnNlRW51bRIMCghTUEFSU0VfQRB7Eg4KCFNQQVJTRV9CEKbnAxIP", + "CghTUEFSU0VfQxCysYAGEhUKCFNQQVJTRV9EEPH//////////wESFQoIU1BB", + "UlNFX0UQtN78////////ARIMCghTUEFSU0VfRhAAEgwKCFNQQVJTRV9HEAIq", + "iw8KDVZlcnlMYXJnZUVudW0SFgoSRU5VTV9MQUJFTF9ERUZBVUxUEAASEAoM", + "RU5VTV9MQUJFTF8xEAESEAoMRU5VTV9MQUJFTF8yEAISEAoMRU5VTV9MQUJF", + "TF8zEAMSEAoMRU5VTV9MQUJFTF80EAQSEAoMRU5VTV9MQUJFTF81EAUSEAoM", + "RU5VTV9MQUJFTF82EAYSEAoMRU5VTV9MQUJFTF83EAcSEAoMRU5VTV9MQUJF", + "TF84EAgSEAoMRU5VTV9MQUJFTF85EAkSEQoNRU5VTV9MQUJFTF8xMBAKEhEK", + "DUVOVU1fTEFCRUxfMTEQCxIRCg1FTlVNX0xBQkVMXzEyEAwSEQoNRU5VTV9M", + "QUJFTF8xMxANEhEKDUVOVU1fTEFCRUxfMTQQDhIRCg1FTlVNX0xBQkVMXzE1", + "EA8SEQoNRU5VTV9MQUJFTF8xNhAQEhEKDUVOVU1fTEFCRUxfMTcQERIRCg1F", + "TlVNX0xBQkVMXzE4EBISEQoNRU5VTV9MQUJFTF8xORATEhEKDUVOVU1fTEFC", + "RUxfMjAQFBIRCg1FTlVNX0xBQkVMXzIxEBUSEQoNRU5VTV9MQUJFTF8yMhAW", + "EhEKDUVOVU1fTEFCRUxfMjMQFxIRCg1FTlVNX0xBQkVMXzI0EBgSEQoNRU5V", + "TV9MQUJFTF8yNRAZEhEKDUVOVU1fTEFCRUxfMjYQGhIRCg1FTlVNX0xBQkVM", + "XzI3EBsSEQoNRU5VTV9MQUJFTF8yOBAcEhEKDUVOVU1fTEFCRUxfMjkQHRIR", + "Cg1FTlVNX0xBQkVMXzMwEB4SEQoNRU5VTV9MQUJFTF8zMRAfEhEKDUVOVU1f", + "TEFCRUxfMzIQIBIRCg1FTlVNX0xBQkVMXzMzECESEQoNRU5VTV9MQUJFTF8z", + "NBAiEhEKDUVOVU1fTEFCRUxfMzUQIxIRCg1FTlVNX0xBQkVMXzM2ECQSEQoN", + "RU5VTV9MQUJFTF8zNxAlEhEKDUVOVU1fTEFCRUxfMzgQJhIRCg1FTlVNX0xB", + "QkVMXzM5ECcSEQoNRU5VTV9MQUJFTF80MBAoEhEKDUVOVU1fTEFCRUxfNDEQ", + "KRIRCg1FTlVNX0xBQkVMXzQyECoSEQoNRU5VTV9MQUJFTF80MxArEhEKDUVO", + "VU1fTEFCRUxfNDQQLBIRCg1FTlVNX0xBQkVMXzQ1EC0SEQoNRU5VTV9MQUJF", + "TF80NhAuEhEKDUVOVU1fTEFCRUxfNDcQLxIRCg1FTlVNX0xBQkVMXzQ4EDAS", + "EQoNRU5VTV9MQUJFTF80ORAxEhEKDUVOVU1fTEFCRUxfNTAQMhIRCg1FTlVN", + "X0xBQkVMXzUxEDMSEQoNRU5VTV9MQUJFTF81MhA0EhEKDUVOVU1fTEFCRUxf", + "NTMQNRIRCg1FTlVNX0xBQkVMXzU0EDYSEQoNRU5VTV9MQUJFTF81NRA3EhEK", + "DUVOVU1fTEFCRUxfNTYQOBIRCg1FTlVNX0xBQkVMXzU3EDkSEQoNRU5VTV9M", + "QUJFTF81OBA6EhEKDUVOVU1fTEFCRUxfNTkQOxIRCg1FTlVNX0xBQkVMXzYw", + "EDwSEQoNRU5VTV9MQUJFTF82MRA9EhEKDUVOVU1fTEFCRUxfNjIQPhIRCg1F", + "TlVNX0xBQkVMXzYzED8SEQoNRU5VTV9MQUJFTF82NBBAEhEKDUVOVU1fTEFC", + "RUxfNjUQQRIRCg1FTlVNX0xBQkVMXzY2EEISEQoNRU5VTV9MQUJFTF82NxBD", + "EhEKDUVOVU1fTEFCRUxfNjgQRBIRCg1FTlVNX0xBQkVMXzY5EEUSEQoNRU5V", + "TV9MQUJFTF83MBBGEhEKDUVOVU1fTEFCRUxfNzEQRxIRCg1FTlVNX0xBQkVM", + "XzcyEEgSEQoNRU5VTV9MQUJFTF83MxBJEhEKDUVOVU1fTEFCRUxfNzQQShIR", + "Cg1FTlVNX0xBQkVMXzc1EEsSEQoNRU5VTV9MQUJFTF83NhBMEhEKDUVOVU1f", + "TEFCRUxfNzcQTRIRCg1FTlVNX0xBQkVMXzc4EE4SEQoNRU5VTV9MQUJFTF83", + "ORBPEhEKDUVOVU1fTEFCRUxfODAQUBIRCg1FTlVNX0xBQkVMXzgxEFESEQoN", + "RU5VTV9MQUJFTF84MhBSEhEKDUVOVU1fTEFCRUxfODMQUxIRCg1FTlVNX0xB", + "QkVMXzg0EFQSEQoNRU5VTV9MQUJFTF84NRBVEhEKDUVOVU1fTEFCRUxfODYQ", + "VhIRCg1FTlVNX0xBQkVMXzg3EFcSEQoNRU5VTV9MQUJFTF84OBBYEhEKDUVO", + "VU1fTEFCRUxfODkQWRIRCg1FTlVNX0xBQkVMXzkwEFoSEQoNRU5VTV9MQUJF", + "TF85MRBbEhEKDUVOVU1fTEFCRUxfOTIQXBIRCg1FTlVNX0xBQkVMXzkzEF0S", + "EQoNRU5VTV9MQUJFTF85NBBeEhEKDUVOVU1fTEFCRUxfOTUQXxIRCg1FTlVN", + "X0xBQkVMXzk2EGASEQoNRU5VTV9MQUJFTF85NxBhEhEKDUVOVU1fTEFCRUxf", + "OTgQYhIRCg1FTlVNX0xBQkVMXzk5EGMSEgoORU5VTV9MQUJFTF8xMDAQZDK1", + "AQoLVGVzdFNlcnZpY2USUgoDRm9vEiQucHJvdG9idWZfdW5pdHRlc3RfcHJv", + "dG8yLkZvb1JlcXVlc3QaJS5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuRm9v", + "UmVzcG9uc2USUgoDQmFyEiQucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLkJh", + "clJlcXVlc3QaJS5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuQmFyUmVzcG9u", + "c2U6TQoYb3B0aW9uYWxfaW50MzJfZXh0ZW5zaW9uEisucHJvdG9idWZfdW5p", + "dHRlc3RfcHJvdG8yLlRlc3RBbGxFeHRlbnNpb25zGAEgASgFOk0KGG9wdGlv", + "bmFsX2ludDY0X2V4dGVuc2lvbhIrLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3Rv", + "Mi5UZXN0QWxsRXh0ZW5zaW9ucxgCIAEoAzpOChlvcHRpb25hbF91aW50MzJf", + "ZXh0ZW5zaW9uEisucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RBbGxF", + "eHRlbnNpb25zGAMgASgNOk4KGW9wdGlvbmFsX3VpbnQ2NF9leHRlbnNpb24S", + "Ky5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdEFsbEV4dGVuc2lvbnMY", + "BCABKAQ6TgoZb3B0aW9uYWxfc2ludDMyX2V4dGVuc2lvbhIrLnByb3RvYnVm", + "X3VuaXR0ZXN0X3Byb3RvMi5UZXN0QWxsRXh0ZW5zaW9ucxgFIAEoETpOChlv", + "cHRpb25hbF9zaW50NjRfZXh0ZW5zaW9uEisucHJvdG9idWZfdW5pdHRlc3Rf", + "cHJvdG8yLlRlc3RBbGxFeHRlbnNpb25zGAYgASgSOk8KGm9wdGlvbmFsX2Zp", + "eGVkMzJfZXh0ZW5zaW9uEisucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRl", + "c3RBbGxFeHRlbnNpb25zGAcgASgHOk8KGm9wdGlvbmFsX2ZpeGVkNjRfZXh0", + "ZW5zaW9uEisucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RBbGxFeHRl", + "bnNpb25zGAggASgGOlAKG29wdGlvbmFsX3NmaXhlZDMyX2V4dGVuc2lvbhIr", + "LnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0QWxsRXh0ZW5zaW9ucxgJ", + "IAEoDzpQChtvcHRpb25hbF9zZml4ZWQ2NF9leHRlbnNpb24SKy5wcm90b2J1", + "Zl91bml0dGVzdF9wcm90bzIuVGVzdEFsbEV4dGVuc2lvbnMYCiABKBA6TQoY", + "b3B0aW9uYWxfZmxvYXRfZXh0ZW5zaW9uEisucHJvdG9idWZfdW5pdHRlc3Rf", + "cHJvdG8yLlRlc3RBbGxFeHRlbnNpb25zGAsgASgCOk4KGW9wdGlvbmFsX2Rv", + "dWJsZV9leHRlbnNpb24SKy5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVz", + "dEFsbEV4dGVuc2lvbnMYDCABKAE6TAoXb3B0aW9uYWxfYm9vbF9leHRlbnNp", + "b24SKy5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdEFsbEV4dGVuc2lv", + "bnMYDSABKAg6TgoZb3B0aW9uYWxfc3RyaW5nX2V4dGVuc2lvbhIrLnByb3Rv", + "YnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0QWxsRXh0ZW5zaW9ucxgOIAEoCTpN", + "ChhvcHRpb25hbF9ieXRlc19leHRlbnNpb24SKy5wcm90b2J1Zl91bml0dGVz", + "dF9wcm90bzIuVGVzdEFsbEV4dGVuc2lvbnMYDyABKAw6fwoXb3B0aW9uYWxn", + "cm91cF9leHRlbnNpb24SKy5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVz", + "dEFsbEV4dGVuc2lvbnMYECABKAoyMS5wcm90b2J1Zl91bml0dGVzdF9wcm90", + "bzIuT3B0aW9uYWxHcm91cF9leHRlbnNpb246jAEKIW9wdGlvbmFsX25lc3Rl", + "ZF9tZXNzYWdlX2V4dGVuc2lvbhIrLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3Rv", + "Mi5UZXN0QWxsRXh0ZW5zaW9ucxgSIAEoCzI0LnByb3RvYnVmX3VuaXR0ZXN0", + "X3Byb3RvMi5UZXN0QWxsVHlwZXMuTmVzdGVkTWVzc2FnZTqBAQoib3B0aW9u", + "YWxfZm9yZWlnbl9tZXNzYWdlX2V4dGVuc2lvbhIrLnByb3RvYnVmX3VuaXR0", + "ZXN0X3Byb3RvMi5UZXN0QWxsRXh0ZW5zaW9ucxgTIAEoCzIoLnByb3RvYnVm", + "X3VuaXR0ZXN0X3Byb3RvMi5Gb3JlaWduTWVzc2FnZTqGAQohb3B0aW9uYWxf", + "aW1wb3J0X21lc3NhZ2VfZXh0ZW5zaW9uEisucHJvdG9idWZfdW5pdHRlc3Rf", + "cHJvdG8yLlRlc3RBbGxFeHRlbnNpb25zGBQgASgLMi4ucHJvdG9idWZfdW5p", + "dHRlc3RfaW1wb3J0X3Byb3RvMi5JbXBvcnRNZXNzYWdlOoYBCh5vcHRpb25h", + "bF9uZXN0ZWRfZW51bV9leHRlbnNpb24SKy5wcm90b2J1Zl91bml0dGVzdF9w", + "cm90bzIuVGVzdEFsbEV4dGVuc2lvbnMYFSABKA4yMS5wcm90b2J1Zl91bml0", + "dGVzdF9wcm90bzIuVGVzdEFsbFR5cGVzLk5lc3RlZEVudW06ewofb3B0aW9u", + "YWxfZm9yZWlnbl9lbnVtX2V4dGVuc2lvbhIrLnByb3RvYnVmX3VuaXR0ZXN0", + "X3Byb3RvMi5UZXN0QWxsRXh0ZW5zaW9ucxgWIAEoDjIlLnByb3RvYnVmX3Vu", + "aXR0ZXN0X3Byb3RvMi5Gb3JlaWduRW51bTqAAQoeb3B0aW9uYWxfaW1wb3J0", + "X2VudW1fZXh0ZW5zaW9uEisucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRl", + "c3RBbGxFeHRlbnNpb25zGBcgASgOMisucHJvdG9idWZfdW5pdHRlc3RfaW1w", + "b3J0X3Byb3RvMi5JbXBvcnRFbnVtOlgKH29wdGlvbmFsX3N0cmluZ19waWVj", + "ZV9leHRlbnNpb24SKy5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdEFs", + "bEV4dGVuc2lvbnMYGCABKAlCAggCOlAKF29wdGlvbmFsX2NvcmRfZXh0ZW5z", + "aW9uEisucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RBbGxFeHRlbnNp", + "b25zGBkgASgJQgIIATqTAQoob3B0aW9uYWxfcHVibGljX2ltcG9ydF9tZXNz", + "YWdlX2V4dGVuc2lvbhIrLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0", + "QWxsRXh0ZW5zaW9ucxgaIAEoCzI0LnByb3RvYnVmX3VuaXR0ZXN0X2ltcG9y", + "dF9wcm90bzIuUHVibGljSW1wb3J0TWVzc2FnZTqOAQofb3B0aW9uYWxfbGF6", + "eV9tZXNzYWdlX2V4dGVuc2lvbhIrLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3Rv", + "Mi5UZXN0QWxsRXh0ZW5zaW9ucxgbIAEoCzI0LnByb3RvYnVmX3VuaXR0ZXN0", + "X3Byb3RvMi5UZXN0QWxsVHlwZXMuTmVzdGVkTWVzc2FnZUICKAE6TQoYcmVw", + "ZWF0ZWRfaW50MzJfZXh0ZW5zaW9uEisucHJvdG9idWZfdW5pdHRlc3RfcHJv", + "dG8yLlRlc3RBbGxFeHRlbnNpb25zGB8gAygFOk0KGHJlcGVhdGVkX2ludDY0", + "X2V4dGVuc2lvbhIrLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0QWxs", + "RXh0ZW5zaW9ucxggIAMoAzpOChlyZXBlYXRlZF91aW50MzJfZXh0ZW5zaW9u", + "EisucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RBbGxFeHRlbnNpb25z", + "GCEgAygNOk4KGXJlcGVhdGVkX3VpbnQ2NF9leHRlbnNpb24SKy5wcm90b2J1", + "Zl91bml0dGVzdF9wcm90bzIuVGVzdEFsbEV4dGVuc2lvbnMYIiADKAQ6TgoZ", + "cmVwZWF0ZWRfc2ludDMyX2V4dGVuc2lvbhIrLnByb3RvYnVmX3VuaXR0ZXN0", + "X3Byb3RvMi5UZXN0QWxsRXh0ZW5zaW9ucxgjIAMoETpOChlyZXBlYXRlZF9z", + "aW50NjRfZXh0ZW5zaW9uEisucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRl", + "c3RBbGxFeHRlbnNpb25zGCQgAygSOk8KGnJlcGVhdGVkX2ZpeGVkMzJfZXh0", + "ZW5zaW9uEisucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RBbGxFeHRl", + "bnNpb25zGCUgAygHOk8KGnJlcGVhdGVkX2ZpeGVkNjRfZXh0ZW5zaW9uEisu", + "cHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RBbGxFeHRlbnNpb25zGCYg", + "AygGOlAKG3JlcGVhdGVkX3NmaXhlZDMyX2V4dGVuc2lvbhIrLnByb3RvYnVm", + "X3VuaXR0ZXN0X3Byb3RvMi5UZXN0QWxsRXh0ZW5zaW9ucxgnIAMoDzpQChty", + "ZXBlYXRlZF9zZml4ZWQ2NF9leHRlbnNpb24SKy5wcm90b2J1Zl91bml0dGVz", + "dF9wcm90bzIuVGVzdEFsbEV4dGVuc2lvbnMYKCADKBA6TQoYcmVwZWF0ZWRf", + "ZmxvYXRfZXh0ZW5zaW9uEisucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRl", + "c3RBbGxFeHRlbnNpb25zGCkgAygCOk4KGXJlcGVhdGVkX2RvdWJsZV9leHRl", + "bnNpb24SKy5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdEFsbEV4dGVu", + "c2lvbnMYKiADKAE6TAoXcmVwZWF0ZWRfYm9vbF9leHRlbnNpb24SKy5wcm90", + "b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdEFsbEV4dGVuc2lvbnMYKyADKAg6", + "TgoZcmVwZWF0ZWRfc3RyaW5nX2V4dGVuc2lvbhIrLnByb3RvYnVmX3VuaXR0", + "ZXN0X3Byb3RvMi5UZXN0QWxsRXh0ZW5zaW9ucxgsIAMoCTpNChhyZXBlYXRl", + "ZF9ieXRlc19leHRlbnNpb24SKy5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIu", + "VGVzdEFsbEV4dGVuc2lvbnMYLSADKAw6fwoXcmVwZWF0ZWRncm91cF9leHRl", + "bnNpb24SKy5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdEFsbEV4dGVu", + "c2lvbnMYLiADKAoyMS5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuUmVwZWF0", + "ZWRHcm91cF9leHRlbnNpb246jAEKIXJlcGVhdGVkX25lc3RlZF9tZXNzYWdl", + "X2V4dGVuc2lvbhIrLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0QWxs", + "RXh0ZW5zaW9ucxgwIAMoCzI0LnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5U", + "ZXN0QWxsVHlwZXMuTmVzdGVkTWVzc2FnZTqBAQoicmVwZWF0ZWRfZm9yZWln", + "bl9tZXNzYWdlX2V4dGVuc2lvbhIrLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3Rv", + "Mi5UZXN0QWxsRXh0ZW5zaW9ucxgxIAMoCzIoLnByb3RvYnVmX3VuaXR0ZXN0", + "X3Byb3RvMi5Gb3JlaWduTWVzc2FnZTqGAQohcmVwZWF0ZWRfaW1wb3J0X21l", + "c3NhZ2VfZXh0ZW5zaW9uEisucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRl", + "c3RBbGxFeHRlbnNpb25zGDIgAygLMi4ucHJvdG9idWZfdW5pdHRlc3RfaW1w", + "b3J0X3Byb3RvMi5JbXBvcnRNZXNzYWdlOoYBCh5yZXBlYXRlZF9uZXN0ZWRf", + "ZW51bV9leHRlbnNpb24SKy5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVz", + "dEFsbEV4dGVuc2lvbnMYMyADKA4yMS5wcm90b2J1Zl91bml0dGVzdF9wcm90", + "bzIuVGVzdEFsbFR5cGVzLk5lc3RlZEVudW06ewofcmVwZWF0ZWRfZm9yZWln", + "bl9lbnVtX2V4dGVuc2lvbhIrLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5U", + "ZXN0QWxsRXh0ZW5zaW9ucxg0IAMoDjIlLnByb3RvYnVmX3VuaXR0ZXN0X3By", + "b3RvMi5Gb3JlaWduRW51bTqAAQoecmVwZWF0ZWRfaW1wb3J0X2VudW1fZXh0", + "ZW5zaW9uEisucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RBbGxFeHRl", + "bnNpb25zGDUgAygOMisucHJvdG9idWZfdW5pdHRlc3RfaW1wb3J0X3Byb3Rv", + "Mi5JbXBvcnRFbnVtOlgKH3JlcGVhdGVkX3N0cmluZ19waWVjZV9leHRlbnNp", + "b24SKy5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdEFsbEV4dGVuc2lv", + "bnMYNiADKAlCAggCOlAKF3JlcGVhdGVkX2NvcmRfZXh0ZW5zaW9uEisucHJv", + "dG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RBbGxFeHRlbnNpb25zGDcgAygJ", + "QgIIATqOAQofcmVwZWF0ZWRfbGF6eV9tZXNzYWdlX2V4dGVuc2lvbhIrLnBy", + "b3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0QWxsRXh0ZW5zaW9ucxg5IAMo", + "CzI0LnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0QWxsVHlwZXMuTmVz", + "dGVkTWVzc2FnZUICKAE6UAoXZGVmYXVsdF9pbnQzMl9leHRlbnNpb24SKy5w", + "cm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdEFsbEV4dGVuc2lvbnMYPSAB", + "KAU6AjQxOlAKF2RlZmF1bHRfaW50NjRfZXh0ZW5zaW9uEisucHJvdG9idWZf", + "dW5pdHRlc3RfcHJvdG8yLlRlc3RBbGxFeHRlbnNpb25zGD4gASgDOgI0MjpR", + "ChhkZWZhdWx0X3VpbnQzMl9leHRlbnNpb24SKy5wcm90b2J1Zl91bml0dGVz", + "dF9wcm90bzIuVGVzdEFsbEV4dGVuc2lvbnMYPyABKA06AjQzOlEKGGRlZmF1", + "bHRfdWludDY0X2V4dGVuc2lvbhIrLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3Rv", + "Mi5UZXN0QWxsRXh0ZW5zaW9ucxhAIAEoBDoCNDQ6UgoYZGVmYXVsdF9zaW50", + "MzJfZXh0ZW5zaW9uEisucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RB", + "bGxFeHRlbnNpb25zGEEgASgROgMtNDU6UQoYZGVmYXVsdF9zaW50NjRfZXh0", + "ZW5zaW9uEisucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RBbGxFeHRl", + "bnNpb25zGEIgASgSOgI0NjpSChlkZWZhdWx0X2ZpeGVkMzJfZXh0ZW5zaW9u", + "EisucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RBbGxFeHRlbnNpb25z", + "GEMgASgHOgI0NzpSChlkZWZhdWx0X2ZpeGVkNjRfZXh0ZW5zaW9uEisucHJv", + "dG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RBbGxFeHRlbnNpb25zGEQgASgG", + "OgI0ODpTChpkZWZhdWx0X3NmaXhlZDMyX2V4dGVuc2lvbhIrLnByb3RvYnVm", + "X3VuaXR0ZXN0X3Byb3RvMi5UZXN0QWxsRXh0ZW5zaW9ucxhFIAEoDzoCNDk6", + "VAoaZGVmYXVsdF9zZml4ZWQ2NF9leHRlbnNpb24SKy5wcm90b2J1Zl91bml0", + "dGVzdF9wcm90bzIuVGVzdEFsbEV4dGVuc2lvbnMYRiABKBA6Ay01MDpSChdk", + "ZWZhdWx0X2Zsb2F0X2V4dGVuc2lvbhIrLnByb3RvYnVmX3VuaXR0ZXN0X3By", + "b3RvMi5UZXN0QWxsRXh0ZW5zaW9ucxhHIAEoAjoENTEuNTpUChhkZWZhdWx0", + "X2RvdWJsZV9leHRlbnNpb24SKy5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIu", + "VGVzdEFsbEV4dGVuc2lvbnMYSCABKAE6BTUyMDAwOlEKFmRlZmF1bHRfYm9v", + "bF9leHRlbnNpb24SKy5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdEFs", + "bEV4dGVuc2lvbnMYSSABKAg6BHRydWU6VAoYZGVmYXVsdF9zdHJpbmdfZXh0", + "ZW5zaW9uEisucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RBbGxFeHRl", + "bnNpb25zGEogASgJOgVoZWxsbzpTChdkZWZhdWx0X2J5dGVzX2V4dGVuc2lv", + "bhIrLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0QWxsRXh0ZW5zaW9u", + "cxhLIAEoDDoFd29ybGQ6igEKHWRlZmF1bHRfbmVzdGVkX2VudW1fZXh0ZW5z", + "aW9uEisucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RBbGxFeHRlbnNp", + "b25zGFEgASgOMjEucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RBbGxU", + "eXBlcy5OZXN0ZWRFbnVtOgNCQVI6hwEKHmRlZmF1bHRfZm9yZWlnbl9lbnVt", + "X2V4dGVuc2lvbhIrLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0QWxs", + "RXh0ZW5zaW9ucxhSIAEoDjIlLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5G", + "b3JlaWduRW51bToLRk9SRUlHTl9CQVI6iwEKHWRlZmF1bHRfaW1wb3J0X2Vu", + "dW1fZXh0ZW5zaW9uEisucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RB", + "bGxFeHRlbnNpb25zGFMgASgOMisucHJvdG9idWZfdW5pdHRlc3RfaW1wb3J0", + "X3Byb3RvMi5JbXBvcnRFbnVtOgpJTVBPUlRfQkFSOlwKHmRlZmF1bHRfc3Ry", + "aW5nX3BpZWNlX2V4dGVuc2lvbhIrLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3Rv", + "Mi5UZXN0QWxsRXh0ZW5zaW9ucxhUIAEoCToDYWJjQgIIAjpUChZkZWZhdWx0", + "X2NvcmRfZXh0ZW5zaW9uEisucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRl", + "c3RBbGxFeHRlbnNpb25zGFUgASgJOgMxMjNCAggBOksKFm9uZW9mX3VpbnQz", + "Ml9leHRlbnNpb24SKy5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdEFs", + "bEV4dGVuc2lvbnMYbyABKA06iQEKHm9uZW9mX25lc3RlZF9tZXNzYWdlX2V4", + "dGVuc2lvbhIrLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0QWxsRXh0", + "ZW5zaW9ucxhwIAEoCzI0LnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0", + "QWxsVHlwZXMuTmVzdGVkTWVzc2FnZTpLChZvbmVvZl9zdHJpbmdfZXh0ZW5z", + "aW9uEisucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RBbGxFeHRlbnNp", + "b25zGHEgASgJOkoKFW9uZW9mX2J5dGVzX2V4dGVuc2lvbhIrLnByb3RvYnVm", + "X3VuaXR0ZXN0X3Byb3RvMi5UZXN0QWxsRXh0ZW5zaW9ucxhyIAEoDDpJChNt", + "eV9leHRlbnNpb25fc3RyaW5nEiwucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8y", + "LlRlc3RGaWVsZE9yZGVyaW5ncxgyIAEoCTpGChBteV9leHRlbnNpb25faW50", + "EiwucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RGaWVsZE9yZGVyaW5n", + "cxgFIAEoBTpSChZwYWNrZWRfaW50MzJfZXh0ZW5zaW9uEi4ucHJvdG9idWZf", + "dW5pdHRlc3RfcHJvdG8yLlRlc3RQYWNrZWRFeHRlbnNpb25zGFogAygFQgIQ", + "ATpSChZwYWNrZWRfaW50NjRfZXh0ZW5zaW9uEi4ucHJvdG9idWZfdW5pdHRl", + "c3RfcHJvdG8yLlRlc3RQYWNrZWRFeHRlbnNpb25zGFsgAygDQgIQATpTChdw", + "YWNrZWRfdWludDMyX2V4dGVuc2lvbhIuLnByb3RvYnVmX3VuaXR0ZXN0X3By", + "b3RvMi5UZXN0UGFja2VkRXh0ZW5zaW9ucxhcIAMoDUICEAE6UwoXcGFja2Vk", + "X3VpbnQ2NF9leHRlbnNpb24SLi5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIu", + "VGVzdFBhY2tlZEV4dGVuc2lvbnMYXSADKARCAhABOlMKF3BhY2tlZF9zaW50", + "MzJfZXh0ZW5zaW9uEi4ucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RQ", + "YWNrZWRFeHRlbnNpb25zGF4gAygRQgIQATpTChdwYWNrZWRfc2ludDY0X2V4", + "dGVuc2lvbhIuLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0UGFja2Vk", + "RXh0ZW5zaW9ucxhfIAMoEkICEAE6VAoYcGFja2VkX2ZpeGVkMzJfZXh0ZW5z", + "aW9uEi4ucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RQYWNrZWRFeHRl", + "bnNpb25zGGAgAygHQgIQATpUChhwYWNrZWRfZml4ZWQ2NF9leHRlbnNpb24S", + "Li5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdFBhY2tlZEV4dGVuc2lv", + "bnMYYSADKAZCAhABOlUKGXBhY2tlZF9zZml4ZWQzMl9leHRlbnNpb24SLi5w", + "cm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdFBhY2tlZEV4dGVuc2lvbnMY", + "YiADKA9CAhABOlUKGXBhY2tlZF9zZml4ZWQ2NF9leHRlbnNpb24SLi5wcm90", + "b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdFBhY2tlZEV4dGVuc2lvbnMYYyAD", + "KBBCAhABOlIKFnBhY2tlZF9mbG9hdF9leHRlbnNpb24SLi5wcm90b2J1Zl91", + "bml0dGVzdF9wcm90bzIuVGVzdFBhY2tlZEV4dGVuc2lvbnMYZCADKAJCAhAB", + "OlMKF3BhY2tlZF9kb3VibGVfZXh0ZW5zaW9uEi4ucHJvdG9idWZfdW5pdHRl", + "c3RfcHJvdG8yLlRlc3RQYWNrZWRFeHRlbnNpb25zGGUgAygBQgIQATpRChVw", + "YWNrZWRfYm9vbF9leHRlbnNpb24SLi5wcm90b2J1Zl91bml0dGVzdF9wcm90", + "bzIuVGVzdFBhY2tlZEV4dGVuc2lvbnMYZiADKAhCAhABOngKFXBhY2tlZF9l", + "bnVtX2V4dGVuc2lvbhIuLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0", + "UGFja2VkRXh0ZW5zaW9ucxhnIAMoDjIlLnByb3RvYnVmX3VuaXR0ZXN0X3By", + "b3RvMi5Gb3JlaWduRW51bUICEAE6VgoYdW5wYWNrZWRfaW50MzJfZXh0ZW5z", + "aW9uEjAucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RVbnBhY2tlZEV4", + "dGVuc2lvbnMYWiADKAVCAhAAOlYKGHVucGFja2VkX2ludDY0X2V4dGVuc2lv", + "bhIwLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0VW5wYWNrZWRFeHRl", + "bnNpb25zGFsgAygDQgIQADpXChl1bnBhY2tlZF91aW50MzJfZXh0ZW5zaW9u", + "EjAucHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RVbnBhY2tlZEV4dGVu", + "c2lvbnMYXCADKA1CAhAAOlcKGXVucGFja2VkX3VpbnQ2NF9leHRlbnNpb24S", + "MC5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdFVucGFja2VkRXh0ZW5z", + "aW9ucxhdIAMoBEICEAA6VwoZdW5wYWNrZWRfc2ludDMyX2V4dGVuc2lvbhIw", + "LnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0VW5wYWNrZWRFeHRlbnNp", + "b25zGF4gAygRQgIQADpXChl1bnBhY2tlZF9zaW50NjRfZXh0ZW5zaW9uEjAu", + "cHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RVbnBhY2tlZEV4dGVuc2lv", + "bnMYXyADKBJCAhAAOlgKGnVucGFja2VkX2ZpeGVkMzJfZXh0ZW5zaW9uEjAu", + "cHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RVbnBhY2tlZEV4dGVuc2lv", + "bnMYYCADKAdCAhAAOlgKGnVucGFja2VkX2ZpeGVkNjRfZXh0ZW5zaW9uEjAu", + "cHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RVbnBhY2tlZEV4dGVuc2lv", + "bnMYYSADKAZCAhAAOlkKG3VucGFja2VkX3NmaXhlZDMyX2V4dGVuc2lvbhIw", + "LnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5UZXN0VW5wYWNrZWRFeHRlbnNp", + "b25zGGIgAygPQgIQADpZCht1bnBhY2tlZF9zZml4ZWQ2NF9leHRlbnNpb24S", + "MC5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdFVucGFja2VkRXh0ZW5z", + "aW9ucxhjIAMoEEICEAA6VgoYdW5wYWNrZWRfZmxvYXRfZXh0ZW5zaW9uEjAu", + "cHJvdG9idWZfdW5pdHRlc3RfcHJvdG8yLlRlc3RVbnBhY2tlZEV4dGVuc2lv", + "bnMYZCADKAJCAhAAOlcKGXVucGFja2VkX2RvdWJsZV9leHRlbnNpb24SMC5w", + "cm90b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdFVucGFja2VkRXh0ZW5zaW9u", + "cxhlIAMoAUICEAA6VQoXdW5wYWNrZWRfYm9vbF9leHRlbnNpb24SMC5wcm90", + "b2J1Zl91bml0dGVzdF9wcm90bzIuVGVzdFVucGFja2VkRXh0ZW5zaW9ucxhm", + "IAMoCEICEAA6fAoXdW5wYWNrZWRfZW51bV9leHRlbnNpb24SMC5wcm90b2J1", + "Zl91bml0dGVzdF9wcm90bzIuVGVzdFVucGFja2VkRXh0ZW5zaW9ucxhnIAMo", + "DjIlLnByb3RvYnVmX3VuaXR0ZXN0X3Byb3RvMi5Gb3JlaWduRW51bUICEAA6", + "cgoOdGVzdF9hbGxfdHlwZXMSLi5wcm90b2J1Zl91bml0dGVzdF9wcm90bzIu", + "VGVzdEh1Z2VGaWVsZE51bWJlcnMY4Kr//wEgASgLMiYucHJvdG9idWZfdW5p", + "dHRlc3RfcHJvdG8yLlRlc3RBbGxUeXBlczphCiV0ZXN0X2V4dGVuc2lvbl9p", + "bnNpZGVfdGFibGVfZXh0ZW5zaW9uEjIucHJvdG9idWZfdW5pdHRlc3RfcHJv", + "dG8yLlRlc3RFeHRlbnNpb25JbnNpZGVUYWJsZRgFIAEoBUIySAGAAQGIAQGQ", + "AQH4AQGqAiFHb29nbGUuUHJvdG9idWYuVGVzdFByb3Rvcy5Qcm90bzI=")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { global::Google.Protobuf.TestProtos.Proto2.UnittestImportReflection.Descriptor, }, + new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Google.Protobuf.TestProtos.Proto2.ForeignEnum), typeof(global::Google.Protobuf.TestProtos.Proto2.TestEnumWithDupValue), typeof(global::Google.Protobuf.TestProtos.Proto2.TestSparseEnum), typeof(global::Google.Protobuf.TestProtos.Proto2.VeryLargeEnum), }, new pb::Extension[] { UnittestExtensions.OptionalInt32Extension, UnittestExtensions.OptionalInt64Extension, UnittestExtensions.OptionalUint32Extension, UnittestExtensions.OptionalUint64Extension, UnittestExtensions.OptionalSint32Extension, UnittestExtensions.OptionalSint64Extension, UnittestExtensions.OptionalFixed32Extension, UnittestExtensions.OptionalFixed64Extension, UnittestExtensions.OptionalSfixed32Extension, UnittestExtensions.OptionalSfixed64Extension, UnittestExtensions.OptionalFloatExtension, UnittestExtensions.OptionalDoubleExtension, UnittestExtensions.OptionalBoolExtension, UnittestExtensions.OptionalStringExtension, UnittestExtensions.OptionalBytesExtension, UnittestExtensions.OptionalGroupExtension, UnittestExtensions.OptionalNestedMessageExtension, UnittestExtensions.OptionalForeignMessageExtension, UnittestExtensions.OptionalImportMessageExtension, UnittestExtensions.OptionalNestedEnumExtension, UnittestExtensions.OptionalForeignEnumExtension, UnittestExtensions.OptionalImportEnumExtension, UnittestExtensions.OptionalStringPieceExtension, UnittestExtensions.OptionalCordExtension, UnittestExtensions.OptionalPublicImportMessageExtension, UnittestExtensions.OptionalLazyMessageExtension, UnittestExtensions.RepeatedInt32Extension, UnittestExtensions.RepeatedInt64Extension, UnittestExtensions.RepeatedUint32Extension, UnittestExtensions.RepeatedUint64Extension, UnittestExtensions.RepeatedSint32Extension, UnittestExtensions.RepeatedSint64Extension, UnittestExtensions.RepeatedFixed32Extension, UnittestExtensions.RepeatedFixed64Extension, UnittestExtensions.RepeatedSfixed32Extension, UnittestExtensions.RepeatedSfixed64Extension, UnittestExtensions.RepeatedFloatExtension, UnittestExtensions.RepeatedDoubleExtension, UnittestExtensions.RepeatedBoolExtension, UnittestExtensions.RepeatedStringExtension, UnittestExtensions.RepeatedBytesExtension, UnittestExtensions.RepeatedGroupExtension, UnittestExtensions.RepeatedNestedMessageExtension, UnittestExtensions.RepeatedForeignMessageExtension, UnittestExtensions.RepeatedImportMessageExtension, UnittestExtensions.RepeatedNestedEnumExtension, UnittestExtensions.RepeatedForeignEnumExtension, UnittestExtensions.RepeatedImportEnumExtension, UnittestExtensions.RepeatedStringPieceExtension, UnittestExtensions.RepeatedCordExtension, UnittestExtensions.RepeatedLazyMessageExtension, UnittestExtensions.DefaultInt32Extension, UnittestExtensions.DefaultInt64Extension, UnittestExtensions.DefaultUint32Extension, UnittestExtensions.DefaultUint64Extension, UnittestExtensions.DefaultSint32Extension, UnittestExtensions.DefaultSint64Extension, UnittestExtensions.DefaultFixed32Extension, UnittestExtensions.DefaultFixed64Extension, UnittestExtensions.DefaultSfixed32Extension, UnittestExtensions.DefaultSfixed64Extension, UnittestExtensions.DefaultFloatExtension, UnittestExtensions.DefaultDoubleExtension, UnittestExtensions.DefaultBoolExtension, UnittestExtensions.DefaultStringExtension, UnittestExtensions.DefaultBytesExtension, UnittestExtensions.DefaultNestedEnumExtension, UnittestExtensions.DefaultForeignEnumExtension, UnittestExtensions.DefaultImportEnumExtension, UnittestExtensions.DefaultStringPieceExtension, UnittestExtensions.DefaultCordExtension, UnittestExtensions.OneofUint32Extension, UnittestExtensions.OneofNestedMessageExtension, UnittestExtensions.OneofStringExtension, UnittestExtensions.OneofBytesExtension, UnittestExtensions.MyExtensionString, UnittestExtensions.MyExtensionInt, UnittestExtensions.PackedInt32Extension, UnittestExtensions.PackedInt64Extension, UnittestExtensions.PackedUint32Extension, UnittestExtensions.PackedUint64Extension, UnittestExtensions.PackedSint32Extension, UnittestExtensions.PackedSint64Extension, UnittestExtensions.PackedFixed32Extension, UnittestExtensions.PackedFixed64Extension, UnittestExtensions.PackedSfixed32Extension, UnittestExtensions.PackedSfixed64Extension, UnittestExtensions.PackedFloatExtension, UnittestExtensions.PackedDoubleExtension, UnittestExtensions.PackedBoolExtension, UnittestExtensions.PackedEnumExtension, UnittestExtensions.UnpackedInt32Extension, UnittestExtensions.UnpackedInt64Extension, UnittestExtensions.UnpackedUint32Extension, UnittestExtensions.UnpackedUint64Extension, UnittestExtensions.UnpackedSint32Extension, UnittestExtensions.UnpackedSint64Extension, UnittestExtensions.UnpackedFixed32Extension, UnittestExtensions.UnpackedFixed64Extension, UnittestExtensions.UnpackedSfixed32Extension, UnittestExtensions.UnpackedSfixed64Extension, UnittestExtensions.UnpackedFloatExtension, UnittestExtensions.UnpackedDoubleExtension, UnittestExtensions.UnpackedBoolExtension, UnittestExtensions.UnpackedEnumExtension, UnittestExtensions.TestAllTypes, UnittestExtensions.TestExtensionInsideTableExtension }, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestAllTypes), global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Parser, new[]{ "OptionalInt32", "OptionalInt64", "OptionalUint32", "OptionalUint64", "OptionalSint32", "OptionalSint64", "OptionalFixed32", "OptionalFixed64", "OptionalSfixed32", "OptionalSfixed64", "OptionalFloat", "OptionalDouble", "OptionalBool", "OptionalString", "OptionalBytes", "OptionalGroup", "OptionalNestedMessage", "OptionalForeignMessage", "OptionalImportMessage", "OptionalNestedEnum", "OptionalForeignEnum", "OptionalImportEnum", "OptionalStringPiece", "OptionalCord", "OptionalPublicImportMessage", "OptionalLazyMessage", "RepeatedInt32", "RepeatedInt64", "RepeatedUint32", "RepeatedUint64", "RepeatedSint32", "RepeatedSint64", "RepeatedFixed32", "RepeatedFixed64", "RepeatedSfixed32", "RepeatedSfixed64", "RepeatedFloat", "RepeatedDouble", "RepeatedBool", "RepeatedString", "RepeatedBytes", "RepeatedGroup", "RepeatedNestedMessage", "RepeatedForeignMessage", "RepeatedImportMessage", "RepeatedNestedEnum", "RepeatedForeignEnum", "RepeatedImportEnum", "RepeatedStringPiece", "RepeatedCord", "RepeatedLazyMessage", "DefaultInt32", "DefaultInt64", "DefaultUint32", "DefaultUint64", "DefaultSint32", "DefaultSint64", "DefaultFixed32", "DefaultFixed64", "DefaultSfixed32", "DefaultSfixed64", "DefaultFloat", "DefaultDouble", "DefaultBool", "DefaultString", "DefaultBytes", "DefaultNestedEnum", "DefaultForeignEnum", "DefaultImportEnum", "DefaultStringPiece", "DefaultCord", "OneofUint32", "OneofNestedMessage", "OneofString", "OneofBytes" }, new[]{ "OneofField" }, new[]{ typeof(global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedEnum) }, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage), global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage.Parser, new[]{ "Bb" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.OptionalGroup), global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.OptionalGroup.Parser, new[]{ "A" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.RepeatedGroup), global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.RepeatedGroup.Parser, new[]{ "A" }, null, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.NestedTestAllTypes), global::Google.Protobuf.TestProtos.Proto2.NestedTestAllTypes.Parser, new[]{ "Child", "Payload", "RepeatedChild" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestDeprecatedFields), global::Google.Protobuf.TestProtos.Proto2.TestDeprecatedFields.Parser, new[]{ "DeprecatedInt32", "DeprecatedInt32InOneof" }, new[]{ "OneofFields" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestDeprecatedMessage), global::Google.Protobuf.TestProtos.Proto2.TestDeprecatedMessage.Parser, null, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.ForeignMessage), global::Google.Protobuf.TestProtos.Proto2.ForeignMessage.Parser, new[]{ "C", "D" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestReservedFields), global::Google.Protobuf.TestProtos.Proto2.TestReservedFields.Parser, null, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestAllExtensions), global::Google.Protobuf.TestProtos.Proto2.TestAllExtensions.Parser, null, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.OptionalGroup_extension), global::Google.Protobuf.TestProtos.Proto2.OptionalGroup_extension.Parser, new[]{ "A" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.RepeatedGroup_extension), global::Google.Protobuf.TestProtos.Proto2.RepeatedGroup_extension.Parser, new[]{ "A" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestGroup), global::Google.Protobuf.TestProtos.Proto2.TestGroup.Parser, new[]{ "OptionalGroup", "OptionalForeignEnum" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestGroup.Types.OptionalGroup), global::Google.Protobuf.TestProtos.Proto2.TestGroup.Types.OptionalGroup.Parser, new[]{ "A" }, null, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestGroupExtension), global::Google.Protobuf.TestProtos.Proto2.TestGroupExtension.Parser, null, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestNestedExtension), global::Google.Protobuf.TestProtos.Proto2.TestNestedExtension.Parser, null, null, null, new pb::Extension[] { global::Google.Protobuf.TestProtos.Proto2.TestNestedExtension.Extensions.Test, global::Google.Protobuf.TestProtos.Proto2.TestNestedExtension.Extensions.NestedStringExtension, global::Google.Protobuf.TestProtos.Proto2.TestNestedExtension.Extensions.OptionalGroupExtension, global::Google.Protobuf.TestProtos.Proto2.TestNestedExtension.Extensions.OptionalForeignEnumExtension }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestNestedExtension.Types.OptionalGroup_extension), global::Google.Protobuf.TestProtos.Proto2.TestNestedExtension.Types.OptionalGroup_extension.Parser, new[]{ "A" }, null, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestRequired), global::Google.Protobuf.TestProtos.Proto2.TestRequired.Parser, new[]{ "A", "Dummy2", "B", "Dummy4", "Dummy5", "Dummy6", "Dummy7", "Dummy8", "Dummy9", "Dummy10", "Dummy11", "Dummy12", "Dummy13", "Dummy14", "Dummy15", "Dummy16", "Dummy17", "Dummy18", "Dummy19", "Dummy20", "Dummy21", "Dummy22", "Dummy23", "Dummy24", "Dummy25", "Dummy26", "Dummy27", "Dummy28", "Dummy29", "Dummy30", "Dummy31", "Dummy32", "C" }, null, null, new pb::Extension[] { global::Google.Protobuf.TestProtos.Proto2.TestRequired.Extensions.Single, global::Google.Protobuf.TestProtos.Proto2.TestRequired.Extensions.Multi }, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestRequiredForeign), global::Google.Protobuf.TestProtos.Proto2.TestRequiredForeign.Parser, new[]{ "OptionalMessage", "RepeatedMessage", "Dummy" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestRequiredMessage), global::Google.Protobuf.TestProtos.Proto2.TestRequiredMessage.Parser, new[]{ "OptionalMessage", "RepeatedMessage", "RequiredMessage" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestForeignNested), global::Google.Protobuf.TestProtos.Proto2.TestForeignNested.Parser, new[]{ "ForeignNested" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestEmptyMessage), global::Google.Protobuf.TestProtos.Proto2.TestEmptyMessage.Parser, null, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestEmptyMessageWithExtensions), global::Google.Protobuf.TestProtos.Proto2.TestEmptyMessageWithExtensions.Parser, null, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestMultipleExtensionRanges), global::Google.Protobuf.TestProtos.Proto2.TestMultipleExtensionRanges.Parser, null, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestReallyLargeTagNumber), global::Google.Protobuf.TestProtos.Proto2.TestReallyLargeTagNumber.Parser, new[]{ "A", "Bb" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestRecursiveMessage), global::Google.Protobuf.TestProtos.Proto2.TestRecursiveMessage.Parser, new[]{ "A", "I" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA), global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA.Parser, new[]{ "Bb", "SubGroup" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA.Types.SubMessage), global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA.Types.SubMessage.Parser, new[]{ "B" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA.Types.SubGroup), global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA.Types.SubGroup.Parser, new[]{ "SubMessage", "NotInThisScc" }, null, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionB), global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionB.Parser, new[]{ "A", "OptionalInt32" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestIsInitialized), global::Google.Protobuf.TestProtos.Proto2.TestIsInitialized.Parser, new[]{ "SubMessage" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestIsInitialized.Types.SubMessage), global::Google.Protobuf.TestProtos.Proto2.TestIsInitialized.Types.SubMessage.Parser, new[]{ "SubGroup" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestIsInitialized.Types.SubMessage.Types.SubGroup), global::Google.Protobuf.TestProtos.Proto2.TestIsInitialized.Types.SubMessage.Types.SubGroup.Parser, new[]{ "I" }, null, null, null, null)})}), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestDupFieldNumber), global::Google.Protobuf.TestProtos.Proto2.TestDupFieldNumber.Parser, new[]{ "A", "Foo", "Bar" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestDupFieldNumber.Types.Foo), global::Google.Protobuf.TestProtos.Proto2.TestDupFieldNumber.Types.Foo.Parser, new[]{ "A" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestDupFieldNumber.Types.Bar), global::Google.Protobuf.TestProtos.Proto2.TestDupFieldNumber.Types.Bar.Parser, new[]{ "A" }, null, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestEagerMessage), global::Google.Protobuf.TestProtos.Proto2.TestEagerMessage.Parser, new[]{ "SubMessage" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestLazyMessage), global::Google.Protobuf.TestProtos.Proto2.TestLazyMessage.Parser, new[]{ "SubMessage" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestNestedMessageHasBits), global::Google.Protobuf.TestProtos.Proto2.TestNestedMessageHasBits.Parser, new[]{ "OptionalNestedMessage" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestNestedMessageHasBits.Types.NestedMessage), global::Google.Protobuf.TestProtos.Proto2.TestNestedMessageHasBits.Types.NestedMessage.Parser, new[]{ "NestedmessageRepeatedInt32", "NestedmessageRepeatedForeignmessage" }, null, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestCamelCaseFieldNames), global::Google.Protobuf.TestProtos.Proto2.TestCamelCaseFieldNames.Parser, new[]{ "PrimitiveField", "StringField", "EnumField", "MessageField", "StringPieceField", "CordField", "RepeatedPrimitiveField", "RepeatedStringField", "RepeatedEnumField", "RepeatedMessageField", "RepeatedStringPieceField", "RepeatedCordField" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestFieldOrderings), global::Google.Protobuf.TestProtos.Proto2.TestFieldOrderings.Parser, new[]{ "MyString", "MyInt", "MyFloat", "OptionalNestedMessage" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestFieldOrderings.Types.NestedMessage), global::Google.Protobuf.TestProtos.Proto2.TestFieldOrderings.Types.NestedMessage.Parser, new[]{ "Oo", "Bb" }, null, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestExtensionOrderings1), global::Google.Protobuf.TestProtos.Proto2.TestExtensionOrderings1.Parser, new[]{ "MyString" }, null, null, new pb::Extension[] { global::Google.Protobuf.TestProtos.Proto2.TestExtensionOrderings1.Extensions.TestExtOrderings1 }, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestExtensionOrderings2), global::Google.Protobuf.TestProtos.Proto2.TestExtensionOrderings2.Parser, new[]{ "MyString" }, null, null, new pb::Extension[] { global::Google.Protobuf.TestProtos.Proto2.TestExtensionOrderings2.Extensions.TestExtOrderings2 }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestExtensionOrderings2.Types.TestExtensionOrderings3), global::Google.Protobuf.TestProtos.Proto2.TestExtensionOrderings2.Types.TestExtensionOrderings3.Parser, new[]{ "MyString" }, null, null, new pb::Extension[] { global::Google.Protobuf.TestProtos.Proto2.TestExtensionOrderings2.Types.TestExtensionOrderings3.Extensions.TestExtOrderings3 }, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestExtremeDefaultValues), global::Google.Protobuf.TestProtos.Proto2.TestExtremeDefaultValues.Parser, new[]{ "EscapedBytes", "LargeUint32", "LargeUint64", "SmallInt32", "SmallInt64", "ReallySmallInt32", "ReallySmallInt64", "Utf8String", "ZeroFloat", "OneFloat", "SmallFloat", "NegativeOneFloat", "NegativeFloat", "LargeFloat", "SmallNegativeFloat", "InfDouble", "NegInfDouble", "NanDouble", "InfFloat", "NegInfFloat", "NanFloat", "CppTrigraph", "StringWithZero", "BytesWithZero", "StringPieceWithZero", "CordWithZero", "ReplacementString" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.SparseEnumMessage), global::Google.Protobuf.TestProtos.Proto2.SparseEnumMessage.Parser, new[]{ "SparseEnum" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.OneString), global::Google.Protobuf.TestProtos.Proto2.OneString.Parser, new[]{ "Data" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.MoreString), global::Google.Protobuf.TestProtos.Proto2.MoreString.Parser, new[]{ "Data" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.OneBytes), global::Google.Protobuf.TestProtos.Proto2.OneBytes.Parser, new[]{ "Data" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.MoreBytes), global::Google.Protobuf.TestProtos.Proto2.MoreBytes.Parser, new[]{ "Data" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.Int32Message), global::Google.Protobuf.TestProtos.Proto2.Int32Message.Parser, new[]{ "Data" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.Uint32Message), global::Google.Protobuf.TestProtos.Proto2.Uint32Message.Parser, new[]{ "Data" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.Int64Message), global::Google.Protobuf.TestProtos.Proto2.Int64Message.Parser, new[]{ "Data" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.Uint64Message), global::Google.Protobuf.TestProtos.Proto2.Uint64Message.Parser, new[]{ "Data" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.BoolMessage), global::Google.Protobuf.TestProtos.Proto2.BoolMessage.Parser, new[]{ "Data" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestOneof), global::Google.Protobuf.TestProtos.Proto2.TestOneof.Parser, new[]{ "FooInt", "FooString", "FooMessage", "FooGroup" }, new[]{ "Foo" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestOneof.Types.FooGroup), global::Google.Protobuf.TestProtos.Proto2.TestOneof.Types.FooGroup.Parser, new[]{ "A", "B" }, null, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestOneofBackwardsCompatible), global::Google.Protobuf.TestProtos.Proto2.TestOneofBackwardsCompatible.Parser, new[]{ "FooInt", "FooString", "FooMessage", "FooGroup" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestOneofBackwardsCompatible.Types.FooGroup), global::Google.Protobuf.TestProtos.Proto2.TestOneofBackwardsCompatible.Types.FooGroup.Parser, new[]{ "A", "B" }, null, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestOneof2), global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Parser, new[]{ "FooInt", "FooString", "FooCord", "FooStringPiece", "FooBytes", "FooEnum", "FooMessage", "FooGroup", "FooLazyMessage", "BarInt", "BarString", "BarCord", "BarStringPiece", "BarBytes", "BarEnum", "BazInt", "BazString" }, new[]{ "Foo", "Bar" }, new[]{ typeof(global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedEnum) }, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.FooGroup), global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.FooGroup.Parser, new[]{ "A", "B" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage), global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage.Parser, new[]{ "QuxInt", "CorgeInt" }, null, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestRequiredOneof), global::Google.Protobuf.TestProtos.Proto2.TestRequiredOneof.Parser, new[]{ "FooInt", "FooString", "FooMessage" }, new[]{ "Foo" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestRequiredOneof.Types.NestedMessage), global::Google.Protobuf.TestProtos.Proto2.TestRequiredOneof.Types.NestedMessage.Parser, new[]{ "RequiredDouble" }, null, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestRequiredMap), global::Google.Protobuf.TestProtos.Proto2.TestRequiredMap.Parser, new[]{ "Foo" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { null, new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestRequiredMap.Types.NestedMessage), global::Google.Protobuf.TestProtos.Proto2.TestRequiredMap.Types.NestedMessage.Parser, new[]{ "RequiredInt32" }, null, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestPackedTypes), global::Google.Protobuf.TestProtos.Proto2.TestPackedTypes.Parser, new[]{ "PackedInt32", "PackedInt64", "PackedUint32", "PackedUint64", "PackedSint32", "PackedSint64", "PackedFixed32", "PackedFixed64", "PackedSfixed32", "PackedSfixed64", "PackedFloat", "PackedDouble", "PackedBool", "PackedEnum" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestUnpackedTypes), global::Google.Protobuf.TestProtos.Proto2.TestUnpackedTypes.Parser, new[]{ "UnpackedInt32", "UnpackedInt64", "UnpackedUint32", "UnpackedUint64", "UnpackedSint32", "UnpackedSint64", "UnpackedFixed32", "UnpackedFixed64", "UnpackedSfixed32", "UnpackedSfixed64", "UnpackedFloat", "UnpackedDouble", "UnpackedBool", "UnpackedEnum" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestPackedExtensions), global::Google.Protobuf.TestProtos.Proto2.TestPackedExtensions.Parser, null, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestUnpackedExtensions), global::Google.Protobuf.TestProtos.Proto2.TestUnpackedExtensions.Parser, null, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestDynamicExtensions), global::Google.Protobuf.TestProtos.Proto2.TestDynamicExtensions.Parser, new[]{ "ScalarExtension", "EnumExtension", "DynamicEnumExtension", "MessageExtension", "DynamicMessageExtension", "RepeatedExtension", "PackedExtension" }, null, new[]{ typeof(global::Google.Protobuf.TestProtos.Proto2.TestDynamicExtensions.Types.DynamicEnumType) }, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestDynamicExtensions.Types.DynamicMessageType), global::Google.Protobuf.TestProtos.Proto2.TestDynamicExtensions.Types.DynamicMessageType.Parser, new[]{ "DynamicField" }, null, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestRepeatedScalarDifferentTagSizes), global::Google.Protobuf.TestProtos.Proto2.TestRepeatedScalarDifferentTagSizes.Parser, new[]{ "RepeatedFixed32", "RepeatedInt32", "RepeatedFixed64", "RepeatedInt64", "RepeatedFloat", "RepeatedUint64" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge), global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Parser, new[]{ "RequiredAllTypes", "OptionalAllTypes", "RepeatedAllTypes", "OptionalGroup", "RepeatedGroup" }, null, null, new pb::Extension[] { global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Extensions.OptionalExt, global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Extensions.RepeatedExt }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Types.RepeatedFieldsGenerator), global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Types.RepeatedFieldsGenerator.Parser, new[]{ "Field1", "Field2", "Field3", "Group1", "Group2", "Ext1", "Ext2" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Types.RepeatedFieldsGenerator.Types.Group1), global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Types.RepeatedFieldsGenerator.Types.Group1.Parser, new[]{ "Field1" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Types.RepeatedFieldsGenerator.Types.Group2), global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Types.RepeatedFieldsGenerator.Types.Group2.Parser, new[]{ "Field1" }, null, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Types.OptionalGroup), global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Types.OptionalGroup.Parser, new[]{ "OptionalGroupAllTypes" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Types.RepeatedGroup), global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Types.RepeatedGroup.Parser, new[]{ "RepeatedGroupAllTypes" }, null, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestCommentInjectionMessage), global::Google.Protobuf.TestProtos.Proto2.TestCommentInjectionMessage.Parser, new[]{ "A" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.FooRequest), global::Google.Protobuf.TestProtos.Proto2.FooRequest.Parser, null, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.FooResponse), global::Google.Protobuf.TestProtos.Proto2.FooResponse.Parser, null, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.FooClientMessage), global::Google.Protobuf.TestProtos.Proto2.FooClientMessage.Parser, null, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.FooServerMessage), global::Google.Protobuf.TestProtos.Proto2.FooServerMessage.Parser, null, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.BarRequest), global::Google.Protobuf.TestProtos.Proto2.BarRequest.Parser, null, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.BarResponse), global::Google.Protobuf.TestProtos.Proto2.BarResponse.Parser, null, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestJsonName), global::Google.Protobuf.TestProtos.Proto2.TestJsonName.Parser, new[]{ "FieldName1", "FieldName2", "FieldName3", "FieldName4", "FIELDNAME5", "FieldName6" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestHugeFieldNumbers), global::Google.Protobuf.TestProtos.Proto2.TestHugeFieldNumbers.Parser, new[]{ "OptionalInt32", "Fixed32", "RepeatedInt32", "PackedInt32", "OptionalEnum", "OptionalString", "OptionalBytes", "OptionalMessage", "OptionalGroup", "StringStringMap", "OneofUint32", "OneofTestAllTypes", "OneofString", "OneofBytes" }, new[]{ "OneofField" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestHugeFieldNumbers.Types.OptionalGroup), global::Google.Protobuf.TestProtos.Proto2.TestHugeFieldNumbers.Types.OptionalGroup.Parser, new[]{ "GroupA" }, null, null, null, null), + null, }), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.Proto2.TestExtensionInsideTable), global::Google.Protobuf.TestProtos.Proto2.TestExtensionInsideTable.Parser, new[]{ "Field1", "Field2", "Field3", "Field4", "Field6", "Field7", "Field8", "Field9", "Field10" }, null, null, null, null) + })); + } + #endregion + + } + /// Holder for extension identifiers generated from the top level of unittest.proto + public static partial class UnittestExtensions { + /// + /// Singular + /// + public static readonly pb::Extension OptionalInt32Extension = + new pb::Extension(1, pb::FieldCodec.ForInt32(8, 0)); + public static readonly pb::Extension OptionalInt64Extension = + new pb::Extension(2, pb::FieldCodec.ForInt64(16, 0L)); + public static readonly pb::Extension OptionalUint32Extension = + new pb::Extension(3, pb::FieldCodec.ForUInt32(24, 0)); + public static readonly pb::Extension OptionalUint64Extension = + new pb::Extension(4, pb::FieldCodec.ForUInt64(32, 0UL)); + public static readonly pb::Extension OptionalSint32Extension = + new pb::Extension(5, pb::FieldCodec.ForSInt32(40, 0)); + public static readonly pb::Extension OptionalSint64Extension = + new pb::Extension(6, pb::FieldCodec.ForSInt64(48, 0L)); + public static readonly pb::Extension OptionalFixed32Extension = + new pb::Extension(7, pb::FieldCodec.ForFixed32(61, 0)); + public static readonly pb::Extension OptionalFixed64Extension = + new pb::Extension(8, pb::FieldCodec.ForFixed64(65, 0UL)); + public static readonly pb::Extension OptionalSfixed32Extension = + new pb::Extension(9, pb::FieldCodec.ForSFixed32(77, 0)); + public static readonly pb::Extension OptionalSfixed64Extension = + new pb::Extension(10, pb::FieldCodec.ForSFixed64(81, 0L)); + public static readonly pb::Extension OptionalFloatExtension = + new pb::Extension(11, pb::FieldCodec.ForFloat(93, 0F)); + public static readonly pb::Extension OptionalDoubleExtension = + new pb::Extension(12, pb::FieldCodec.ForDouble(97, 0D)); + public static readonly pb::Extension OptionalBoolExtension = + new pb::Extension(13, pb::FieldCodec.ForBool(104, false)); + public static readonly pb::Extension OptionalStringExtension = + new pb::Extension(14, pb::FieldCodec.ForString(114, "")); + public static readonly pb::Extension OptionalBytesExtension = + new pb::Extension(15, pb::FieldCodec.ForBytes(122, pb::ByteString.Empty)); + public static readonly pb::Extension OptionalGroupExtension = + new pb::Extension(16, pb::FieldCodec.ForGroup(131, 132, global::Google.Protobuf.TestProtos.Proto2.OptionalGroup_extension.Parser)); + public static readonly pb::Extension OptionalNestedMessageExtension = + new pb::Extension(18, pb::FieldCodec.ForMessage(146, global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage.Parser)); + public static readonly pb::Extension OptionalForeignMessageExtension = + new pb::Extension(19, pb::FieldCodec.ForMessage(154, global::Google.Protobuf.TestProtos.Proto2.ForeignMessage.Parser)); + public static readonly pb::Extension OptionalImportMessageExtension = + new pb::Extension(20, pb::FieldCodec.ForMessage(162, global::Google.Protobuf.TestProtos.Proto2.ImportMessage.Parser)); + public static readonly pb::Extension OptionalNestedEnumExtension = + new pb::Extension(21, pb::FieldCodec.ForEnum(168, x => (int) x, x => (global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedEnum) x, global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedEnum.Foo)); + public static readonly pb::Extension OptionalForeignEnumExtension = + new pb::Extension(22, pb::FieldCodec.ForEnum(176, x => (int) x, x => (global::Google.Protobuf.TestProtos.Proto2.ForeignEnum) x, global::Google.Protobuf.TestProtos.Proto2.ForeignEnum.ForeignFoo)); + public static readonly pb::Extension OptionalImportEnumExtension = + new pb::Extension(23, pb::FieldCodec.ForEnum(184, x => (int) x, x => (global::Google.Protobuf.TestProtos.Proto2.ImportEnum) x, global::Google.Protobuf.TestProtos.Proto2.ImportEnum.ImportFoo)); + public static readonly pb::Extension OptionalStringPieceExtension = + new pb::Extension(24, pb::FieldCodec.ForString(194, "")); + public static readonly pb::Extension OptionalCordExtension = + new pb::Extension(25, pb::FieldCodec.ForString(202, "")); + public static readonly pb::Extension OptionalPublicImportMessageExtension = + new pb::Extension(26, pb::FieldCodec.ForMessage(210, global::Google.Protobuf.TestProtos.Proto2.PublicImportMessage.Parser)); + public static readonly pb::Extension OptionalLazyMessageExtension = + new pb::Extension(27, pb::FieldCodec.ForMessage(218, global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage.Parser)); + /// + /// Repeated + /// + public static readonly pb::RepeatedExtension RepeatedInt32Extension = + new pb::RepeatedExtension(31, pb::FieldCodec.ForInt32(248)); + public static readonly pb::RepeatedExtension RepeatedInt64Extension = + new pb::RepeatedExtension(32, pb::FieldCodec.ForInt64(256)); + public static readonly pb::RepeatedExtension RepeatedUint32Extension = + new pb::RepeatedExtension(33, pb::FieldCodec.ForUInt32(264)); + public static readonly pb::RepeatedExtension RepeatedUint64Extension = + new pb::RepeatedExtension(34, pb::FieldCodec.ForUInt64(272)); + public static readonly pb::RepeatedExtension RepeatedSint32Extension = + new pb::RepeatedExtension(35, pb::FieldCodec.ForSInt32(280)); + public static readonly pb::RepeatedExtension RepeatedSint64Extension = + new pb::RepeatedExtension(36, pb::FieldCodec.ForSInt64(288)); + public static readonly pb::RepeatedExtension RepeatedFixed32Extension = + new pb::RepeatedExtension(37, pb::FieldCodec.ForFixed32(301)); + public static readonly pb::RepeatedExtension RepeatedFixed64Extension = + new pb::RepeatedExtension(38, pb::FieldCodec.ForFixed64(305)); + public static readonly pb::RepeatedExtension RepeatedSfixed32Extension = + new pb::RepeatedExtension(39, pb::FieldCodec.ForSFixed32(317)); + public static readonly pb::RepeatedExtension RepeatedSfixed64Extension = + new pb::RepeatedExtension(40, pb::FieldCodec.ForSFixed64(321)); + public static readonly pb::RepeatedExtension RepeatedFloatExtension = + new pb::RepeatedExtension(41, pb::FieldCodec.ForFloat(333)); + public static readonly pb::RepeatedExtension RepeatedDoubleExtension = + new pb::RepeatedExtension(42, pb::FieldCodec.ForDouble(337)); + public static readonly pb::RepeatedExtension RepeatedBoolExtension = + new pb::RepeatedExtension(43, pb::FieldCodec.ForBool(344)); + public static readonly pb::RepeatedExtension RepeatedStringExtension = + new pb::RepeatedExtension(44, pb::FieldCodec.ForString(354)); + public static readonly pb::RepeatedExtension RepeatedBytesExtension = + new pb::RepeatedExtension(45, pb::FieldCodec.ForBytes(362)); + public static readonly pb::RepeatedExtension RepeatedGroupExtension = + new pb::RepeatedExtension(46, pb::FieldCodec.ForGroup(371, 372, global::Google.Protobuf.TestProtos.Proto2.RepeatedGroup_extension.Parser)); + public static readonly pb::RepeatedExtension RepeatedNestedMessageExtension = + new pb::RepeatedExtension(48, pb::FieldCodec.ForMessage(386, global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage.Parser)); + public static readonly pb::RepeatedExtension RepeatedForeignMessageExtension = + new pb::RepeatedExtension(49, pb::FieldCodec.ForMessage(394, global::Google.Protobuf.TestProtos.Proto2.ForeignMessage.Parser)); + public static readonly pb::RepeatedExtension RepeatedImportMessageExtension = + new pb::RepeatedExtension(50, pb::FieldCodec.ForMessage(402, global::Google.Protobuf.TestProtos.Proto2.ImportMessage.Parser)); + public static readonly pb::RepeatedExtension RepeatedNestedEnumExtension = + new pb::RepeatedExtension(51, pb::FieldCodec.ForEnum(408, x => (int) x, x => (global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedEnum) x)); + public static readonly pb::RepeatedExtension RepeatedForeignEnumExtension = + new pb::RepeatedExtension(52, pb::FieldCodec.ForEnum(416, x => (int) x, x => (global::Google.Protobuf.TestProtos.Proto2.ForeignEnum) x)); + public static readonly pb::RepeatedExtension RepeatedImportEnumExtension = + new pb::RepeatedExtension(53, pb::FieldCodec.ForEnum(424, x => (int) x, x => (global::Google.Protobuf.TestProtos.Proto2.ImportEnum) x)); + public static readonly pb::RepeatedExtension RepeatedStringPieceExtension = + new pb::RepeatedExtension(54, pb::FieldCodec.ForString(434)); + public static readonly pb::RepeatedExtension RepeatedCordExtension = + new pb::RepeatedExtension(55, pb::FieldCodec.ForString(442)); + public static readonly pb::RepeatedExtension RepeatedLazyMessageExtension = + new pb::RepeatedExtension(57, pb::FieldCodec.ForMessage(458, global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage.Parser)); + /// + /// Singular with defaults + /// + public static readonly pb::Extension DefaultInt32Extension = + new pb::Extension(61, pb::FieldCodec.ForInt32(488, 41)); + public static readonly pb::Extension DefaultInt64Extension = + new pb::Extension(62, pb::FieldCodec.ForInt64(496, 42L)); + public static readonly pb::Extension DefaultUint32Extension = + new pb::Extension(63, pb::FieldCodec.ForUInt32(504, 43)); + public static readonly pb::Extension DefaultUint64Extension = + new pb::Extension(64, pb::FieldCodec.ForUInt64(512, 44UL)); + public static readonly pb::Extension DefaultSint32Extension = + new pb::Extension(65, pb::FieldCodec.ForSInt32(520, -45)); + public static readonly pb::Extension DefaultSint64Extension = + new pb::Extension(66, pb::FieldCodec.ForSInt64(528, 46L)); + public static readonly pb::Extension DefaultFixed32Extension = + new pb::Extension(67, pb::FieldCodec.ForFixed32(541, 47)); + public static readonly pb::Extension DefaultFixed64Extension = + new pb::Extension(68, pb::FieldCodec.ForFixed64(545, 48UL)); + public static readonly pb::Extension DefaultSfixed32Extension = + new pb::Extension(69, pb::FieldCodec.ForSFixed32(557, 49)); + public static readonly pb::Extension DefaultSfixed64Extension = + new pb::Extension(70, pb::FieldCodec.ForSFixed64(561, -50L)); + public static readonly pb::Extension DefaultFloatExtension = + new pb::Extension(71, pb::FieldCodec.ForFloat(573, 51.5F)); + public static readonly pb::Extension DefaultDoubleExtension = + new pb::Extension(72, pb::FieldCodec.ForDouble(577, 52000D)); + public static readonly pb::Extension DefaultBoolExtension = + new pb::Extension(73, pb::FieldCodec.ForBool(584, true)); + public static readonly pb::Extension DefaultStringExtension = + new pb::Extension(74, pb::FieldCodec.ForString(594, global::System.Text.Encoding.UTF8.GetString(global::System.Convert.FromBase64String("aGVsbG8="), 0, 5))); + public static readonly pb::Extension DefaultBytesExtension = + new pb::Extension(75, pb::FieldCodec.ForBytes(602, pb::ByteString.FromBase64("d29ybGQ="))); + public static readonly pb::Extension DefaultNestedEnumExtension = + new pb::Extension(81, pb::FieldCodec.ForEnum(648, x => (int) x, x => (global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedEnum) x, global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedEnum.Bar)); + public static readonly pb::Extension DefaultForeignEnumExtension = + new pb::Extension(82, pb::FieldCodec.ForEnum(656, x => (int) x, x => (global::Google.Protobuf.TestProtos.Proto2.ForeignEnum) x, global::Google.Protobuf.TestProtos.Proto2.ForeignEnum.ForeignBar)); + public static readonly pb::Extension DefaultImportEnumExtension = + new pb::Extension(83, pb::FieldCodec.ForEnum(664, x => (int) x, x => (global::Google.Protobuf.TestProtos.Proto2.ImportEnum) x, global::Google.Protobuf.TestProtos.Proto2.ImportEnum.ImportBar)); + public static readonly pb::Extension DefaultStringPieceExtension = + new pb::Extension(84, pb::FieldCodec.ForString(674, global::System.Text.Encoding.UTF8.GetString(global::System.Convert.FromBase64String("YWJj"), 0, 3))); + public static readonly pb::Extension DefaultCordExtension = + new pb::Extension(85, pb::FieldCodec.ForString(682, global::System.Text.Encoding.UTF8.GetString(global::System.Convert.FromBase64String("MTIz"), 0, 3))); + /// + /// For oneof test + /// + public static readonly pb::Extension OneofUint32Extension = + new pb::Extension(111, pb::FieldCodec.ForUInt32(888, 0)); + public static readonly pb::Extension OneofNestedMessageExtension = + new pb::Extension(112, pb::FieldCodec.ForMessage(898, global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage.Parser)); + public static readonly pb::Extension OneofStringExtension = + new pb::Extension(113, pb::FieldCodec.ForString(906, "")); + public static readonly pb::Extension OneofBytesExtension = + new pb::Extension(114, pb::FieldCodec.ForBytes(914, pb::ByteString.Empty)); + public static readonly pb::Extension MyExtensionString = + new pb::Extension(50, pb::FieldCodec.ForString(402, "")); + public static readonly pb::Extension MyExtensionInt = + new pb::Extension(5, pb::FieldCodec.ForInt32(40, 0)); + public static readonly pb::RepeatedExtension PackedInt32Extension = + new pb::RepeatedExtension(90, pb::FieldCodec.ForInt32(722)); + public static readonly pb::RepeatedExtension PackedInt64Extension = + new pb::RepeatedExtension(91, pb::FieldCodec.ForInt64(730)); + public static readonly pb::RepeatedExtension PackedUint32Extension = + new pb::RepeatedExtension(92, pb::FieldCodec.ForUInt32(738)); + public static readonly pb::RepeatedExtension PackedUint64Extension = + new pb::RepeatedExtension(93, pb::FieldCodec.ForUInt64(746)); + public static readonly pb::RepeatedExtension PackedSint32Extension = + new pb::RepeatedExtension(94, pb::FieldCodec.ForSInt32(754)); + public static readonly pb::RepeatedExtension PackedSint64Extension = + new pb::RepeatedExtension(95, pb::FieldCodec.ForSInt64(762)); + public static readonly pb::RepeatedExtension PackedFixed32Extension = + new pb::RepeatedExtension(96, pb::FieldCodec.ForFixed32(770)); + public static readonly pb::RepeatedExtension PackedFixed64Extension = + new pb::RepeatedExtension(97, pb::FieldCodec.ForFixed64(778)); + public static readonly pb::RepeatedExtension PackedSfixed32Extension = + new pb::RepeatedExtension(98, pb::FieldCodec.ForSFixed32(786)); + public static readonly pb::RepeatedExtension PackedSfixed64Extension = + new pb::RepeatedExtension(99, pb::FieldCodec.ForSFixed64(794)); + public static readonly pb::RepeatedExtension PackedFloatExtension = + new pb::RepeatedExtension(100, pb::FieldCodec.ForFloat(802)); + public static readonly pb::RepeatedExtension PackedDoubleExtension = + new pb::RepeatedExtension(101, pb::FieldCodec.ForDouble(810)); + public static readonly pb::RepeatedExtension PackedBoolExtension = + new pb::RepeatedExtension(102, pb::FieldCodec.ForBool(818)); + public static readonly pb::RepeatedExtension PackedEnumExtension = + new pb::RepeatedExtension(103, pb::FieldCodec.ForEnum(826, x => (int) x, x => (global::Google.Protobuf.TestProtos.Proto2.ForeignEnum) x)); + public static readonly pb::RepeatedExtension UnpackedInt32Extension = + new pb::RepeatedExtension(90, pb::FieldCodec.ForInt32(720)); + public static readonly pb::RepeatedExtension UnpackedInt64Extension = + new pb::RepeatedExtension(91, pb::FieldCodec.ForInt64(728)); + public static readonly pb::RepeatedExtension UnpackedUint32Extension = + new pb::RepeatedExtension(92, pb::FieldCodec.ForUInt32(736)); + public static readonly pb::RepeatedExtension UnpackedUint64Extension = + new pb::RepeatedExtension(93, pb::FieldCodec.ForUInt64(744)); + public static readonly pb::RepeatedExtension UnpackedSint32Extension = + new pb::RepeatedExtension(94, pb::FieldCodec.ForSInt32(752)); + public static readonly pb::RepeatedExtension UnpackedSint64Extension = + new pb::RepeatedExtension(95, pb::FieldCodec.ForSInt64(760)); + public static readonly pb::RepeatedExtension UnpackedFixed32Extension = + new pb::RepeatedExtension(96, pb::FieldCodec.ForFixed32(773)); + public static readonly pb::RepeatedExtension UnpackedFixed64Extension = + new pb::RepeatedExtension(97, pb::FieldCodec.ForFixed64(777)); + public static readonly pb::RepeatedExtension UnpackedSfixed32Extension = + new pb::RepeatedExtension(98, pb::FieldCodec.ForSFixed32(789)); + public static readonly pb::RepeatedExtension UnpackedSfixed64Extension = + new pb::RepeatedExtension(99, pb::FieldCodec.ForSFixed64(793)); + public static readonly pb::RepeatedExtension UnpackedFloatExtension = + new pb::RepeatedExtension(100, pb::FieldCodec.ForFloat(805)); + public static readonly pb::RepeatedExtension UnpackedDoubleExtension = + new pb::RepeatedExtension(101, pb::FieldCodec.ForDouble(809)); + public static readonly pb::RepeatedExtension UnpackedBoolExtension = + new pb::RepeatedExtension(102, pb::FieldCodec.ForBool(816)); + public static readonly pb::RepeatedExtension UnpackedEnumExtension = + new pb::RepeatedExtension(103, pb::FieldCodec.ForEnum(824, x => (int) x, x => (global::Google.Protobuf.TestProtos.Proto2.ForeignEnum) x)); + public static readonly pb::Extension TestAllTypes = + new pb::Extension(536860000, pb::FieldCodec.ForMessage(4294880002, global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Parser)); + public static readonly pb::Extension TestExtensionInsideTableExtension = + new pb::Extension(5, pb::FieldCodec.ForInt32(40, 0)); + } + + #region Enums + public enum ForeignEnum { + [pbr::OriginalName("FOREIGN_FOO")] ForeignFoo = 4, + [pbr::OriginalName("FOREIGN_BAR")] ForeignBar = 5, + [pbr::OriginalName("FOREIGN_BAZ")] ForeignBaz = 6, + } + + /// + /// Test an enum that has multiple values with the same number. + /// + public enum TestEnumWithDupValue { + [pbr::OriginalName("FOO1")] Foo1 = 1, + [pbr::OriginalName("BAR1")] Bar1 = 2, + [pbr::OriginalName("BAZ")] Baz = 3, + [pbr::OriginalName("FOO2", PreferredAlias = false)] Foo2 = 1, + [pbr::OriginalName("BAR2", PreferredAlias = false)] Bar2 = 2, + } + + /// + /// Test an enum with large, unordered values. + /// + public enum TestSparseEnum { + [pbr::OriginalName("SPARSE_A")] SparseA = 123, + [pbr::OriginalName("SPARSE_B")] SparseB = 62374, + [pbr::OriginalName("SPARSE_C")] SparseC = 12589234, + [pbr::OriginalName("SPARSE_D")] SparseD = -15, + [pbr::OriginalName("SPARSE_E")] SparseE = -53452, + [pbr::OriginalName("SPARSE_F")] SparseF = 0, + [pbr::OriginalName("SPARSE_G")] SparseG = 2, + } + + public enum VeryLargeEnum { + [pbr::OriginalName("ENUM_LABEL_DEFAULT")] EnumLabelDefault = 0, + [pbr::OriginalName("ENUM_LABEL_1")] EnumLabel1 = 1, + [pbr::OriginalName("ENUM_LABEL_2")] EnumLabel2 = 2, + [pbr::OriginalName("ENUM_LABEL_3")] EnumLabel3 = 3, + [pbr::OriginalName("ENUM_LABEL_4")] EnumLabel4 = 4, + [pbr::OriginalName("ENUM_LABEL_5")] EnumLabel5 = 5, + [pbr::OriginalName("ENUM_LABEL_6")] EnumLabel6 = 6, + [pbr::OriginalName("ENUM_LABEL_7")] EnumLabel7 = 7, + [pbr::OriginalName("ENUM_LABEL_8")] EnumLabel8 = 8, + [pbr::OriginalName("ENUM_LABEL_9")] EnumLabel9 = 9, + [pbr::OriginalName("ENUM_LABEL_10")] EnumLabel10 = 10, + [pbr::OriginalName("ENUM_LABEL_11")] EnumLabel11 = 11, + [pbr::OriginalName("ENUM_LABEL_12")] EnumLabel12 = 12, + [pbr::OriginalName("ENUM_LABEL_13")] EnumLabel13 = 13, + [pbr::OriginalName("ENUM_LABEL_14")] EnumLabel14 = 14, + [pbr::OriginalName("ENUM_LABEL_15")] EnumLabel15 = 15, + [pbr::OriginalName("ENUM_LABEL_16")] EnumLabel16 = 16, + [pbr::OriginalName("ENUM_LABEL_17")] EnumLabel17 = 17, + [pbr::OriginalName("ENUM_LABEL_18")] EnumLabel18 = 18, + [pbr::OriginalName("ENUM_LABEL_19")] EnumLabel19 = 19, + [pbr::OriginalName("ENUM_LABEL_20")] EnumLabel20 = 20, + [pbr::OriginalName("ENUM_LABEL_21")] EnumLabel21 = 21, + [pbr::OriginalName("ENUM_LABEL_22")] EnumLabel22 = 22, + [pbr::OriginalName("ENUM_LABEL_23")] EnumLabel23 = 23, + [pbr::OriginalName("ENUM_LABEL_24")] EnumLabel24 = 24, + [pbr::OriginalName("ENUM_LABEL_25")] EnumLabel25 = 25, + [pbr::OriginalName("ENUM_LABEL_26")] EnumLabel26 = 26, + [pbr::OriginalName("ENUM_LABEL_27")] EnumLabel27 = 27, + [pbr::OriginalName("ENUM_LABEL_28")] EnumLabel28 = 28, + [pbr::OriginalName("ENUM_LABEL_29")] EnumLabel29 = 29, + [pbr::OriginalName("ENUM_LABEL_30")] EnumLabel30 = 30, + [pbr::OriginalName("ENUM_LABEL_31")] EnumLabel31 = 31, + [pbr::OriginalName("ENUM_LABEL_32")] EnumLabel32 = 32, + [pbr::OriginalName("ENUM_LABEL_33")] EnumLabel33 = 33, + [pbr::OriginalName("ENUM_LABEL_34")] EnumLabel34 = 34, + [pbr::OriginalName("ENUM_LABEL_35")] EnumLabel35 = 35, + [pbr::OriginalName("ENUM_LABEL_36")] EnumLabel36 = 36, + [pbr::OriginalName("ENUM_LABEL_37")] EnumLabel37 = 37, + [pbr::OriginalName("ENUM_LABEL_38")] EnumLabel38 = 38, + [pbr::OriginalName("ENUM_LABEL_39")] EnumLabel39 = 39, + [pbr::OriginalName("ENUM_LABEL_40")] EnumLabel40 = 40, + [pbr::OriginalName("ENUM_LABEL_41")] EnumLabel41 = 41, + [pbr::OriginalName("ENUM_LABEL_42")] EnumLabel42 = 42, + [pbr::OriginalName("ENUM_LABEL_43")] EnumLabel43 = 43, + [pbr::OriginalName("ENUM_LABEL_44")] EnumLabel44 = 44, + [pbr::OriginalName("ENUM_LABEL_45")] EnumLabel45 = 45, + [pbr::OriginalName("ENUM_LABEL_46")] EnumLabel46 = 46, + [pbr::OriginalName("ENUM_LABEL_47")] EnumLabel47 = 47, + [pbr::OriginalName("ENUM_LABEL_48")] EnumLabel48 = 48, + [pbr::OriginalName("ENUM_LABEL_49")] EnumLabel49 = 49, + [pbr::OriginalName("ENUM_LABEL_50")] EnumLabel50 = 50, + [pbr::OriginalName("ENUM_LABEL_51")] EnumLabel51 = 51, + [pbr::OriginalName("ENUM_LABEL_52")] EnumLabel52 = 52, + [pbr::OriginalName("ENUM_LABEL_53")] EnumLabel53 = 53, + [pbr::OriginalName("ENUM_LABEL_54")] EnumLabel54 = 54, + [pbr::OriginalName("ENUM_LABEL_55")] EnumLabel55 = 55, + [pbr::OriginalName("ENUM_LABEL_56")] EnumLabel56 = 56, + [pbr::OriginalName("ENUM_LABEL_57")] EnumLabel57 = 57, + [pbr::OriginalName("ENUM_LABEL_58")] EnumLabel58 = 58, + [pbr::OriginalName("ENUM_LABEL_59")] EnumLabel59 = 59, + [pbr::OriginalName("ENUM_LABEL_60")] EnumLabel60 = 60, + [pbr::OriginalName("ENUM_LABEL_61")] EnumLabel61 = 61, + [pbr::OriginalName("ENUM_LABEL_62")] EnumLabel62 = 62, + [pbr::OriginalName("ENUM_LABEL_63")] EnumLabel63 = 63, + [pbr::OriginalName("ENUM_LABEL_64")] EnumLabel64 = 64, + [pbr::OriginalName("ENUM_LABEL_65")] EnumLabel65 = 65, + [pbr::OriginalName("ENUM_LABEL_66")] EnumLabel66 = 66, + [pbr::OriginalName("ENUM_LABEL_67")] EnumLabel67 = 67, + [pbr::OriginalName("ENUM_LABEL_68")] EnumLabel68 = 68, + [pbr::OriginalName("ENUM_LABEL_69")] EnumLabel69 = 69, + [pbr::OriginalName("ENUM_LABEL_70")] EnumLabel70 = 70, + [pbr::OriginalName("ENUM_LABEL_71")] EnumLabel71 = 71, + [pbr::OriginalName("ENUM_LABEL_72")] EnumLabel72 = 72, + [pbr::OriginalName("ENUM_LABEL_73")] EnumLabel73 = 73, + [pbr::OriginalName("ENUM_LABEL_74")] EnumLabel74 = 74, + [pbr::OriginalName("ENUM_LABEL_75")] EnumLabel75 = 75, + [pbr::OriginalName("ENUM_LABEL_76")] EnumLabel76 = 76, + [pbr::OriginalName("ENUM_LABEL_77")] EnumLabel77 = 77, + [pbr::OriginalName("ENUM_LABEL_78")] EnumLabel78 = 78, + [pbr::OriginalName("ENUM_LABEL_79")] EnumLabel79 = 79, + [pbr::OriginalName("ENUM_LABEL_80")] EnumLabel80 = 80, + [pbr::OriginalName("ENUM_LABEL_81")] EnumLabel81 = 81, + [pbr::OriginalName("ENUM_LABEL_82")] EnumLabel82 = 82, + [pbr::OriginalName("ENUM_LABEL_83")] EnumLabel83 = 83, + [pbr::OriginalName("ENUM_LABEL_84")] EnumLabel84 = 84, + [pbr::OriginalName("ENUM_LABEL_85")] EnumLabel85 = 85, + [pbr::OriginalName("ENUM_LABEL_86")] EnumLabel86 = 86, + [pbr::OriginalName("ENUM_LABEL_87")] EnumLabel87 = 87, + [pbr::OriginalName("ENUM_LABEL_88")] EnumLabel88 = 88, + [pbr::OriginalName("ENUM_LABEL_89")] EnumLabel89 = 89, + [pbr::OriginalName("ENUM_LABEL_90")] EnumLabel90 = 90, + [pbr::OriginalName("ENUM_LABEL_91")] EnumLabel91 = 91, + [pbr::OriginalName("ENUM_LABEL_92")] EnumLabel92 = 92, + [pbr::OriginalName("ENUM_LABEL_93")] EnumLabel93 = 93, + [pbr::OriginalName("ENUM_LABEL_94")] EnumLabel94 = 94, + [pbr::OriginalName("ENUM_LABEL_95")] EnumLabel95 = 95, + [pbr::OriginalName("ENUM_LABEL_96")] EnumLabel96 = 96, + [pbr::OriginalName("ENUM_LABEL_97")] EnumLabel97 = 97, + [pbr::OriginalName("ENUM_LABEL_98")] EnumLabel98 = 98, + [pbr::OriginalName("ENUM_LABEL_99")] EnumLabel99 = 99, + [pbr::OriginalName("ENUM_LABEL_100")] EnumLabel100 = 100, + } + + #endregion + + #region Messages + /// + /// This proto includes every type of field in both singular and repeated + /// forms. + /// + public sealed partial class TestAllTypes : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestAllTypes()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + private int _hasBits1; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestAllTypes() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestAllTypes(TestAllTypes other) : this() { + _hasBits0 = other._hasBits0; + _hasBits1 = other._hasBits1; + optionalInt32_ = other.optionalInt32_; + optionalInt64_ = other.optionalInt64_; + optionalUint32_ = other.optionalUint32_; + optionalUint64_ = other.optionalUint64_; + optionalSint32_ = other.optionalSint32_; + optionalSint64_ = other.optionalSint64_; + optionalFixed32_ = other.optionalFixed32_; + optionalFixed64_ = other.optionalFixed64_; + optionalSfixed32_ = other.optionalSfixed32_; + optionalSfixed64_ = other.optionalSfixed64_; + optionalFloat_ = other.optionalFloat_; + optionalDouble_ = other.optionalDouble_; + optionalBool_ = other.optionalBool_; + optionalString_ = other.optionalString_; + optionalBytes_ = other.optionalBytes_; + optionalGroup_ = other.HasOptionalGroup ? other.optionalGroup_.Clone() : null; + optionalNestedMessage_ = other.optionalNestedMessage_ != null ? other.optionalNestedMessage_.Clone() : null; + optionalForeignMessage_ = other.optionalForeignMessage_ != null ? other.optionalForeignMessage_.Clone() : null; + optionalImportMessage_ = other.optionalImportMessage_ != null ? other.optionalImportMessage_.Clone() : null; + optionalNestedEnum_ = other.optionalNestedEnum_; + optionalForeignEnum_ = other.optionalForeignEnum_; + optionalImportEnum_ = other.optionalImportEnum_; + optionalStringPiece_ = other.optionalStringPiece_; + optionalCord_ = other.optionalCord_; + optionalPublicImportMessage_ = other.optionalPublicImportMessage_ != null ? other.optionalPublicImportMessage_.Clone() : null; + optionalLazyMessage_ = other.optionalLazyMessage_ != null ? other.optionalLazyMessage_.Clone() : null; + repeatedInt32_ = other.repeatedInt32_.Clone(); + repeatedInt64_ = other.repeatedInt64_.Clone(); + repeatedUint32_ = other.repeatedUint32_.Clone(); + repeatedUint64_ = other.repeatedUint64_.Clone(); + repeatedSint32_ = other.repeatedSint32_.Clone(); + repeatedSint64_ = other.repeatedSint64_.Clone(); + repeatedFixed32_ = other.repeatedFixed32_.Clone(); + repeatedFixed64_ = other.repeatedFixed64_.Clone(); + repeatedSfixed32_ = other.repeatedSfixed32_.Clone(); + repeatedSfixed64_ = other.repeatedSfixed64_.Clone(); + repeatedFloat_ = other.repeatedFloat_.Clone(); + repeatedDouble_ = other.repeatedDouble_.Clone(); + repeatedBool_ = other.repeatedBool_.Clone(); + repeatedString_ = other.repeatedString_.Clone(); + repeatedBytes_ = other.repeatedBytes_.Clone(); + repeatedGroup_ = other.repeatedGroup_.Clone(); + repeatedNestedMessage_ = other.repeatedNestedMessage_.Clone(); + repeatedForeignMessage_ = other.repeatedForeignMessage_.Clone(); + repeatedImportMessage_ = other.repeatedImportMessage_.Clone(); + repeatedNestedEnum_ = other.repeatedNestedEnum_.Clone(); + repeatedForeignEnum_ = other.repeatedForeignEnum_.Clone(); + repeatedImportEnum_ = other.repeatedImportEnum_.Clone(); + repeatedStringPiece_ = other.repeatedStringPiece_.Clone(); + repeatedCord_ = other.repeatedCord_.Clone(); + repeatedLazyMessage_ = other.repeatedLazyMessage_.Clone(); + defaultInt32_ = other.defaultInt32_; + defaultInt64_ = other.defaultInt64_; + defaultUint32_ = other.defaultUint32_; + defaultUint64_ = other.defaultUint64_; + defaultSint32_ = other.defaultSint32_; + defaultSint64_ = other.defaultSint64_; + defaultFixed32_ = other.defaultFixed32_; + defaultFixed64_ = other.defaultFixed64_; + defaultSfixed32_ = other.defaultSfixed32_; + defaultSfixed64_ = other.defaultSfixed64_; + defaultFloat_ = other.defaultFloat_; + defaultDouble_ = other.defaultDouble_; + defaultBool_ = other.defaultBool_; + defaultString_ = other.defaultString_; + defaultBytes_ = other.defaultBytes_; + defaultNestedEnum_ = other.defaultNestedEnum_; + defaultForeignEnum_ = other.defaultForeignEnum_; + defaultImportEnum_ = other.defaultImportEnum_; + defaultStringPiece_ = other.defaultStringPiece_; + defaultCord_ = other.defaultCord_; + switch (other.OneofFieldCase) { + case OneofFieldOneofCase.OneofUint32: + OneofUint32 = other.OneofUint32; + break; + case OneofFieldOneofCase.OneofNestedMessage: + OneofNestedMessage = other.OneofNestedMessage.Clone(); + break; + case OneofFieldOneofCase.OneofString: + OneofString = other.OneofString; + break; + case OneofFieldOneofCase.OneofBytes: + OneofBytes = other.OneofBytes; + break; + } + + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestAllTypes Clone() { + return new TestAllTypes(this); + } + + /// Field number for the "optional_int32" field. + public const int OptionalInt32FieldNumber = 1; + private readonly static int OptionalInt32DefaultValue = 0; + + private int optionalInt32_; + /// + /// Singular + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int OptionalInt32 { + get { if ((_hasBits0 & 1) != 0) { return optionalInt32_; } else { return OptionalInt32DefaultValue; } } + set { + _hasBits0 |= 1; + optionalInt32_ = value; + } + } + /// Gets whether the "optional_int32" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalInt32 { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "optional_int32" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalInt32() { + _hasBits0 &= ~1; + } + + /// Field number for the "optional_int64" field. + public const int OptionalInt64FieldNumber = 2; + private readonly static long OptionalInt64DefaultValue = 0L; + + private long optionalInt64_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public long OptionalInt64 { + get { if ((_hasBits0 & 2) != 0) { return optionalInt64_; } else { return OptionalInt64DefaultValue; } } + set { + _hasBits0 |= 2; + optionalInt64_ = value; + } + } + /// Gets whether the "optional_int64" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalInt64 { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "optional_int64" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalInt64() { + _hasBits0 &= ~2; + } + + /// Field number for the "optional_uint32" field. + public const int OptionalUint32FieldNumber = 3; + private readonly static uint OptionalUint32DefaultValue = 0; + + private uint optionalUint32_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public uint OptionalUint32 { + get { if ((_hasBits0 & 4) != 0) { return optionalUint32_; } else { return OptionalUint32DefaultValue; } } + set { + _hasBits0 |= 4; + optionalUint32_ = value; + } + } + /// Gets whether the "optional_uint32" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalUint32 { + get { return (_hasBits0 & 4) != 0; } + } + /// Clears the value of the "optional_uint32" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalUint32() { + _hasBits0 &= ~4; + } + + /// Field number for the "optional_uint64" field. + public const int OptionalUint64FieldNumber = 4; + private readonly static ulong OptionalUint64DefaultValue = 0UL; + + private ulong optionalUint64_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ulong OptionalUint64 { + get { if ((_hasBits0 & 8) != 0) { return optionalUint64_; } else { return OptionalUint64DefaultValue; } } + set { + _hasBits0 |= 8; + optionalUint64_ = value; + } + } + /// Gets whether the "optional_uint64" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalUint64 { + get { return (_hasBits0 & 8) != 0; } + } + /// Clears the value of the "optional_uint64" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalUint64() { + _hasBits0 &= ~8; + } + + /// Field number for the "optional_sint32" field. + public const int OptionalSint32FieldNumber = 5; + private readonly static int OptionalSint32DefaultValue = 0; + + private int optionalSint32_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int OptionalSint32 { + get { if ((_hasBits0 & 16) != 0) { return optionalSint32_; } else { return OptionalSint32DefaultValue; } } + set { + _hasBits0 |= 16; + optionalSint32_ = value; + } + } + /// Gets whether the "optional_sint32" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalSint32 { + get { return (_hasBits0 & 16) != 0; } + } + /// Clears the value of the "optional_sint32" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalSint32() { + _hasBits0 &= ~16; + } + + /// Field number for the "optional_sint64" field. + public const int OptionalSint64FieldNumber = 6; + private readonly static long OptionalSint64DefaultValue = 0L; + + private long optionalSint64_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public long OptionalSint64 { + get { if ((_hasBits0 & 32) != 0) { return optionalSint64_; } else { return OptionalSint64DefaultValue; } } + set { + _hasBits0 |= 32; + optionalSint64_ = value; + } + } + /// Gets whether the "optional_sint64" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalSint64 { + get { return (_hasBits0 & 32) != 0; } + } + /// Clears the value of the "optional_sint64" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalSint64() { + _hasBits0 &= ~32; + } + + /// Field number for the "optional_fixed32" field. + public const int OptionalFixed32FieldNumber = 7; + private readonly static uint OptionalFixed32DefaultValue = 0; + + private uint optionalFixed32_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public uint OptionalFixed32 { + get { if ((_hasBits0 & 64) != 0) { return optionalFixed32_; } else { return OptionalFixed32DefaultValue; } } + set { + _hasBits0 |= 64; + optionalFixed32_ = value; + } + } + /// Gets whether the "optional_fixed32" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalFixed32 { + get { return (_hasBits0 & 64) != 0; } + } + /// Clears the value of the "optional_fixed32" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalFixed32() { + _hasBits0 &= ~64; + } + + /// Field number for the "optional_fixed64" field. + public const int OptionalFixed64FieldNumber = 8; + private readonly static ulong OptionalFixed64DefaultValue = 0UL; + + private ulong optionalFixed64_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ulong OptionalFixed64 { + get { if ((_hasBits0 & 128) != 0) { return optionalFixed64_; } else { return OptionalFixed64DefaultValue; } } + set { + _hasBits0 |= 128; + optionalFixed64_ = value; + } + } + /// Gets whether the "optional_fixed64" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalFixed64 { + get { return (_hasBits0 & 128) != 0; } + } + /// Clears the value of the "optional_fixed64" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalFixed64() { + _hasBits0 &= ~128; + } + + /// Field number for the "optional_sfixed32" field. + public const int OptionalSfixed32FieldNumber = 9; + private readonly static int OptionalSfixed32DefaultValue = 0; + + private int optionalSfixed32_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int OptionalSfixed32 { + get { if ((_hasBits0 & 256) != 0) { return optionalSfixed32_; } else { return OptionalSfixed32DefaultValue; } } + set { + _hasBits0 |= 256; + optionalSfixed32_ = value; + } + } + /// Gets whether the "optional_sfixed32" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalSfixed32 { + get { return (_hasBits0 & 256) != 0; } + } + /// Clears the value of the "optional_sfixed32" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalSfixed32() { + _hasBits0 &= ~256; + } + + /// Field number for the "optional_sfixed64" field. + public const int OptionalSfixed64FieldNumber = 10; + private readonly static long OptionalSfixed64DefaultValue = 0L; + + private long optionalSfixed64_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public long OptionalSfixed64 { + get { if ((_hasBits0 & 512) != 0) { return optionalSfixed64_; } else { return OptionalSfixed64DefaultValue; } } + set { + _hasBits0 |= 512; + optionalSfixed64_ = value; + } + } + /// Gets whether the "optional_sfixed64" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalSfixed64 { + get { return (_hasBits0 & 512) != 0; } + } + /// Clears the value of the "optional_sfixed64" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalSfixed64() { + _hasBits0 &= ~512; + } + + /// Field number for the "optional_float" field. + public const int OptionalFloatFieldNumber = 11; + private readonly static float OptionalFloatDefaultValue = 0F; + + private float optionalFloat_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public float OptionalFloat { + get { if ((_hasBits0 & 1024) != 0) { return optionalFloat_; } else { return OptionalFloatDefaultValue; } } + set { + _hasBits0 |= 1024; + optionalFloat_ = value; + } + } + /// Gets whether the "optional_float" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalFloat { + get { return (_hasBits0 & 1024) != 0; } + } + /// Clears the value of the "optional_float" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalFloat() { + _hasBits0 &= ~1024; + } + + /// Field number for the "optional_double" field. + public const int OptionalDoubleFieldNumber = 12; + private readonly static double OptionalDoubleDefaultValue = 0D; + + private double optionalDouble_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public double OptionalDouble { + get { if ((_hasBits0 & 2048) != 0) { return optionalDouble_; } else { return OptionalDoubleDefaultValue; } } + set { + _hasBits0 |= 2048; + optionalDouble_ = value; + } + } + /// Gets whether the "optional_double" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalDouble { + get { return (_hasBits0 & 2048) != 0; } + } + /// Clears the value of the "optional_double" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalDouble() { + _hasBits0 &= ~2048; + } + + /// Field number for the "optional_bool" field. + public const int OptionalBoolFieldNumber = 13; + private readonly static bool OptionalBoolDefaultValue = false; + + private bool optionalBool_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool OptionalBool { + get { if ((_hasBits0 & 4096) != 0) { return optionalBool_; } else { return OptionalBoolDefaultValue; } } + set { + _hasBits0 |= 4096; + optionalBool_ = value; + } + } + /// Gets whether the "optional_bool" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalBool { + get { return (_hasBits0 & 4096) != 0; } + } + /// Clears the value of the "optional_bool" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalBool() { + _hasBits0 &= ~4096; + } + + /// Field number for the "optional_string" field. + public const int OptionalStringFieldNumber = 14; + private readonly static string OptionalStringDefaultValue = ""; + + private string optionalString_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string OptionalString { + get { return optionalString_ ?? OptionalStringDefaultValue; } + set { + optionalString_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "optional_string" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalString { + get { return optionalString_ != null; } + } + /// Clears the value of the "optional_string" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalString() { + optionalString_ = null; + } + + /// Field number for the "optional_bytes" field. + public const int OptionalBytesFieldNumber = 15; + private readonly static pb::ByteString OptionalBytesDefaultValue = pb::ByteString.Empty; + + private pb::ByteString optionalBytes_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pb::ByteString OptionalBytes { + get { return optionalBytes_ ?? OptionalBytesDefaultValue; } + set { + optionalBytes_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "optional_bytes" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalBytes { + get { return optionalBytes_ != null; } + } + /// Clears the value of the "optional_bytes" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalBytes() { + optionalBytes_ = null; + } + + /// Field number for the "optionalgroup" field. + public const int OptionalGroupFieldNumber = 16; + private global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.OptionalGroup optionalGroup_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.OptionalGroup OptionalGroup { + get { return optionalGroup_; } + set { + optionalGroup_ = value; + } + } + /// Gets whether the optionalgroup field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalGroup { + get { return optionalGroup_ != null; } + } + /// Clears the value of the optionalgroup field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalGroup() { + optionalGroup_ = null; + } + + /// Field number for the "optional_nested_message" field. + public const int OptionalNestedMessageFieldNumber = 18; + private global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage optionalNestedMessage_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage OptionalNestedMessage { + get { return optionalNestedMessage_; } + set { + optionalNestedMessage_ = value; + } + } + + /// Field number for the "optional_foreign_message" field. + public const int OptionalForeignMessageFieldNumber = 19; + private global::Google.Protobuf.TestProtos.Proto2.ForeignMessage optionalForeignMessage_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.ForeignMessage OptionalForeignMessage { + get { return optionalForeignMessage_; } + set { + optionalForeignMessage_ = value; + } + } + + /// Field number for the "optional_import_message" field. + public const int OptionalImportMessageFieldNumber = 20; + private global::Google.Protobuf.TestProtos.Proto2.ImportMessage optionalImportMessage_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.ImportMessage OptionalImportMessage { + get { return optionalImportMessage_; } + set { + optionalImportMessage_ = value; + } + } + + /// Field number for the "optional_nested_enum" field. + public const int OptionalNestedEnumFieldNumber = 21; + private readonly static global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedEnum OptionalNestedEnumDefaultValue = global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedEnum.Foo; + + private global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedEnum optionalNestedEnum_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedEnum OptionalNestedEnum { + get { if ((_hasBits0 & 8192) != 0) { return optionalNestedEnum_; } else { return OptionalNestedEnumDefaultValue; } } + set { + _hasBits0 |= 8192; + optionalNestedEnum_ = value; + } + } + /// Gets whether the "optional_nested_enum" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalNestedEnum { + get { return (_hasBits0 & 8192) != 0; } + } + /// Clears the value of the "optional_nested_enum" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalNestedEnum() { + _hasBits0 &= ~8192; + } + + /// Field number for the "optional_foreign_enum" field. + public const int OptionalForeignEnumFieldNumber = 22; + private readonly static global::Google.Protobuf.TestProtos.Proto2.ForeignEnum OptionalForeignEnumDefaultValue = global::Google.Protobuf.TestProtos.Proto2.ForeignEnum.ForeignFoo; + + private global::Google.Protobuf.TestProtos.Proto2.ForeignEnum optionalForeignEnum_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.ForeignEnum OptionalForeignEnum { + get { if ((_hasBits0 & 16384) != 0) { return optionalForeignEnum_; } else { return OptionalForeignEnumDefaultValue; } } + set { + _hasBits0 |= 16384; + optionalForeignEnum_ = value; + } + } + /// Gets whether the "optional_foreign_enum" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalForeignEnum { + get { return (_hasBits0 & 16384) != 0; } + } + /// Clears the value of the "optional_foreign_enum" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalForeignEnum() { + _hasBits0 &= ~16384; + } + + /// Field number for the "optional_import_enum" field. + public const int OptionalImportEnumFieldNumber = 23; + private readonly static global::Google.Protobuf.TestProtos.Proto2.ImportEnum OptionalImportEnumDefaultValue = global::Google.Protobuf.TestProtos.Proto2.ImportEnum.ImportFoo; + + private global::Google.Protobuf.TestProtos.Proto2.ImportEnum optionalImportEnum_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.ImportEnum OptionalImportEnum { + get { if ((_hasBits0 & 32768) != 0) { return optionalImportEnum_; } else { return OptionalImportEnumDefaultValue; } } + set { + _hasBits0 |= 32768; + optionalImportEnum_ = value; + } + } + /// Gets whether the "optional_import_enum" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalImportEnum { + get { return (_hasBits0 & 32768) != 0; } + } + /// Clears the value of the "optional_import_enum" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalImportEnum() { + _hasBits0 &= ~32768; + } + + /// Field number for the "optional_string_piece" field. + public const int OptionalStringPieceFieldNumber = 24; + private readonly static string OptionalStringPieceDefaultValue = ""; + + private string optionalStringPiece_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string OptionalStringPiece { + get { return optionalStringPiece_ ?? OptionalStringPieceDefaultValue; } + set { + optionalStringPiece_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "optional_string_piece" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalStringPiece { + get { return optionalStringPiece_ != null; } + } + /// Clears the value of the "optional_string_piece" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalStringPiece() { + optionalStringPiece_ = null; + } + + /// Field number for the "optional_cord" field. + public const int OptionalCordFieldNumber = 25; + private readonly static string OptionalCordDefaultValue = ""; + + private string optionalCord_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string OptionalCord { + get { return optionalCord_ ?? OptionalCordDefaultValue; } + set { + optionalCord_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "optional_cord" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalCord { + get { return optionalCord_ != null; } + } + /// Clears the value of the "optional_cord" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalCord() { + optionalCord_ = null; + } + + /// Field number for the "optional_public_import_message" field. + public const int OptionalPublicImportMessageFieldNumber = 26; + private global::Google.Protobuf.TestProtos.Proto2.PublicImportMessage optionalPublicImportMessage_; + /// + /// Defined in unittest_import_public.proto + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.PublicImportMessage OptionalPublicImportMessage { + get { return optionalPublicImportMessage_; } + set { + optionalPublicImportMessage_ = value; + } + } + + /// Field number for the "optional_lazy_message" field. + public const int OptionalLazyMessageFieldNumber = 27; + private global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage optionalLazyMessage_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage OptionalLazyMessage { + get { return optionalLazyMessage_; } + set { + optionalLazyMessage_ = value; + } + } + + /// Field number for the "repeated_int32" field. + public const int RepeatedInt32FieldNumber = 31; + private static readonly pb::FieldCodec _repeated_repeatedInt32_codec + = pb::FieldCodec.ForInt32(248); + private readonly pbc::RepeatedField repeatedInt32_ = new pbc::RepeatedField(); + /// + /// Repeated + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedInt32 { + get { return repeatedInt32_; } + } + + /// Field number for the "repeated_int64" field. + public const int RepeatedInt64FieldNumber = 32; + private static readonly pb::FieldCodec _repeated_repeatedInt64_codec + = pb::FieldCodec.ForInt64(256); + private readonly pbc::RepeatedField repeatedInt64_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedInt64 { + get { return repeatedInt64_; } + } + + /// Field number for the "repeated_uint32" field. + public const int RepeatedUint32FieldNumber = 33; + private static readonly pb::FieldCodec _repeated_repeatedUint32_codec + = pb::FieldCodec.ForUInt32(264); + private readonly pbc::RepeatedField repeatedUint32_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedUint32 { + get { return repeatedUint32_; } + } + + /// Field number for the "repeated_uint64" field. + public const int RepeatedUint64FieldNumber = 34; + private static readonly pb::FieldCodec _repeated_repeatedUint64_codec + = pb::FieldCodec.ForUInt64(272); + private readonly pbc::RepeatedField repeatedUint64_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedUint64 { + get { return repeatedUint64_; } + } + + /// Field number for the "repeated_sint32" field. + public const int RepeatedSint32FieldNumber = 35; + private static readonly pb::FieldCodec _repeated_repeatedSint32_codec + = pb::FieldCodec.ForSInt32(280); + private readonly pbc::RepeatedField repeatedSint32_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedSint32 { + get { return repeatedSint32_; } + } + + /// Field number for the "repeated_sint64" field. + public const int RepeatedSint64FieldNumber = 36; + private static readonly pb::FieldCodec _repeated_repeatedSint64_codec + = pb::FieldCodec.ForSInt64(288); + private readonly pbc::RepeatedField repeatedSint64_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedSint64 { + get { return repeatedSint64_; } + } + + /// Field number for the "repeated_fixed32" field. + public const int RepeatedFixed32FieldNumber = 37; + private static readonly pb::FieldCodec _repeated_repeatedFixed32_codec + = pb::FieldCodec.ForFixed32(301); + private readonly pbc::RepeatedField repeatedFixed32_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedFixed32 { + get { return repeatedFixed32_; } + } + + /// Field number for the "repeated_fixed64" field. + public const int RepeatedFixed64FieldNumber = 38; + private static readonly pb::FieldCodec _repeated_repeatedFixed64_codec + = pb::FieldCodec.ForFixed64(305); + private readonly pbc::RepeatedField repeatedFixed64_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedFixed64 { + get { return repeatedFixed64_; } + } + + /// Field number for the "repeated_sfixed32" field. + public const int RepeatedSfixed32FieldNumber = 39; + private static readonly pb::FieldCodec _repeated_repeatedSfixed32_codec + = pb::FieldCodec.ForSFixed32(317); + private readonly pbc::RepeatedField repeatedSfixed32_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedSfixed32 { + get { return repeatedSfixed32_; } + } + + /// Field number for the "repeated_sfixed64" field. + public const int RepeatedSfixed64FieldNumber = 40; + private static readonly pb::FieldCodec _repeated_repeatedSfixed64_codec + = pb::FieldCodec.ForSFixed64(321); + private readonly pbc::RepeatedField repeatedSfixed64_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedSfixed64 { + get { return repeatedSfixed64_; } + } + + /// Field number for the "repeated_float" field. + public const int RepeatedFloatFieldNumber = 41; + private static readonly pb::FieldCodec _repeated_repeatedFloat_codec + = pb::FieldCodec.ForFloat(333); + private readonly pbc::RepeatedField repeatedFloat_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedFloat { + get { return repeatedFloat_; } + } + + /// Field number for the "repeated_double" field. + public const int RepeatedDoubleFieldNumber = 42; + private static readonly pb::FieldCodec _repeated_repeatedDouble_codec + = pb::FieldCodec.ForDouble(337); + private readonly pbc::RepeatedField repeatedDouble_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedDouble { + get { return repeatedDouble_; } + } + + /// Field number for the "repeated_bool" field. + public const int RepeatedBoolFieldNumber = 43; + private static readonly pb::FieldCodec _repeated_repeatedBool_codec + = pb::FieldCodec.ForBool(344); + private readonly pbc::RepeatedField repeatedBool_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedBool { + get { return repeatedBool_; } + } + + /// Field number for the "repeated_string" field. + public const int RepeatedStringFieldNumber = 44; + private static readonly pb::FieldCodec _repeated_repeatedString_codec + = pb::FieldCodec.ForString(354); + private readonly pbc::RepeatedField repeatedString_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedString { + get { return repeatedString_; } + } + + /// Field number for the "repeated_bytes" field. + public const int RepeatedBytesFieldNumber = 45; + private static readonly pb::FieldCodec _repeated_repeatedBytes_codec + = pb::FieldCodec.ForBytes(362); + private readonly pbc::RepeatedField repeatedBytes_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedBytes { + get { return repeatedBytes_; } + } + + /// Field number for the "repeatedgroup" field. + public const int RepeatedGroupFieldNumber = 46; + private static readonly pb::FieldCodec _repeated_repeatedGroup_codec + = pb::FieldCodec.ForGroup(371, 372, global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.RepeatedGroup.Parser); + private readonly pbc::RepeatedField repeatedGroup_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedGroup { + get { return repeatedGroup_; } + } + + /// Field number for the "repeated_nested_message" field. + public const int RepeatedNestedMessageFieldNumber = 48; + private static readonly pb::FieldCodec _repeated_repeatedNestedMessage_codec + = pb::FieldCodec.ForMessage(386, global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage.Parser); + private readonly pbc::RepeatedField repeatedNestedMessage_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedNestedMessage { + get { return repeatedNestedMessage_; } + } + + /// Field number for the "repeated_foreign_message" field. + public const int RepeatedForeignMessageFieldNumber = 49; + private static readonly pb::FieldCodec _repeated_repeatedForeignMessage_codec + = pb::FieldCodec.ForMessage(394, global::Google.Protobuf.TestProtos.Proto2.ForeignMessage.Parser); + private readonly pbc::RepeatedField repeatedForeignMessage_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedForeignMessage { + get { return repeatedForeignMessage_; } + } + + /// Field number for the "repeated_import_message" field. + public const int RepeatedImportMessageFieldNumber = 50; + private static readonly pb::FieldCodec _repeated_repeatedImportMessage_codec + = pb::FieldCodec.ForMessage(402, global::Google.Protobuf.TestProtos.Proto2.ImportMessage.Parser); + private readonly pbc::RepeatedField repeatedImportMessage_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedImportMessage { + get { return repeatedImportMessage_; } + } + + /// Field number for the "repeated_nested_enum" field. + public const int RepeatedNestedEnumFieldNumber = 51; + private static readonly pb::FieldCodec _repeated_repeatedNestedEnum_codec + = pb::FieldCodec.ForEnum(408, x => (int) x, x => (global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedEnum) x); + private readonly pbc::RepeatedField repeatedNestedEnum_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedNestedEnum { + get { return repeatedNestedEnum_; } + } + + /// Field number for the "repeated_foreign_enum" field. + public const int RepeatedForeignEnumFieldNumber = 52; + private static readonly pb::FieldCodec _repeated_repeatedForeignEnum_codec + = pb::FieldCodec.ForEnum(416, x => (int) x, x => (global::Google.Protobuf.TestProtos.Proto2.ForeignEnum) x); + private readonly pbc::RepeatedField repeatedForeignEnum_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedForeignEnum { + get { return repeatedForeignEnum_; } + } + + /// Field number for the "repeated_import_enum" field. + public const int RepeatedImportEnumFieldNumber = 53; + private static readonly pb::FieldCodec _repeated_repeatedImportEnum_codec + = pb::FieldCodec.ForEnum(424, x => (int) x, x => (global::Google.Protobuf.TestProtos.Proto2.ImportEnum) x); + private readonly pbc::RepeatedField repeatedImportEnum_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedImportEnum { + get { return repeatedImportEnum_; } + } + + /// Field number for the "repeated_string_piece" field. + public const int RepeatedStringPieceFieldNumber = 54; + private static readonly pb::FieldCodec _repeated_repeatedStringPiece_codec + = pb::FieldCodec.ForString(434); + private readonly pbc::RepeatedField repeatedStringPiece_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedStringPiece { + get { return repeatedStringPiece_; } + } + + /// Field number for the "repeated_cord" field. + public const int RepeatedCordFieldNumber = 55; + private static readonly pb::FieldCodec _repeated_repeatedCord_codec + = pb::FieldCodec.ForString(442); + private readonly pbc::RepeatedField repeatedCord_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedCord { + get { return repeatedCord_; } + } + + /// Field number for the "repeated_lazy_message" field. + public const int RepeatedLazyMessageFieldNumber = 57; + private static readonly pb::FieldCodec _repeated_repeatedLazyMessage_codec + = pb::FieldCodec.ForMessage(458, global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage.Parser); + private readonly pbc::RepeatedField repeatedLazyMessage_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedLazyMessage { + get { return repeatedLazyMessage_; } + } + + /// Field number for the "default_int32" field. + public const int DefaultInt32FieldNumber = 61; + private readonly static int DefaultInt32DefaultValue = 41; + + private int defaultInt32_; + /// + /// Singular with defaults + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int DefaultInt32 { + get { if ((_hasBits0 & 65536) != 0) { return defaultInt32_; } else { return DefaultInt32DefaultValue; } } + set { + _hasBits0 |= 65536; + defaultInt32_ = value; + } + } + /// Gets whether the "default_int32" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDefaultInt32 { + get { return (_hasBits0 & 65536) != 0; } + } + /// Clears the value of the "default_int32" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDefaultInt32() { + _hasBits0 &= ~65536; + } + + /// Field number for the "default_int64" field. + public const int DefaultInt64FieldNumber = 62; + private readonly static long DefaultInt64DefaultValue = 42L; + + private long defaultInt64_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public long DefaultInt64 { + get { if ((_hasBits0 & 131072) != 0) { return defaultInt64_; } else { return DefaultInt64DefaultValue; } } + set { + _hasBits0 |= 131072; + defaultInt64_ = value; + } + } + /// Gets whether the "default_int64" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDefaultInt64 { + get { return (_hasBits0 & 131072) != 0; } + } + /// Clears the value of the "default_int64" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDefaultInt64() { + _hasBits0 &= ~131072; + } + + /// Field number for the "default_uint32" field. + public const int DefaultUint32FieldNumber = 63; + private readonly static uint DefaultUint32DefaultValue = 43; + + private uint defaultUint32_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public uint DefaultUint32 { + get { if ((_hasBits0 & 262144) != 0) { return defaultUint32_; } else { return DefaultUint32DefaultValue; } } + set { + _hasBits0 |= 262144; + defaultUint32_ = value; + } + } + /// Gets whether the "default_uint32" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDefaultUint32 { + get { return (_hasBits0 & 262144) != 0; } + } + /// Clears the value of the "default_uint32" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDefaultUint32() { + _hasBits0 &= ~262144; + } + + /// Field number for the "default_uint64" field. + public const int DefaultUint64FieldNumber = 64; + private readonly static ulong DefaultUint64DefaultValue = 44UL; + + private ulong defaultUint64_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ulong DefaultUint64 { + get { if ((_hasBits0 & 524288) != 0) { return defaultUint64_; } else { return DefaultUint64DefaultValue; } } + set { + _hasBits0 |= 524288; + defaultUint64_ = value; + } + } + /// Gets whether the "default_uint64" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDefaultUint64 { + get { return (_hasBits0 & 524288) != 0; } + } + /// Clears the value of the "default_uint64" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDefaultUint64() { + _hasBits0 &= ~524288; + } + + /// Field number for the "default_sint32" field. + public const int DefaultSint32FieldNumber = 65; + private readonly static int DefaultSint32DefaultValue = -45; + + private int defaultSint32_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int DefaultSint32 { + get { if ((_hasBits0 & 1048576) != 0) { return defaultSint32_; } else { return DefaultSint32DefaultValue; } } + set { + _hasBits0 |= 1048576; + defaultSint32_ = value; + } + } + /// Gets whether the "default_sint32" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDefaultSint32 { + get { return (_hasBits0 & 1048576) != 0; } + } + /// Clears the value of the "default_sint32" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDefaultSint32() { + _hasBits0 &= ~1048576; + } + + /// Field number for the "default_sint64" field. + public const int DefaultSint64FieldNumber = 66; + private readonly static long DefaultSint64DefaultValue = 46L; + + private long defaultSint64_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public long DefaultSint64 { + get { if ((_hasBits0 & 2097152) != 0) { return defaultSint64_; } else { return DefaultSint64DefaultValue; } } + set { + _hasBits0 |= 2097152; + defaultSint64_ = value; + } + } + /// Gets whether the "default_sint64" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDefaultSint64 { + get { return (_hasBits0 & 2097152) != 0; } + } + /// Clears the value of the "default_sint64" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDefaultSint64() { + _hasBits0 &= ~2097152; + } + + /// Field number for the "default_fixed32" field. + public const int DefaultFixed32FieldNumber = 67; + private readonly static uint DefaultFixed32DefaultValue = 47; + + private uint defaultFixed32_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public uint DefaultFixed32 { + get { if ((_hasBits0 & 4194304) != 0) { return defaultFixed32_; } else { return DefaultFixed32DefaultValue; } } + set { + _hasBits0 |= 4194304; + defaultFixed32_ = value; + } + } + /// Gets whether the "default_fixed32" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDefaultFixed32 { + get { return (_hasBits0 & 4194304) != 0; } + } + /// Clears the value of the "default_fixed32" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDefaultFixed32() { + _hasBits0 &= ~4194304; + } + + /// Field number for the "default_fixed64" field. + public const int DefaultFixed64FieldNumber = 68; + private readonly static ulong DefaultFixed64DefaultValue = 48UL; + + private ulong defaultFixed64_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ulong DefaultFixed64 { + get { if ((_hasBits0 & 8388608) != 0) { return defaultFixed64_; } else { return DefaultFixed64DefaultValue; } } + set { + _hasBits0 |= 8388608; + defaultFixed64_ = value; + } + } + /// Gets whether the "default_fixed64" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDefaultFixed64 { + get { return (_hasBits0 & 8388608) != 0; } + } + /// Clears the value of the "default_fixed64" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDefaultFixed64() { + _hasBits0 &= ~8388608; + } + + /// Field number for the "default_sfixed32" field. + public const int DefaultSfixed32FieldNumber = 69; + private readonly static int DefaultSfixed32DefaultValue = 49; + + private int defaultSfixed32_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int DefaultSfixed32 { + get { if ((_hasBits0 & 16777216) != 0) { return defaultSfixed32_; } else { return DefaultSfixed32DefaultValue; } } + set { + _hasBits0 |= 16777216; + defaultSfixed32_ = value; + } + } + /// Gets whether the "default_sfixed32" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDefaultSfixed32 { + get { return (_hasBits0 & 16777216) != 0; } + } + /// Clears the value of the "default_sfixed32" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDefaultSfixed32() { + _hasBits0 &= ~16777216; + } + + /// Field number for the "default_sfixed64" field. + public const int DefaultSfixed64FieldNumber = 70; + private readonly static long DefaultSfixed64DefaultValue = -50L; + + private long defaultSfixed64_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public long DefaultSfixed64 { + get { if ((_hasBits0 & 33554432) != 0) { return defaultSfixed64_; } else { return DefaultSfixed64DefaultValue; } } + set { + _hasBits0 |= 33554432; + defaultSfixed64_ = value; + } + } + /// Gets whether the "default_sfixed64" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDefaultSfixed64 { + get { return (_hasBits0 & 33554432) != 0; } + } + /// Clears the value of the "default_sfixed64" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDefaultSfixed64() { + _hasBits0 &= ~33554432; + } + + /// Field number for the "default_float" field. + public const int DefaultFloatFieldNumber = 71; + private readonly static float DefaultFloatDefaultValue = 51.5F; + + private float defaultFloat_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public float DefaultFloat { + get { if ((_hasBits0 & 67108864) != 0) { return defaultFloat_; } else { return DefaultFloatDefaultValue; } } + set { + _hasBits0 |= 67108864; + defaultFloat_ = value; + } + } + /// Gets whether the "default_float" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDefaultFloat { + get { return (_hasBits0 & 67108864) != 0; } + } + /// Clears the value of the "default_float" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDefaultFloat() { + _hasBits0 &= ~67108864; + } + + /// Field number for the "default_double" field. + public const int DefaultDoubleFieldNumber = 72; + private readonly static double DefaultDoubleDefaultValue = 52000D; + + private double defaultDouble_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public double DefaultDouble { + get { if ((_hasBits0 & 134217728) != 0) { return defaultDouble_; } else { return DefaultDoubleDefaultValue; } } + set { + _hasBits0 |= 134217728; + defaultDouble_ = value; + } + } + /// Gets whether the "default_double" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDefaultDouble { + get { return (_hasBits0 & 134217728) != 0; } + } + /// Clears the value of the "default_double" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDefaultDouble() { + _hasBits0 &= ~134217728; + } + + /// Field number for the "default_bool" field. + public const int DefaultBoolFieldNumber = 73; + private readonly static bool DefaultBoolDefaultValue = true; + + private bool defaultBool_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool DefaultBool { + get { if ((_hasBits0 & 268435456) != 0) { return defaultBool_; } else { return DefaultBoolDefaultValue; } } + set { + _hasBits0 |= 268435456; + defaultBool_ = value; + } + } + /// Gets whether the "default_bool" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDefaultBool { + get { return (_hasBits0 & 268435456) != 0; } + } + /// Clears the value of the "default_bool" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDefaultBool() { + _hasBits0 &= ~268435456; + } + + /// Field number for the "default_string" field. + public const int DefaultStringFieldNumber = 74; + private readonly static string DefaultStringDefaultValue = global::System.Text.Encoding.UTF8.GetString(global::System.Convert.FromBase64String("aGVsbG8="), 0, 5); + + private string defaultString_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string DefaultString { + get { return defaultString_ ?? DefaultStringDefaultValue; } + set { + defaultString_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "default_string" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDefaultString { + get { return defaultString_ != null; } + } + /// Clears the value of the "default_string" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDefaultString() { + defaultString_ = null; + } + + /// Field number for the "default_bytes" field. + public const int DefaultBytesFieldNumber = 75; + private readonly static pb::ByteString DefaultBytesDefaultValue = pb::ByteString.FromBase64("d29ybGQ="); + + private pb::ByteString defaultBytes_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pb::ByteString DefaultBytes { + get { return defaultBytes_ ?? DefaultBytesDefaultValue; } + set { + defaultBytes_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "default_bytes" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDefaultBytes { + get { return defaultBytes_ != null; } + } + /// Clears the value of the "default_bytes" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDefaultBytes() { + defaultBytes_ = null; + } + + /// Field number for the "default_nested_enum" field. + public const int DefaultNestedEnumFieldNumber = 81; + private readonly static global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedEnum DefaultNestedEnumDefaultValue = global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedEnum.Bar; + + private global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedEnum defaultNestedEnum_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedEnum DefaultNestedEnum { + get { if ((_hasBits0 & 536870912) != 0) { return defaultNestedEnum_; } else { return DefaultNestedEnumDefaultValue; } } + set { + _hasBits0 |= 536870912; + defaultNestedEnum_ = value; + } + } + /// Gets whether the "default_nested_enum" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDefaultNestedEnum { + get { return (_hasBits0 & 536870912) != 0; } + } + /// Clears the value of the "default_nested_enum" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDefaultNestedEnum() { + _hasBits0 &= ~536870912; + } + + /// Field number for the "default_foreign_enum" field. + public const int DefaultForeignEnumFieldNumber = 82; + private readonly static global::Google.Protobuf.TestProtos.Proto2.ForeignEnum DefaultForeignEnumDefaultValue = global::Google.Protobuf.TestProtos.Proto2.ForeignEnum.ForeignBar; + + private global::Google.Protobuf.TestProtos.Proto2.ForeignEnum defaultForeignEnum_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.ForeignEnum DefaultForeignEnum { + get { if ((_hasBits0 & 1073741824) != 0) { return defaultForeignEnum_; } else { return DefaultForeignEnumDefaultValue; } } + set { + _hasBits0 |= 1073741824; + defaultForeignEnum_ = value; + } + } + /// Gets whether the "default_foreign_enum" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDefaultForeignEnum { + get { return (_hasBits0 & 1073741824) != 0; } + } + /// Clears the value of the "default_foreign_enum" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDefaultForeignEnum() { + _hasBits0 &= ~1073741824; + } + + /// Field number for the "default_import_enum" field. + public const int DefaultImportEnumFieldNumber = 83; + private readonly static global::Google.Protobuf.TestProtos.Proto2.ImportEnum DefaultImportEnumDefaultValue = global::Google.Protobuf.TestProtos.Proto2.ImportEnum.ImportBar; + + private global::Google.Protobuf.TestProtos.Proto2.ImportEnum defaultImportEnum_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.ImportEnum DefaultImportEnum { + get { if ((_hasBits0 & -2147483648) != 0) { return defaultImportEnum_; } else { return DefaultImportEnumDefaultValue; } } + set { + _hasBits0 |= -2147483648; + defaultImportEnum_ = value; + } + } + /// Gets whether the "default_import_enum" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDefaultImportEnum { + get { return (_hasBits0 & -2147483648) != 0; } + } + /// Clears the value of the "default_import_enum" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDefaultImportEnum() { + _hasBits0 &= ~-2147483648; + } + + /// Field number for the "default_string_piece" field. + public const int DefaultStringPieceFieldNumber = 84; + private readonly static string DefaultStringPieceDefaultValue = global::System.Text.Encoding.UTF8.GetString(global::System.Convert.FromBase64String("YWJj"), 0, 3); + + private string defaultStringPiece_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string DefaultStringPiece { + get { return defaultStringPiece_ ?? DefaultStringPieceDefaultValue; } + set { + defaultStringPiece_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "default_string_piece" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDefaultStringPiece { + get { return defaultStringPiece_ != null; } + } + /// Clears the value of the "default_string_piece" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDefaultStringPiece() { + defaultStringPiece_ = null; + } + + /// Field number for the "default_cord" field. + public const int DefaultCordFieldNumber = 85; + private readonly static string DefaultCordDefaultValue = global::System.Text.Encoding.UTF8.GetString(global::System.Convert.FromBase64String("MTIz"), 0, 3); + + private string defaultCord_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string DefaultCord { + get { return defaultCord_ ?? DefaultCordDefaultValue; } + set { + defaultCord_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "default_cord" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDefaultCord { + get { return defaultCord_ != null; } + } + /// Clears the value of the "default_cord" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDefaultCord() { + defaultCord_ = null; + } + + /// Field number for the "oneof_uint32" field. + public const int OneofUint32FieldNumber = 111; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public uint OneofUint32 { + get { return HasOneofUint32 ? (uint) oneofField_ : 0; } + set { + oneofField_ = value; + oneofFieldCase_ = OneofFieldOneofCase.OneofUint32; + } + } + /// Gets whether the "oneof_uint32" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOneofUint32 { + get { return oneofFieldCase_ == OneofFieldOneofCase.OneofUint32; } + } + /// Clears the value of the oneof if it's currently set to "oneof_uint32" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOneofUint32() { + if (HasOneofUint32) { + ClearOneofField(); + } + } + + /// Field number for the "oneof_nested_message" field. + public const int OneofNestedMessageFieldNumber = 112; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage OneofNestedMessage { + get { return oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage ? (global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage) oneofField_ : null; } + set { + oneofField_ = value; + oneofFieldCase_ = value == null ? OneofFieldOneofCase.None : OneofFieldOneofCase.OneofNestedMessage; + } + } + + /// Field number for the "oneof_string" field. + public const int OneofStringFieldNumber = 113; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string OneofString { + get { return HasOneofString ? (string) oneofField_ : ""; } + set { + oneofField_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + oneofFieldCase_ = OneofFieldOneofCase.OneofString; + } + } + /// Gets whether the "oneof_string" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOneofString { + get { return oneofFieldCase_ == OneofFieldOneofCase.OneofString; } + } + /// Clears the value of the oneof if it's currently set to "oneof_string" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOneofString() { + if (HasOneofString) { + ClearOneofField(); + } + } + + /// Field number for the "oneof_bytes" field. + public const int OneofBytesFieldNumber = 114; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pb::ByteString OneofBytes { + get { return HasOneofBytes ? (pb::ByteString) oneofField_ : pb::ByteString.Empty; } + set { + oneofField_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + oneofFieldCase_ = OneofFieldOneofCase.OneofBytes; + } + } + /// Gets whether the "oneof_bytes" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOneofBytes { + get { return oneofFieldCase_ == OneofFieldOneofCase.OneofBytes; } + } + /// Clears the value of the oneof if it's currently set to "oneof_bytes" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOneofBytes() { + if (HasOneofBytes) { + ClearOneofField(); + } + } + + private object oneofField_; + /// Enum of possible cases for the "oneof_field" oneof. + public enum OneofFieldOneofCase { + None = 0, + OneofUint32 = 111, + OneofNestedMessage = 112, + OneofString = 113, + OneofBytes = 114, + } + private OneofFieldOneofCase oneofFieldCase_ = OneofFieldOneofCase.None; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneofFieldOneofCase OneofFieldCase { + get { return oneofFieldCase_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOneofField() { + oneofFieldCase_ = OneofFieldOneofCase.None; + oneofField_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestAllTypes); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestAllTypes other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (OptionalInt32 != other.OptionalInt32) return false; + if (OptionalInt64 != other.OptionalInt64) return false; + if (OptionalUint32 != other.OptionalUint32) return false; + if (OptionalUint64 != other.OptionalUint64) return false; + if (OptionalSint32 != other.OptionalSint32) return false; + if (OptionalSint64 != other.OptionalSint64) return false; + if (OptionalFixed32 != other.OptionalFixed32) return false; + if (OptionalFixed64 != other.OptionalFixed64) return false; + if (OptionalSfixed32 != other.OptionalSfixed32) return false; + if (OptionalSfixed64 != other.OptionalSfixed64) return false; + if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(OptionalFloat, other.OptionalFloat)) return false; + if (!pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.Equals(OptionalDouble, other.OptionalDouble)) return false; + if (OptionalBool != other.OptionalBool) return false; + if (OptionalString != other.OptionalString) return false; + if (OptionalBytes != other.OptionalBytes) return false; + if (!object.Equals(OptionalGroup, other.OptionalGroup)) return false; + if (!object.Equals(OptionalNestedMessage, other.OptionalNestedMessage)) return false; + if (!object.Equals(OptionalForeignMessage, other.OptionalForeignMessage)) return false; + if (!object.Equals(OptionalImportMessage, other.OptionalImportMessage)) return false; + if (OptionalNestedEnum != other.OptionalNestedEnum) return false; + if (OptionalForeignEnum != other.OptionalForeignEnum) return false; + if (OptionalImportEnum != other.OptionalImportEnum) return false; + if (OptionalStringPiece != other.OptionalStringPiece) return false; + if (OptionalCord != other.OptionalCord) return false; + if (!object.Equals(OptionalPublicImportMessage, other.OptionalPublicImportMessage)) return false; + if (!object.Equals(OptionalLazyMessage, other.OptionalLazyMessage)) return false; + if(!repeatedInt32_.Equals(other.repeatedInt32_)) return false; + if(!repeatedInt64_.Equals(other.repeatedInt64_)) return false; + if(!repeatedUint32_.Equals(other.repeatedUint32_)) return false; + if(!repeatedUint64_.Equals(other.repeatedUint64_)) return false; + if(!repeatedSint32_.Equals(other.repeatedSint32_)) return false; + if(!repeatedSint64_.Equals(other.repeatedSint64_)) return false; + if(!repeatedFixed32_.Equals(other.repeatedFixed32_)) return false; + if(!repeatedFixed64_.Equals(other.repeatedFixed64_)) return false; + if(!repeatedSfixed32_.Equals(other.repeatedSfixed32_)) return false; + if(!repeatedSfixed64_.Equals(other.repeatedSfixed64_)) return false; + if(!repeatedFloat_.Equals(other.repeatedFloat_)) return false; + if(!repeatedDouble_.Equals(other.repeatedDouble_)) return false; + if(!repeatedBool_.Equals(other.repeatedBool_)) return false; + if(!repeatedString_.Equals(other.repeatedString_)) return false; + if(!repeatedBytes_.Equals(other.repeatedBytes_)) return false; + if(!repeatedGroup_.Equals(other.repeatedGroup_)) return false; + if(!repeatedNestedMessage_.Equals(other.repeatedNestedMessage_)) return false; + if(!repeatedForeignMessage_.Equals(other.repeatedForeignMessage_)) return false; + if(!repeatedImportMessage_.Equals(other.repeatedImportMessage_)) return false; + if(!repeatedNestedEnum_.Equals(other.repeatedNestedEnum_)) return false; + if(!repeatedForeignEnum_.Equals(other.repeatedForeignEnum_)) return false; + if(!repeatedImportEnum_.Equals(other.repeatedImportEnum_)) return false; + if(!repeatedStringPiece_.Equals(other.repeatedStringPiece_)) return false; + if(!repeatedCord_.Equals(other.repeatedCord_)) return false; + if(!repeatedLazyMessage_.Equals(other.repeatedLazyMessage_)) return false; + if (DefaultInt32 != other.DefaultInt32) return false; + if (DefaultInt64 != other.DefaultInt64) return false; + if (DefaultUint32 != other.DefaultUint32) return false; + if (DefaultUint64 != other.DefaultUint64) return false; + if (DefaultSint32 != other.DefaultSint32) return false; + if (DefaultSint64 != other.DefaultSint64) return false; + if (DefaultFixed32 != other.DefaultFixed32) return false; + if (DefaultFixed64 != other.DefaultFixed64) return false; + if (DefaultSfixed32 != other.DefaultSfixed32) return false; + if (DefaultSfixed64 != other.DefaultSfixed64) return false; + if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(DefaultFloat, other.DefaultFloat)) return false; + if (!pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.Equals(DefaultDouble, other.DefaultDouble)) return false; + if (DefaultBool != other.DefaultBool) return false; + if (DefaultString != other.DefaultString) return false; + if (DefaultBytes != other.DefaultBytes) return false; + if (DefaultNestedEnum != other.DefaultNestedEnum) return false; + if (DefaultForeignEnum != other.DefaultForeignEnum) return false; + if (DefaultImportEnum != other.DefaultImportEnum) return false; + if (DefaultStringPiece != other.DefaultStringPiece) return false; + if (DefaultCord != other.DefaultCord) return false; + if (OneofUint32 != other.OneofUint32) return false; + if (!object.Equals(OneofNestedMessage, other.OneofNestedMessage)) return false; + if (OneofString != other.OneofString) return false; + if (OneofBytes != other.OneofBytes) return false; + if (OneofFieldCase != other.OneofFieldCase) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasOptionalInt32) hash ^= OptionalInt32.GetHashCode(); + if (HasOptionalInt64) hash ^= OptionalInt64.GetHashCode(); + if (HasOptionalUint32) hash ^= OptionalUint32.GetHashCode(); + if (HasOptionalUint64) hash ^= OptionalUint64.GetHashCode(); + if (HasOptionalSint32) hash ^= OptionalSint32.GetHashCode(); + if (HasOptionalSint64) hash ^= OptionalSint64.GetHashCode(); + if (HasOptionalFixed32) hash ^= OptionalFixed32.GetHashCode(); + if (HasOptionalFixed64) hash ^= OptionalFixed64.GetHashCode(); + if (HasOptionalSfixed32) hash ^= OptionalSfixed32.GetHashCode(); + if (HasOptionalSfixed64) hash ^= OptionalSfixed64.GetHashCode(); + if (HasOptionalFloat) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(OptionalFloat); + if (HasOptionalDouble) hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(OptionalDouble); + if (HasOptionalBool) hash ^= OptionalBool.GetHashCode(); + if (HasOptionalString) hash ^= OptionalString.GetHashCode(); + if (HasOptionalBytes) hash ^= OptionalBytes.GetHashCode(); + if (HasOptionalGroup) hash ^= OptionalGroup.GetHashCode(); + if (optionalNestedMessage_ != null) hash ^= OptionalNestedMessage.GetHashCode(); + if (optionalForeignMessage_ != null) hash ^= OptionalForeignMessage.GetHashCode(); + if (optionalImportMessage_ != null) hash ^= OptionalImportMessage.GetHashCode(); + if (HasOptionalNestedEnum) hash ^= OptionalNestedEnum.GetHashCode(); + if (HasOptionalForeignEnum) hash ^= OptionalForeignEnum.GetHashCode(); + if (HasOptionalImportEnum) hash ^= OptionalImportEnum.GetHashCode(); + if (HasOptionalStringPiece) hash ^= OptionalStringPiece.GetHashCode(); + if (HasOptionalCord) hash ^= OptionalCord.GetHashCode(); + if (optionalPublicImportMessage_ != null) hash ^= OptionalPublicImportMessage.GetHashCode(); + if (optionalLazyMessage_ != null) hash ^= OptionalLazyMessage.GetHashCode(); + hash ^= repeatedInt32_.GetHashCode(); + hash ^= repeatedInt64_.GetHashCode(); + hash ^= repeatedUint32_.GetHashCode(); + hash ^= repeatedUint64_.GetHashCode(); + hash ^= repeatedSint32_.GetHashCode(); + hash ^= repeatedSint64_.GetHashCode(); + hash ^= repeatedFixed32_.GetHashCode(); + hash ^= repeatedFixed64_.GetHashCode(); + hash ^= repeatedSfixed32_.GetHashCode(); + hash ^= repeatedSfixed64_.GetHashCode(); + hash ^= repeatedFloat_.GetHashCode(); + hash ^= repeatedDouble_.GetHashCode(); + hash ^= repeatedBool_.GetHashCode(); + hash ^= repeatedString_.GetHashCode(); + hash ^= repeatedBytes_.GetHashCode(); + hash ^= repeatedGroup_.GetHashCode(); + hash ^= repeatedNestedMessage_.GetHashCode(); + hash ^= repeatedForeignMessage_.GetHashCode(); + hash ^= repeatedImportMessage_.GetHashCode(); + hash ^= repeatedNestedEnum_.GetHashCode(); + hash ^= repeatedForeignEnum_.GetHashCode(); + hash ^= repeatedImportEnum_.GetHashCode(); + hash ^= repeatedStringPiece_.GetHashCode(); + hash ^= repeatedCord_.GetHashCode(); + hash ^= repeatedLazyMessage_.GetHashCode(); + if (HasDefaultInt32) hash ^= DefaultInt32.GetHashCode(); + if (HasDefaultInt64) hash ^= DefaultInt64.GetHashCode(); + if (HasDefaultUint32) hash ^= DefaultUint32.GetHashCode(); + if (HasDefaultUint64) hash ^= DefaultUint64.GetHashCode(); + if (HasDefaultSint32) hash ^= DefaultSint32.GetHashCode(); + if (HasDefaultSint64) hash ^= DefaultSint64.GetHashCode(); + if (HasDefaultFixed32) hash ^= DefaultFixed32.GetHashCode(); + if (HasDefaultFixed64) hash ^= DefaultFixed64.GetHashCode(); + if (HasDefaultSfixed32) hash ^= DefaultSfixed32.GetHashCode(); + if (HasDefaultSfixed64) hash ^= DefaultSfixed64.GetHashCode(); + if (HasDefaultFloat) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(DefaultFloat); + if (HasDefaultDouble) hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(DefaultDouble); + if (HasDefaultBool) hash ^= DefaultBool.GetHashCode(); + if (HasDefaultString) hash ^= DefaultString.GetHashCode(); + if (HasDefaultBytes) hash ^= DefaultBytes.GetHashCode(); + if (HasDefaultNestedEnum) hash ^= DefaultNestedEnum.GetHashCode(); + if (HasDefaultForeignEnum) hash ^= DefaultForeignEnum.GetHashCode(); + if (HasDefaultImportEnum) hash ^= DefaultImportEnum.GetHashCode(); + if (HasDefaultStringPiece) hash ^= DefaultStringPiece.GetHashCode(); + if (HasDefaultCord) hash ^= DefaultCord.GetHashCode(); + if (HasOneofUint32) hash ^= OneofUint32.GetHashCode(); + if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) hash ^= OneofNestedMessage.GetHashCode(); + if (HasOneofString) hash ^= OneofString.GetHashCode(); + if (HasOneofBytes) hash ^= OneofBytes.GetHashCode(); + hash ^= (int) oneofFieldCase_; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasOptionalInt32) { + output.WriteRawTag(8); + output.WriteInt32(OptionalInt32); + } + if (HasOptionalInt64) { + output.WriteRawTag(16); + output.WriteInt64(OptionalInt64); + } + if (HasOptionalUint32) { + output.WriteRawTag(24); + output.WriteUInt32(OptionalUint32); + } + if (HasOptionalUint64) { + output.WriteRawTag(32); + output.WriteUInt64(OptionalUint64); + } + if (HasOptionalSint32) { + output.WriteRawTag(40); + output.WriteSInt32(OptionalSint32); + } + if (HasOptionalSint64) { + output.WriteRawTag(48); + output.WriteSInt64(OptionalSint64); + } + if (HasOptionalFixed32) { + output.WriteRawTag(61); + output.WriteFixed32(OptionalFixed32); + } + if (HasOptionalFixed64) { + output.WriteRawTag(65); + output.WriteFixed64(OptionalFixed64); + } + if (HasOptionalSfixed32) { + output.WriteRawTag(77); + output.WriteSFixed32(OptionalSfixed32); + } + if (HasOptionalSfixed64) { + output.WriteRawTag(81); + output.WriteSFixed64(OptionalSfixed64); + } + if (HasOptionalFloat) { + output.WriteRawTag(93); + output.WriteFloat(OptionalFloat); + } + if (HasOptionalDouble) { + output.WriteRawTag(97); + output.WriteDouble(OptionalDouble); + } + if (HasOptionalBool) { + output.WriteRawTag(104); + output.WriteBool(OptionalBool); + } + if (HasOptionalString) { + output.WriteRawTag(114); + output.WriteString(OptionalString); + } + if (HasOptionalBytes) { + output.WriteRawTag(122); + output.WriteBytes(OptionalBytes); + } + if (HasOptionalGroup) { + output.WriteRawTag(131, 1); + output.WriteGroup(OptionalGroup); + output.WriteRawTag(132, 1); + } + if (optionalNestedMessage_ != null) { + output.WriteRawTag(146, 1); + output.WriteMessage(OptionalNestedMessage); + } + if (optionalForeignMessage_ != null) { + output.WriteRawTag(154, 1); + output.WriteMessage(OptionalForeignMessage); + } + if (optionalImportMessage_ != null) { + output.WriteRawTag(162, 1); + output.WriteMessage(OptionalImportMessage); + } + if (HasOptionalNestedEnum) { + output.WriteRawTag(168, 1); + output.WriteEnum((int) OptionalNestedEnum); + } + if (HasOptionalForeignEnum) { + output.WriteRawTag(176, 1); + output.WriteEnum((int) OptionalForeignEnum); + } + if (HasOptionalImportEnum) { + output.WriteRawTag(184, 1); + output.WriteEnum((int) OptionalImportEnum); + } + if (HasOptionalStringPiece) { + output.WriteRawTag(194, 1); + output.WriteString(OptionalStringPiece); + } + if (HasOptionalCord) { + output.WriteRawTag(202, 1); + output.WriteString(OptionalCord); + } + if (optionalPublicImportMessage_ != null) { + output.WriteRawTag(210, 1); + output.WriteMessage(OptionalPublicImportMessage); + } + if (optionalLazyMessage_ != null) { + output.WriteRawTag(218, 1); + output.WriteMessage(OptionalLazyMessage); + } + repeatedInt32_.WriteTo(output, _repeated_repeatedInt32_codec); + repeatedInt64_.WriteTo(output, _repeated_repeatedInt64_codec); + repeatedUint32_.WriteTo(output, _repeated_repeatedUint32_codec); + repeatedUint64_.WriteTo(output, _repeated_repeatedUint64_codec); + repeatedSint32_.WriteTo(output, _repeated_repeatedSint32_codec); + repeatedSint64_.WriteTo(output, _repeated_repeatedSint64_codec); + repeatedFixed32_.WriteTo(output, _repeated_repeatedFixed32_codec); + repeatedFixed64_.WriteTo(output, _repeated_repeatedFixed64_codec); + repeatedSfixed32_.WriteTo(output, _repeated_repeatedSfixed32_codec); + repeatedSfixed64_.WriteTo(output, _repeated_repeatedSfixed64_codec); + repeatedFloat_.WriteTo(output, _repeated_repeatedFloat_codec); + repeatedDouble_.WriteTo(output, _repeated_repeatedDouble_codec); + repeatedBool_.WriteTo(output, _repeated_repeatedBool_codec); + repeatedString_.WriteTo(output, _repeated_repeatedString_codec); + repeatedBytes_.WriteTo(output, _repeated_repeatedBytes_codec); + repeatedGroup_.WriteTo(output, _repeated_repeatedGroup_codec); + repeatedNestedMessage_.WriteTo(output, _repeated_repeatedNestedMessage_codec); + repeatedForeignMessage_.WriteTo(output, _repeated_repeatedForeignMessage_codec); + repeatedImportMessage_.WriteTo(output, _repeated_repeatedImportMessage_codec); + repeatedNestedEnum_.WriteTo(output, _repeated_repeatedNestedEnum_codec); + repeatedForeignEnum_.WriteTo(output, _repeated_repeatedForeignEnum_codec); + repeatedImportEnum_.WriteTo(output, _repeated_repeatedImportEnum_codec); + repeatedStringPiece_.WriteTo(output, _repeated_repeatedStringPiece_codec); + repeatedCord_.WriteTo(output, _repeated_repeatedCord_codec); + repeatedLazyMessage_.WriteTo(output, _repeated_repeatedLazyMessage_codec); + if (HasDefaultInt32) { + output.WriteRawTag(232, 3); + output.WriteInt32(DefaultInt32); + } + if (HasDefaultInt64) { + output.WriteRawTag(240, 3); + output.WriteInt64(DefaultInt64); + } + if (HasDefaultUint32) { + output.WriteRawTag(248, 3); + output.WriteUInt32(DefaultUint32); + } + if (HasDefaultUint64) { + output.WriteRawTag(128, 4); + output.WriteUInt64(DefaultUint64); + } + if (HasDefaultSint32) { + output.WriteRawTag(136, 4); + output.WriteSInt32(DefaultSint32); + } + if (HasDefaultSint64) { + output.WriteRawTag(144, 4); + output.WriteSInt64(DefaultSint64); + } + if (HasDefaultFixed32) { + output.WriteRawTag(157, 4); + output.WriteFixed32(DefaultFixed32); + } + if (HasDefaultFixed64) { + output.WriteRawTag(161, 4); + output.WriteFixed64(DefaultFixed64); + } + if (HasDefaultSfixed32) { + output.WriteRawTag(173, 4); + output.WriteSFixed32(DefaultSfixed32); + } + if (HasDefaultSfixed64) { + output.WriteRawTag(177, 4); + output.WriteSFixed64(DefaultSfixed64); + } + if (HasDefaultFloat) { + output.WriteRawTag(189, 4); + output.WriteFloat(DefaultFloat); + } + if (HasDefaultDouble) { + output.WriteRawTag(193, 4); + output.WriteDouble(DefaultDouble); + } + if (HasDefaultBool) { + output.WriteRawTag(200, 4); + output.WriteBool(DefaultBool); + } + if (HasDefaultString) { + output.WriteRawTag(210, 4); + output.WriteString(DefaultString); + } + if (HasDefaultBytes) { + output.WriteRawTag(218, 4); + output.WriteBytes(DefaultBytes); + } + if (HasDefaultNestedEnum) { + output.WriteRawTag(136, 5); + output.WriteEnum((int) DefaultNestedEnum); + } + if (HasDefaultForeignEnum) { + output.WriteRawTag(144, 5); + output.WriteEnum((int) DefaultForeignEnum); + } + if (HasDefaultImportEnum) { + output.WriteRawTag(152, 5); + output.WriteEnum((int) DefaultImportEnum); + } + if (HasDefaultStringPiece) { + output.WriteRawTag(162, 5); + output.WriteString(DefaultStringPiece); + } + if (HasDefaultCord) { + output.WriteRawTag(170, 5); + output.WriteString(DefaultCord); + } + if (HasOneofUint32) { + output.WriteRawTag(248, 6); + output.WriteUInt32(OneofUint32); + } + if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) { + output.WriteRawTag(130, 7); + output.WriteMessage(OneofNestedMessage); + } + if (HasOneofString) { + output.WriteRawTag(138, 7); + output.WriteString(OneofString); + } + if (HasOneofBytes) { + output.WriteRawTag(146, 7); + output.WriteBytes(OneofBytes); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasOptionalInt32) { + output.WriteRawTag(8); + output.WriteInt32(OptionalInt32); + } + if (HasOptionalInt64) { + output.WriteRawTag(16); + output.WriteInt64(OptionalInt64); + } + if (HasOptionalUint32) { + output.WriteRawTag(24); + output.WriteUInt32(OptionalUint32); + } + if (HasOptionalUint64) { + output.WriteRawTag(32); + output.WriteUInt64(OptionalUint64); + } + if (HasOptionalSint32) { + output.WriteRawTag(40); + output.WriteSInt32(OptionalSint32); + } + if (HasOptionalSint64) { + output.WriteRawTag(48); + output.WriteSInt64(OptionalSint64); + } + if (HasOptionalFixed32) { + output.WriteRawTag(61); + output.WriteFixed32(OptionalFixed32); + } + if (HasOptionalFixed64) { + output.WriteRawTag(65); + output.WriteFixed64(OptionalFixed64); + } + if (HasOptionalSfixed32) { + output.WriteRawTag(77); + output.WriteSFixed32(OptionalSfixed32); + } + if (HasOptionalSfixed64) { + output.WriteRawTag(81); + output.WriteSFixed64(OptionalSfixed64); + } + if (HasOptionalFloat) { + output.WriteRawTag(93); + output.WriteFloat(OptionalFloat); + } + if (HasOptionalDouble) { + output.WriteRawTag(97); + output.WriteDouble(OptionalDouble); + } + if (HasOptionalBool) { + output.WriteRawTag(104); + output.WriteBool(OptionalBool); + } + if (HasOptionalString) { + output.WriteRawTag(114); + output.WriteString(OptionalString); + } + if (HasOptionalBytes) { + output.WriteRawTag(122); + output.WriteBytes(OptionalBytes); + } + if (HasOptionalGroup) { + output.WriteRawTag(131, 1); + output.WriteGroup(OptionalGroup); + output.WriteRawTag(132, 1); + } + if (optionalNestedMessage_ != null) { + output.WriteRawTag(146, 1); + output.WriteMessage(OptionalNestedMessage); + } + if (optionalForeignMessage_ != null) { + output.WriteRawTag(154, 1); + output.WriteMessage(OptionalForeignMessage); + } + if (optionalImportMessage_ != null) { + output.WriteRawTag(162, 1); + output.WriteMessage(OptionalImportMessage); + } + if (HasOptionalNestedEnum) { + output.WriteRawTag(168, 1); + output.WriteEnum((int) OptionalNestedEnum); + } + if (HasOptionalForeignEnum) { + output.WriteRawTag(176, 1); + output.WriteEnum((int) OptionalForeignEnum); + } + if (HasOptionalImportEnum) { + output.WriteRawTag(184, 1); + output.WriteEnum((int) OptionalImportEnum); + } + if (HasOptionalStringPiece) { + output.WriteRawTag(194, 1); + output.WriteString(OptionalStringPiece); + } + if (HasOptionalCord) { + output.WriteRawTag(202, 1); + output.WriteString(OptionalCord); + } + if (optionalPublicImportMessage_ != null) { + output.WriteRawTag(210, 1); + output.WriteMessage(OptionalPublicImportMessage); + } + if (optionalLazyMessage_ != null) { + output.WriteRawTag(218, 1); + output.WriteMessage(OptionalLazyMessage); + } + repeatedInt32_.WriteTo(ref output, _repeated_repeatedInt32_codec); + repeatedInt64_.WriteTo(ref output, _repeated_repeatedInt64_codec); + repeatedUint32_.WriteTo(ref output, _repeated_repeatedUint32_codec); + repeatedUint64_.WriteTo(ref output, _repeated_repeatedUint64_codec); + repeatedSint32_.WriteTo(ref output, _repeated_repeatedSint32_codec); + repeatedSint64_.WriteTo(ref output, _repeated_repeatedSint64_codec); + repeatedFixed32_.WriteTo(ref output, _repeated_repeatedFixed32_codec); + repeatedFixed64_.WriteTo(ref output, _repeated_repeatedFixed64_codec); + repeatedSfixed32_.WriteTo(ref output, _repeated_repeatedSfixed32_codec); + repeatedSfixed64_.WriteTo(ref output, _repeated_repeatedSfixed64_codec); + repeatedFloat_.WriteTo(ref output, _repeated_repeatedFloat_codec); + repeatedDouble_.WriteTo(ref output, _repeated_repeatedDouble_codec); + repeatedBool_.WriteTo(ref output, _repeated_repeatedBool_codec); + repeatedString_.WriteTo(ref output, _repeated_repeatedString_codec); + repeatedBytes_.WriteTo(ref output, _repeated_repeatedBytes_codec); + repeatedGroup_.WriteTo(ref output, _repeated_repeatedGroup_codec); + repeatedNestedMessage_.WriteTo(ref output, _repeated_repeatedNestedMessage_codec); + repeatedForeignMessage_.WriteTo(ref output, _repeated_repeatedForeignMessage_codec); + repeatedImportMessage_.WriteTo(ref output, _repeated_repeatedImportMessage_codec); + repeatedNestedEnum_.WriteTo(ref output, _repeated_repeatedNestedEnum_codec); + repeatedForeignEnum_.WriteTo(ref output, _repeated_repeatedForeignEnum_codec); + repeatedImportEnum_.WriteTo(ref output, _repeated_repeatedImportEnum_codec); + repeatedStringPiece_.WriteTo(ref output, _repeated_repeatedStringPiece_codec); + repeatedCord_.WriteTo(ref output, _repeated_repeatedCord_codec); + repeatedLazyMessage_.WriteTo(ref output, _repeated_repeatedLazyMessage_codec); + if (HasDefaultInt32) { + output.WriteRawTag(232, 3); + output.WriteInt32(DefaultInt32); + } + if (HasDefaultInt64) { + output.WriteRawTag(240, 3); + output.WriteInt64(DefaultInt64); + } + if (HasDefaultUint32) { + output.WriteRawTag(248, 3); + output.WriteUInt32(DefaultUint32); + } + if (HasDefaultUint64) { + output.WriteRawTag(128, 4); + output.WriteUInt64(DefaultUint64); + } + if (HasDefaultSint32) { + output.WriteRawTag(136, 4); + output.WriteSInt32(DefaultSint32); + } + if (HasDefaultSint64) { + output.WriteRawTag(144, 4); + output.WriteSInt64(DefaultSint64); + } + if (HasDefaultFixed32) { + output.WriteRawTag(157, 4); + output.WriteFixed32(DefaultFixed32); + } + if (HasDefaultFixed64) { + output.WriteRawTag(161, 4); + output.WriteFixed64(DefaultFixed64); + } + if (HasDefaultSfixed32) { + output.WriteRawTag(173, 4); + output.WriteSFixed32(DefaultSfixed32); + } + if (HasDefaultSfixed64) { + output.WriteRawTag(177, 4); + output.WriteSFixed64(DefaultSfixed64); + } + if (HasDefaultFloat) { + output.WriteRawTag(189, 4); + output.WriteFloat(DefaultFloat); + } + if (HasDefaultDouble) { + output.WriteRawTag(193, 4); + output.WriteDouble(DefaultDouble); + } + if (HasDefaultBool) { + output.WriteRawTag(200, 4); + output.WriteBool(DefaultBool); + } + if (HasDefaultString) { + output.WriteRawTag(210, 4); + output.WriteString(DefaultString); + } + if (HasDefaultBytes) { + output.WriteRawTag(218, 4); + output.WriteBytes(DefaultBytes); + } + if (HasDefaultNestedEnum) { + output.WriteRawTag(136, 5); + output.WriteEnum((int) DefaultNestedEnum); + } + if (HasDefaultForeignEnum) { + output.WriteRawTag(144, 5); + output.WriteEnum((int) DefaultForeignEnum); + } + if (HasDefaultImportEnum) { + output.WriteRawTag(152, 5); + output.WriteEnum((int) DefaultImportEnum); + } + if (HasDefaultStringPiece) { + output.WriteRawTag(162, 5); + output.WriteString(DefaultStringPiece); + } + if (HasDefaultCord) { + output.WriteRawTag(170, 5); + output.WriteString(DefaultCord); + } + if (HasOneofUint32) { + output.WriteRawTag(248, 6); + output.WriteUInt32(OneofUint32); + } + if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) { + output.WriteRawTag(130, 7); + output.WriteMessage(OneofNestedMessage); + } + if (HasOneofString) { + output.WriteRawTag(138, 7); + output.WriteString(OneofString); + } + if (HasOneofBytes) { + output.WriteRawTag(146, 7); + output.WriteBytes(OneofBytes); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasOptionalInt32) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(OptionalInt32); + } + if (HasOptionalInt64) { + size += 1 + pb::CodedOutputStream.ComputeInt64Size(OptionalInt64); + } + if (HasOptionalUint32) { + size += 1 + pb::CodedOutputStream.ComputeUInt32Size(OptionalUint32); + } + if (HasOptionalUint64) { + size += 1 + pb::CodedOutputStream.ComputeUInt64Size(OptionalUint64); + } + if (HasOptionalSint32) { + size += 1 + pb::CodedOutputStream.ComputeSInt32Size(OptionalSint32); + } + if (HasOptionalSint64) { + size += 1 + pb::CodedOutputStream.ComputeSInt64Size(OptionalSint64); + } + if (HasOptionalFixed32) { + size += 1 + 4; + } + if (HasOptionalFixed64) { + size += 1 + 8; + } + if (HasOptionalSfixed32) { + size += 1 + 4; + } + if (HasOptionalSfixed64) { + size += 1 + 8; + } + if (HasOptionalFloat) { + size += 1 + 4; + } + if (HasOptionalDouble) { + size += 1 + 8; + } + if (HasOptionalBool) { + size += 1 + 1; + } + if (HasOptionalString) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(OptionalString); + } + if (HasOptionalBytes) { + size += 1 + pb::CodedOutputStream.ComputeBytesSize(OptionalBytes); + } + if (HasOptionalGroup) { + size += 4 + pb::CodedOutputStream.ComputeGroupSize(OptionalGroup); + } + if (optionalNestedMessage_ != null) { + size += 2 + pb::CodedOutputStream.ComputeMessageSize(OptionalNestedMessage); + } + if (optionalForeignMessage_ != null) { + size += 2 + pb::CodedOutputStream.ComputeMessageSize(OptionalForeignMessage); + } + if (optionalImportMessage_ != null) { + size += 2 + pb::CodedOutputStream.ComputeMessageSize(OptionalImportMessage); + } + if (HasOptionalNestedEnum) { + size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) OptionalNestedEnum); + } + if (HasOptionalForeignEnum) { + size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) OptionalForeignEnum); + } + if (HasOptionalImportEnum) { + size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) OptionalImportEnum); + } + if (HasOptionalStringPiece) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(OptionalStringPiece); + } + if (HasOptionalCord) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(OptionalCord); + } + if (optionalPublicImportMessage_ != null) { + size += 2 + pb::CodedOutputStream.ComputeMessageSize(OptionalPublicImportMessage); + } + if (optionalLazyMessage_ != null) { + size += 2 + pb::CodedOutputStream.ComputeMessageSize(OptionalLazyMessage); + } + size += repeatedInt32_.CalculateSize(_repeated_repeatedInt32_codec); + size += repeatedInt64_.CalculateSize(_repeated_repeatedInt64_codec); + size += repeatedUint32_.CalculateSize(_repeated_repeatedUint32_codec); + size += repeatedUint64_.CalculateSize(_repeated_repeatedUint64_codec); + size += repeatedSint32_.CalculateSize(_repeated_repeatedSint32_codec); + size += repeatedSint64_.CalculateSize(_repeated_repeatedSint64_codec); + size += repeatedFixed32_.CalculateSize(_repeated_repeatedFixed32_codec); + size += repeatedFixed64_.CalculateSize(_repeated_repeatedFixed64_codec); + size += repeatedSfixed32_.CalculateSize(_repeated_repeatedSfixed32_codec); + size += repeatedSfixed64_.CalculateSize(_repeated_repeatedSfixed64_codec); + size += repeatedFloat_.CalculateSize(_repeated_repeatedFloat_codec); + size += repeatedDouble_.CalculateSize(_repeated_repeatedDouble_codec); + size += repeatedBool_.CalculateSize(_repeated_repeatedBool_codec); + size += repeatedString_.CalculateSize(_repeated_repeatedString_codec); + size += repeatedBytes_.CalculateSize(_repeated_repeatedBytes_codec); + size += repeatedGroup_.CalculateSize(_repeated_repeatedGroup_codec); + size += repeatedNestedMessage_.CalculateSize(_repeated_repeatedNestedMessage_codec); + size += repeatedForeignMessage_.CalculateSize(_repeated_repeatedForeignMessage_codec); + size += repeatedImportMessage_.CalculateSize(_repeated_repeatedImportMessage_codec); + size += repeatedNestedEnum_.CalculateSize(_repeated_repeatedNestedEnum_codec); + size += repeatedForeignEnum_.CalculateSize(_repeated_repeatedForeignEnum_codec); + size += repeatedImportEnum_.CalculateSize(_repeated_repeatedImportEnum_codec); + size += repeatedStringPiece_.CalculateSize(_repeated_repeatedStringPiece_codec); + size += repeatedCord_.CalculateSize(_repeated_repeatedCord_codec); + size += repeatedLazyMessage_.CalculateSize(_repeated_repeatedLazyMessage_codec); + if (HasDefaultInt32) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(DefaultInt32); + } + if (HasDefaultInt64) { + size += 2 + pb::CodedOutputStream.ComputeInt64Size(DefaultInt64); + } + if (HasDefaultUint32) { + size += 2 + pb::CodedOutputStream.ComputeUInt32Size(DefaultUint32); + } + if (HasDefaultUint64) { + size += 2 + pb::CodedOutputStream.ComputeUInt64Size(DefaultUint64); + } + if (HasDefaultSint32) { + size += 2 + pb::CodedOutputStream.ComputeSInt32Size(DefaultSint32); + } + if (HasDefaultSint64) { + size += 2 + pb::CodedOutputStream.ComputeSInt64Size(DefaultSint64); + } + if (HasDefaultFixed32) { + size += 2 + 4; + } + if (HasDefaultFixed64) { + size += 2 + 8; + } + if (HasDefaultSfixed32) { + size += 2 + 4; + } + if (HasDefaultSfixed64) { + size += 2 + 8; + } + if (HasDefaultFloat) { + size += 2 + 4; + } + if (HasDefaultDouble) { + size += 2 + 8; + } + if (HasDefaultBool) { + size += 2 + 1; + } + if (HasDefaultString) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(DefaultString); + } + if (HasDefaultBytes) { + size += 2 + pb::CodedOutputStream.ComputeBytesSize(DefaultBytes); + } + if (HasDefaultNestedEnum) { + size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) DefaultNestedEnum); + } + if (HasDefaultForeignEnum) { + size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) DefaultForeignEnum); + } + if (HasDefaultImportEnum) { + size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) DefaultImportEnum); + } + if (HasDefaultStringPiece) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(DefaultStringPiece); + } + if (HasDefaultCord) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(DefaultCord); + } + if (HasOneofUint32) { + size += 2 + pb::CodedOutputStream.ComputeUInt32Size(OneofUint32); + } + if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) { + size += 2 + pb::CodedOutputStream.ComputeMessageSize(OneofNestedMessage); + } + if (HasOneofString) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(OneofString); + } + if (HasOneofBytes) { + size += 2 + pb::CodedOutputStream.ComputeBytesSize(OneofBytes); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestAllTypes other) { + if (other == null) { + return; + } + if (other.HasOptionalInt32) { + OptionalInt32 = other.OptionalInt32; + } + if (other.HasOptionalInt64) { + OptionalInt64 = other.OptionalInt64; + } + if (other.HasOptionalUint32) { + OptionalUint32 = other.OptionalUint32; + } + if (other.HasOptionalUint64) { + OptionalUint64 = other.OptionalUint64; + } + if (other.HasOptionalSint32) { + OptionalSint32 = other.OptionalSint32; + } + if (other.HasOptionalSint64) { + OptionalSint64 = other.OptionalSint64; + } + if (other.HasOptionalFixed32) { + OptionalFixed32 = other.OptionalFixed32; + } + if (other.HasOptionalFixed64) { + OptionalFixed64 = other.OptionalFixed64; + } + if (other.HasOptionalSfixed32) { + OptionalSfixed32 = other.OptionalSfixed32; + } + if (other.HasOptionalSfixed64) { + OptionalSfixed64 = other.OptionalSfixed64; + } + if (other.HasOptionalFloat) { + OptionalFloat = other.OptionalFloat; + } + if (other.HasOptionalDouble) { + OptionalDouble = other.OptionalDouble; + } + if (other.HasOptionalBool) { + OptionalBool = other.OptionalBool; + } + if (other.HasOptionalString) { + OptionalString = other.OptionalString; + } + if (other.HasOptionalBytes) { + OptionalBytes = other.OptionalBytes; + } + if (other.HasOptionalGroup) { + if (!HasOptionalGroup) { + OptionalGroup = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.OptionalGroup(); + } + OptionalGroup.MergeFrom(other.OptionalGroup); + } + if (other.optionalNestedMessage_ != null) { + if (optionalNestedMessage_ == null) { + OptionalNestedMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage(); + } + OptionalNestedMessage.MergeFrom(other.OptionalNestedMessage); + } + if (other.optionalForeignMessage_ != null) { + if (optionalForeignMessage_ == null) { + OptionalForeignMessage = new global::Google.Protobuf.TestProtos.Proto2.ForeignMessage(); + } + OptionalForeignMessage.MergeFrom(other.OptionalForeignMessage); + } + if (other.optionalImportMessage_ != null) { + if (optionalImportMessage_ == null) { + OptionalImportMessage = new global::Google.Protobuf.TestProtos.Proto2.ImportMessage(); + } + OptionalImportMessage.MergeFrom(other.OptionalImportMessage); + } + if (other.HasOptionalNestedEnum) { + OptionalNestedEnum = other.OptionalNestedEnum; + } + if (other.HasOptionalForeignEnum) { + OptionalForeignEnum = other.OptionalForeignEnum; + } + if (other.HasOptionalImportEnum) { + OptionalImportEnum = other.OptionalImportEnum; + } + if (other.HasOptionalStringPiece) { + OptionalStringPiece = other.OptionalStringPiece; + } + if (other.HasOptionalCord) { + OptionalCord = other.OptionalCord; + } + if (other.optionalPublicImportMessage_ != null) { + if (optionalPublicImportMessage_ == null) { + OptionalPublicImportMessage = new global::Google.Protobuf.TestProtos.Proto2.PublicImportMessage(); + } + OptionalPublicImportMessage.MergeFrom(other.OptionalPublicImportMessage); + } + if (other.optionalLazyMessage_ != null) { + if (optionalLazyMessage_ == null) { + OptionalLazyMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage(); + } + OptionalLazyMessage.MergeFrom(other.OptionalLazyMessage); + } + repeatedInt32_.Add(other.repeatedInt32_); + repeatedInt64_.Add(other.repeatedInt64_); + repeatedUint32_.Add(other.repeatedUint32_); + repeatedUint64_.Add(other.repeatedUint64_); + repeatedSint32_.Add(other.repeatedSint32_); + repeatedSint64_.Add(other.repeatedSint64_); + repeatedFixed32_.Add(other.repeatedFixed32_); + repeatedFixed64_.Add(other.repeatedFixed64_); + repeatedSfixed32_.Add(other.repeatedSfixed32_); + repeatedSfixed64_.Add(other.repeatedSfixed64_); + repeatedFloat_.Add(other.repeatedFloat_); + repeatedDouble_.Add(other.repeatedDouble_); + repeatedBool_.Add(other.repeatedBool_); + repeatedString_.Add(other.repeatedString_); + repeatedBytes_.Add(other.repeatedBytes_); + repeatedGroup_.Add(other.repeatedGroup_); + repeatedNestedMessage_.Add(other.repeatedNestedMessage_); + repeatedForeignMessage_.Add(other.repeatedForeignMessage_); + repeatedImportMessage_.Add(other.repeatedImportMessage_); + repeatedNestedEnum_.Add(other.repeatedNestedEnum_); + repeatedForeignEnum_.Add(other.repeatedForeignEnum_); + repeatedImportEnum_.Add(other.repeatedImportEnum_); + repeatedStringPiece_.Add(other.repeatedStringPiece_); + repeatedCord_.Add(other.repeatedCord_); + repeatedLazyMessage_.Add(other.repeatedLazyMessage_); + if (other.HasDefaultInt32) { + DefaultInt32 = other.DefaultInt32; + } + if (other.HasDefaultInt64) { + DefaultInt64 = other.DefaultInt64; + } + if (other.HasDefaultUint32) { + DefaultUint32 = other.DefaultUint32; + } + if (other.HasDefaultUint64) { + DefaultUint64 = other.DefaultUint64; + } + if (other.HasDefaultSint32) { + DefaultSint32 = other.DefaultSint32; + } + if (other.HasDefaultSint64) { + DefaultSint64 = other.DefaultSint64; + } + if (other.HasDefaultFixed32) { + DefaultFixed32 = other.DefaultFixed32; + } + if (other.HasDefaultFixed64) { + DefaultFixed64 = other.DefaultFixed64; + } + if (other.HasDefaultSfixed32) { + DefaultSfixed32 = other.DefaultSfixed32; + } + if (other.HasDefaultSfixed64) { + DefaultSfixed64 = other.DefaultSfixed64; + } + if (other.HasDefaultFloat) { + DefaultFloat = other.DefaultFloat; + } + if (other.HasDefaultDouble) { + DefaultDouble = other.DefaultDouble; + } + if (other.HasDefaultBool) { + DefaultBool = other.DefaultBool; + } + if (other.HasDefaultString) { + DefaultString = other.DefaultString; + } + if (other.HasDefaultBytes) { + DefaultBytes = other.DefaultBytes; + } + if (other.HasDefaultNestedEnum) { + DefaultNestedEnum = other.DefaultNestedEnum; + } + if (other.HasDefaultForeignEnum) { + DefaultForeignEnum = other.DefaultForeignEnum; + } + if (other.HasDefaultImportEnum) { + DefaultImportEnum = other.DefaultImportEnum; + } + if (other.HasDefaultStringPiece) { + DefaultStringPiece = other.DefaultStringPiece; + } + if (other.HasDefaultCord) { + DefaultCord = other.DefaultCord; + } + switch (other.OneofFieldCase) { + case OneofFieldOneofCase.OneofUint32: + OneofUint32 = other.OneofUint32; + break; + case OneofFieldOneofCase.OneofNestedMessage: + if (OneofNestedMessage == null) { + OneofNestedMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage(); + } + OneofNestedMessage.MergeFrom(other.OneofNestedMessage); + break; + case OneofFieldOneofCase.OneofString: + OneofString = other.OneofString; + break; + case OneofFieldOneofCase.OneofBytes: + OneofBytes = other.OneofBytes; + break; + } + + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + OptionalInt32 = input.ReadInt32(); + break; + } + case 16: { + OptionalInt64 = input.ReadInt64(); + break; + } + case 24: { + OptionalUint32 = input.ReadUInt32(); + break; + } + case 32: { + OptionalUint64 = input.ReadUInt64(); + break; + } + case 40: { + OptionalSint32 = input.ReadSInt32(); + break; + } + case 48: { + OptionalSint64 = input.ReadSInt64(); + break; + } + case 61: { + OptionalFixed32 = input.ReadFixed32(); + break; + } + case 65: { + OptionalFixed64 = input.ReadFixed64(); + break; + } + case 77: { + OptionalSfixed32 = input.ReadSFixed32(); + break; + } + case 81: { + OptionalSfixed64 = input.ReadSFixed64(); + break; + } + case 93: { + OptionalFloat = input.ReadFloat(); + break; + } + case 97: { + OptionalDouble = input.ReadDouble(); + break; + } + case 104: { + OptionalBool = input.ReadBool(); + break; + } + case 114: { + OptionalString = input.ReadString(); + break; + } + case 122: { + OptionalBytes = input.ReadBytes(); + break; + } + case 131: { + if (!HasOptionalGroup) { + OptionalGroup = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.OptionalGroup(); + } + input.ReadGroup(OptionalGroup); + break; + } + case 146: { + if (optionalNestedMessage_ == null) { + OptionalNestedMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage(); + } + input.ReadMessage(OptionalNestedMessage); + break; + } + case 154: { + if (optionalForeignMessage_ == null) { + OptionalForeignMessage = new global::Google.Protobuf.TestProtos.Proto2.ForeignMessage(); + } + input.ReadMessage(OptionalForeignMessage); + break; + } + case 162: { + if (optionalImportMessage_ == null) { + OptionalImportMessage = new global::Google.Protobuf.TestProtos.Proto2.ImportMessage(); + } + input.ReadMessage(OptionalImportMessage); + break; + } + case 168: { + OptionalNestedEnum = (global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedEnum) input.ReadEnum(); + break; + } + case 176: { + OptionalForeignEnum = (global::Google.Protobuf.TestProtos.Proto2.ForeignEnum) input.ReadEnum(); + break; + } + case 184: { + OptionalImportEnum = (global::Google.Protobuf.TestProtos.Proto2.ImportEnum) input.ReadEnum(); + break; + } + case 194: { + OptionalStringPiece = input.ReadString(); + break; + } + case 202: { + OptionalCord = input.ReadString(); + break; + } + case 210: { + if (optionalPublicImportMessage_ == null) { + OptionalPublicImportMessage = new global::Google.Protobuf.TestProtos.Proto2.PublicImportMessage(); + } + input.ReadMessage(OptionalPublicImportMessage); + break; + } + case 218: { + if (optionalLazyMessage_ == null) { + OptionalLazyMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage(); + } + input.ReadMessage(OptionalLazyMessage); + break; + } + case 250: + case 248: { + repeatedInt32_.AddEntriesFrom(input, _repeated_repeatedInt32_codec); + break; + } + case 258: + case 256: { + repeatedInt64_.AddEntriesFrom(input, _repeated_repeatedInt64_codec); + break; + } + case 266: + case 264: { + repeatedUint32_.AddEntriesFrom(input, _repeated_repeatedUint32_codec); + break; + } + case 274: + case 272: { + repeatedUint64_.AddEntriesFrom(input, _repeated_repeatedUint64_codec); + break; + } + case 282: + case 280: { + repeatedSint32_.AddEntriesFrom(input, _repeated_repeatedSint32_codec); + break; + } + case 290: + case 288: { + repeatedSint64_.AddEntriesFrom(input, _repeated_repeatedSint64_codec); + break; + } + case 298: + case 301: { + repeatedFixed32_.AddEntriesFrom(input, _repeated_repeatedFixed32_codec); + break; + } + case 306: + case 305: { + repeatedFixed64_.AddEntriesFrom(input, _repeated_repeatedFixed64_codec); + break; + } + case 314: + case 317: { + repeatedSfixed32_.AddEntriesFrom(input, _repeated_repeatedSfixed32_codec); + break; + } + case 322: + case 321: { + repeatedSfixed64_.AddEntriesFrom(input, _repeated_repeatedSfixed64_codec); + break; + } + case 330: + case 333: { + repeatedFloat_.AddEntriesFrom(input, _repeated_repeatedFloat_codec); + break; + } + case 338: + case 337: { + repeatedDouble_.AddEntriesFrom(input, _repeated_repeatedDouble_codec); + break; + } + case 346: + case 344: { + repeatedBool_.AddEntriesFrom(input, _repeated_repeatedBool_codec); + break; + } + case 354: { + repeatedString_.AddEntriesFrom(input, _repeated_repeatedString_codec); + break; + } + case 362: { + repeatedBytes_.AddEntriesFrom(input, _repeated_repeatedBytes_codec); + break; + } + case 371: { + repeatedGroup_.AddEntriesFrom(input, _repeated_repeatedGroup_codec); + break; + } + case 386: { + repeatedNestedMessage_.AddEntriesFrom(input, _repeated_repeatedNestedMessage_codec); + break; + } + case 394: { + repeatedForeignMessage_.AddEntriesFrom(input, _repeated_repeatedForeignMessage_codec); + break; + } + case 402: { + repeatedImportMessage_.AddEntriesFrom(input, _repeated_repeatedImportMessage_codec); + break; + } + case 410: + case 408: { + repeatedNestedEnum_.AddEntriesFrom(input, _repeated_repeatedNestedEnum_codec); + break; + } + case 418: + case 416: { + repeatedForeignEnum_.AddEntriesFrom(input, _repeated_repeatedForeignEnum_codec); + break; + } + case 426: + case 424: { + repeatedImportEnum_.AddEntriesFrom(input, _repeated_repeatedImportEnum_codec); + break; + } + case 434: { + repeatedStringPiece_.AddEntriesFrom(input, _repeated_repeatedStringPiece_codec); + break; + } + case 442: { + repeatedCord_.AddEntriesFrom(input, _repeated_repeatedCord_codec); + break; + } + case 458: { + repeatedLazyMessage_.AddEntriesFrom(input, _repeated_repeatedLazyMessage_codec); + break; + } + case 488: { + DefaultInt32 = input.ReadInt32(); + break; + } + case 496: { + DefaultInt64 = input.ReadInt64(); + break; + } + case 504: { + DefaultUint32 = input.ReadUInt32(); + break; + } + case 512: { + DefaultUint64 = input.ReadUInt64(); + break; + } + case 520: { + DefaultSint32 = input.ReadSInt32(); + break; + } + case 528: { + DefaultSint64 = input.ReadSInt64(); + break; + } + case 541: { + DefaultFixed32 = input.ReadFixed32(); + break; + } + case 545: { + DefaultFixed64 = input.ReadFixed64(); + break; + } + case 557: { + DefaultSfixed32 = input.ReadSFixed32(); + break; + } + case 561: { + DefaultSfixed64 = input.ReadSFixed64(); + break; + } + case 573: { + DefaultFloat = input.ReadFloat(); + break; + } + case 577: { + DefaultDouble = input.ReadDouble(); + break; + } + case 584: { + DefaultBool = input.ReadBool(); + break; + } + case 594: { + DefaultString = input.ReadString(); + break; + } + case 602: { + DefaultBytes = input.ReadBytes(); + break; + } + case 648: { + DefaultNestedEnum = (global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedEnum) input.ReadEnum(); + break; + } + case 656: { + DefaultForeignEnum = (global::Google.Protobuf.TestProtos.Proto2.ForeignEnum) input.ReadEnum(); + break; + } + case 664: { + DefaultImportEnum = (global::Google.Protobuf.TestProtos.Proto2.ImportEnum) input.ReadEnum(); + break; + } + case 674: { + DefaultStringPiece = input.ReadString(); + break; + } + case 682: { + DefaultCord = input.ReadString(); + break; + } + case 888: { + OneofUint32 = input.ReadUInt32(); + break; + } + case 898: { + global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage subBuilder = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage(); + if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) { + subBuilder.MergeFrom(OneofNestedMessage); + } + input.ReadMessage(subBuilder); + OneofNestedMessage = subBuilder; + break; + } + case 906: { + OneofString = input.ReadString(); + break; + } + case 914: { + OneofBytes = input.ReadBytes(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + OptionalInt32 = input.ReadInt32(); + break; + } + case 16: { + OptionalInt64 = input.ReadInt64(); + break; + } + case 24: { + OptionalUint32 = input.ReadUInt32(); + break; + } + case 32: { + OptionalUint64 = input.ReadUInt64(); + break; + } + case 40: { + OptionalSint32 = input.ReadSInt32(); + break; + } + case 48: { + OptionalSint64 = input.ReadSInt64(); + break; + } + case 61: { + OptionalFixed32 = input.ReadFixed32(); + break; + } + case 65: { + OptionalFixed64 = input.ReadFixed64(); + break; + } + case 77: { + OptionalSfixed32 = input.ReadSFixed32(); + break; + } + case 81: { + OptionalSfixed64 = input.ReadSFixed64(); + break; + } + case 93: { + OptionalFloat = input.ReadFloat(); + break; + } + case 97: { + OptionalDouble = input.ReadDouble(); + break; + } + case 104: { + OptionalBool = input.ReadBool(); + break; + } + case 114: { + OptionalString = input.ReadString(); + break; + } + case 122: { + OptionalBytes = input.ReadBytes(); + break; + } + case 131: { + if (!HasOptionalGroup) { + OptionalGroup = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.OptionalGroup(); + } + input.ReadGroup(OptionalGroup); + break; + } + case 146: { + if (optionalNestedMessage_ == null) { + OptionalNestedMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage(); + } + input.ReadMessage(OptionalNestedMessage); + break; + } + case 154: { + if (optionalForeignMessage_ == null) { + OptionalForeignMessage = new global::Google.Protobuf.TestProtos.Proto2.ForeignMessage(); + } + input.ReadMessage(OptionalForeignMessage); + break; + } + case 162: { + if (optionalImportMessage_ == null) { + OptionalImportMessage = new global::Google.Protobuf.TestProtos.Proto2.ImportMessage(); + } + input.ReadMessage(OptionalImportMessage); + break; + } + case 168: { + OptionalNestedEnum = (global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedEnum) input.ReadEnum(); + break; + } + case 176: { + OptionalForeignEnum = (global::Google.Protobuf.TestProtos.Proto2.ForeignEnum) input.ReadEnum(); + break; + } + case 184: { + OptionalImportEnum = (global::Google.Protobuf.TestProtos.Proto2.ImportEnum) input.ReadEnum(); + break; + } + case 194: { + OptionalStringPiece = input.ReadString(); + break; + } + case 202: { + OptionalCord = input.ReadString(); + break; + } + case 210: { + if (optionalPublicImportMessage_ == null) { + OptionalPublicImportMessage = new global::Google.Protobuf.TestProtos.Proto2.PublicImportMessage(); + } + input.ReadMessage(OptionalPublicImportMessage); + break; + } + case 218: { + if (optionalLazyMessage_ == null) { + OptionalLazyMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage(); + } + input.ReadMessage(OptionalLazyMessage); + break; + } + case 250: + case 248: { + repeatedInt32_.AddEntriesFrom(ref input, _repeated_repeatedInt32_codec); + break; + } + case 258: + case 256: { + repeatedInt64_.AddEntriesFrom(ref input, _repeated_repeatedInt64_codec); + break; + } + case 266: + case 264: { + repeatedUint32_.AddEntriesFrom(ref input, _repeated_repeatedUint32_codec); + break; + } + case 274: + case 272: { + repeatedUint64_.AddEntriesFrom(ref input, _repeated_repeatedUint64_codec); + break; + } + case 282: + case 280: { + repeatedSint32_.AddEntriesFrom(ref input, _repeated_repeatedSint32_codec); + break; + } + case 290: + case 288: { + repeatedSint64_.AddEntriesFrom(ref input, _repeated_repeatedSint64_codec); + break; + } + case 298: + case 301: { + repeatedFixed32_.AddEntriesFrom(ref input, _repeated_repeatedFixed32_codec); + break; + } + case 306: + case 305: { + repeatedFixed64_.AddEntriesFrom(ref input, _repeated_repeatedFixed64_codec); + break; + } + case 314: + case 317: { + repeatedSfixed32_.AddEntriesFrom(ref input, _repeated_repeatedSfixed32_codec); + break; + } + case 322: + case 321: { + repeatedSfixed64_.AddEntriesFrom(ref input, _repeated_repeatedSfixed64_codec); + break; + } + case 330: + case 333: { + repeatedFloat_.AddEntriesFrom(ref input, _repeated_repeatedFloat_codec); + break; + } + case 338: + case 337: { + repeatedDouble_.AddEntriesFrom(ref input, _repeated_repeatedDouble_codec); + break; + } + case 346: + case 344: { + repeatedBool_.AddEntriesFrom(ref input, _repeated_repeatedBool_codec); + break; + } + case 354: { + repeatedString_.AddEntriesFrom(ref input, _repeated_repeatedString_codec); + break; + } + case 362: { + repeatedBytes_.AddEntriesFrom(ref input, _repeated_repeatedBytes_codec); + break; + } + case 371: { + repeatedGroup_.AddEntriesFrom(ref input, _repeated_repeatedGroup_codec); + break; + } + case 386: { + repeatedNestedMessage_.AddEntriesFrom(ref input, _repeated_repeatedNestedMessage_codec); + break; + } + case 394: { + repeatedForeignMessage_.AddEntriesFrom(ref input, _repeated_repeatedForeignMessage_codec); + break; + } + case 402: { + repeatedImportMessage_.AddEntriesFrom(ref input, _repeated_repeatedImportMessage_codec); + break; + } + case 410: + case 408: { + repeatedNestedEnum_.AddEntriesFrom(ref input, _repeated_repeatedNestedEnum_codec); + break; + } + case 418: + case 416: { + repeatedForeignEnum_.AddEntriesFrom(ref input, _repeated_repeatedForeignEnum_codec); + break; + } + case 426: + case 424: { + repeatedImportEnum_.AddEntriesFrom(ref input, _repeated_repeatedImportEnum_codec); + break; + } + case 434: { + repeatedStringPiece_.AddEntriesFrom(ref input, _repeated_repeatedStringPiece_codec); + break; + } + case 442: { + repeatedCord_.AddEntriesFrom(ref input, _repeated_repeatedCord_codec); + break; + } + case 458: { + repeatedLazyMessage_.AddEntriesFrom(ref input, _repeated_repeatedLazyMessage_codec); + break; + } + case 488: { + DefaultInt32 = input.ReadInt32(); + break; + } + case 496: { + DefaultInt64 = input.ReadInt64(); + break; + } + case 504: { + DefaultUint32 = input.ReadUInt32(); + break; + } + case 512: { + DefaultUint64 = input.ReadUInt64(); + break; + } + case 520: { + DefaultSint32 = input.ReadSInt32(); + break; + } + case 528: { + DefaultSint64 = input.ReadSInt64(); + break; + } + case 541: { + DefaultFixed32 = input.ReadFixed32(); + break; + } + case 545: { + DefaultFixed64 = input.ReadFixed64(); + break; + } + case 557: { + DefaultSfixed32 = input.ReadSFixed32(); + break; + } + case 561: { + DefaultSfixed64 = input.ReadSFixed64(); + break; + } + case 573: { + DefaultFloat = input.ReadFloat(); + break; + } + case 577: { + DefaultDouble = input.ReadDouble(); + break; + } + case 584: { + DefaultBool = input.ReadBool(); + break; + } + case 594: { + DefaultString = input.ReadString(); + break; + } + case 602: { + DefaultBytes = input.ReadBytes(); + break; + } + case 648: { + DefaultNestedEnum = (global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedEnum) input.ReadEnum(); + break; + } + case 656: { + DefaultForeignEnum = (global::Google.Protobuf.TestProtos.Proto2.ForeignEnum) input.ReadEnum(); + break; + } + case 664: { + DefaultImportEnum = (global::Google.Protobuf.TestProtos.Proto2.ImportEnum) input.ReadEnum(); + break; + } + case 674: { + DefaultStringPiece = input.ReadString(); + break; + } + case 682: { + DefaultCord = input.ReadString(); + break; + } + case 888: { + OneofUint32 = input.ReadUInt32(); + break; + } + case 898: { + global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage subBuilder = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage(); + if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) { + subBuilder.MergeFrom(OneofNestedMessage); + } + input.ReadMessage(subBuilder); + OneofNestedMessage = subBuilder; + break; + } + case 906: { + OneofString = input.ReadString(); + break; + } + case 914: { + OneofBytes = input.ReadBytes(); + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the TestAllTypes message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public enum NestedEnum { + [pbr::OriginalName("FOO")] Foo = 1, + [pbr::OriginalName("BAR")] Bar = 2, + [pbr::OriginalName("BAZ")] Baz = 3, + /// + /// Intentionally negative. + /// + [pbr::OriginalName("NEG")] Neg = -1, + } + + public sealed partial class NestedMessage : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new NestedMessage()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedMessage(NestedMessage other) : this() { + _hasBits0 = other._hasBits0; + bb_ = other.bb_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedMessage Clone() { + return new NestedMessage(this); + } + + /// Field number for the "bb" field. + public const int BbFieldNumber = 1; + private readonly static int BbDefaultValue = 0; + + private int bb_; + /// + /// The field name "b" fails to compile in proto1 because it conflicts with + /// a local variable named "b" in one of the generated methods. Doh. + /// This file needs to compile in proto1 to test backwards-compatibility. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Bb { + get { if ((_hasBits0 & 1) != 0) { return bb_; } else { return BbDefaultValue; } } + set { + _hasBits0 |= 1; + bb_ = value; + } + } + /// Gets whether the "bb" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasBb { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "bb" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearBb() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as NestedMessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(NestedMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Bb != other.Bb) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasBb) hash ^= Bb.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasBb) { + output.WriteRawTag(8); + output.WriteInt32(Bb); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasBb) { + output.WriteRawTag(8); + output.WriteInt32(Bb); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasBb) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Bb); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(NestedMessage other) { + if (other == null) { + return; + } + if (other.HasBb) { + Bb = other.Bb; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Bb = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Bb = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + public sealed partial class OptionalGroup : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new OptionalGroup()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Descriptor.NestedTypes[1]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OptionalGroup() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OptionalGroup(OptionalGroup other) : this() { + _hasBits0 = other._hasBits0; + a_ = other.a_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OptionalGroup Clone() { + return new OptionalGroup(this); + } + + /// Field number for the "a" field. + public const int AFieldNumber = 17; + private readonly static int ADefaultValue = 0; + + private int a_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int A { + get { if ((_hasBits0 & 1) != 0) { return a_; } else { return ADefaultValue; } } + set { + _hasBits0 |= 1; + a_ = value; + } + } + /// Gets whether the "a" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasA { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "a" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearA() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as OptionalGroup); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(OptionalGroup other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (A != other.A) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasA) hash ^= A.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasA) { + output.WriteRawTag(136, 1); + output.WriteInt32(A); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasA) { + output.WriteRawTag(136, 1); + output.WriteInt32(A); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasA) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(A); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(OptionalGroup other) { + if (other == null) { + return; + } + if (other.HasA) { + A = other.A; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 132: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 136: { + A = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 132: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 136: { + A = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + public sealed partial class RepeatedGroup : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new RepeatedGroup()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Descriptor.NestedTypes[2]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public RepeatedGroup() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public RepeatedGroup(RepeatedGroup other) : this() { + _hasBits0 = other._hasBits0; + a_ = other.a_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public RepeatedGroup Clone() { + return new RepeatedGroup(this); + } + + /// Field number for the "a" field. + public const int AFieldNumber = 47; + private readonly static int ADefaultValue = 0; + + private int a_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int A { + get { if ((_hasBits0 & 1) != 0) { return a_; } else { return ADefaultValue; } } + set { + _hasBits0 |= 1; + a_ = value; + } + } + /// Gets whether the "a" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasA { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "a" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearA() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as RepeatedGroup); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(RepeatedGroup other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (A != other.A) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasA) hash ^= A.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasA) { + output.WriteRawTag(248, 2); + output.WriteInt32(A); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasA) { + output.WriteRawTag(248, 2); + output.WriteInt32(A); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasA) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(A); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(RepeatedGroup other) { + if (other == null) { + return; + } + if (other.HasA) { + A = other.A; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 372: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 376: { + A = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 372: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 376: { + A = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + } + #endregion + + } + + /// + /// This proto includes a recursively nested message. + /// + public sealed partial class NestedTestAllTypes : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new NestedTestAllTypes()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[1]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedTestAllTypes() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedTestAllTypes(NestedTestAllTypes other) : this() { + child_ = other.child_ != null ? other.child_.Clone() : null; + payload_ = other.payload_ != null ? other.payload_.Clone() : null; + repeatedChild_ = other.repeatedChild_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedTestAllTypes Clone() { + return new NestedTestAllTypes(this); + } + + /// Field number for the "child" field. + public const int ChildFieldNumber = 1; + private global::Google.Protobuf.TestProtos.Proto2.NestedTestAllTypes child_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.NestedTestAllTypes Child { + get { return child_; } + set { + child_ = value; + } + } + + /// Field number for the "payload" field. + public const int PayloadFieldNumber = 2; + private global::Google.Protobuf.TestProtos.Proto2.TestAllTypes payload_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestAllTypes Payload { + get { return payload_; } + set { + payload_ = value; + } + } + + /// Field number for the "repeated_child" field. + public const int RepeatedChildFieldNumber = 3; + private static readonly pb::FieldCodec _repeated_repeatedChild_codec + = pb::FieldCodec.ForMessage(26, global::Google.Protobuf.TestProtos.Proto2.NestedTestAllTypes.Parser); + private readonly pbc::RepeatedField repeatedChild_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedChild { + get { return repeatedChild_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as NestedTestAllTypes); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(NestedTestAllTypes other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(Child, other.Child)) return false; + if (!object.Equals(Payload, other.Payload)) return false; + if(!repeatedChild_.Equals(other.repeatedChild_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (child_ != null) hash ^= Child.GetHashCode(); + if (payload_ != null) hash ^= Payload.GetHashCode(); + hash ^= repeatedChild_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (child_ != null) { + output.WriteRawTag(10); + output.WriteMessage(Child); + } + if (payload_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Payload); + } + repeatedChild_.WriteTo(output, _repeated_repeatedChild_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (child_ != null) { + output.WriteRawTag(10); + output.WriteMessage(Child); + } + if (payload_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Payload); + } + repeatedChild_.WriteTo(ref output, _repeated_repeatedChild_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (child_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Child); + } + if (payload_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Payload); + } + size += repeatedChild_.CalculateSize(_repeated_repeatedChild_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(NestedTestAllTypes other) { + if (other == null) { + return; + } + if (other.child_ != null) { + if (child_ == null) { + Child = new global::Google.Protobuf.TestProtos.Proto2.NestedTestAllTypes(); + } + Child.MergeFrom(other.Child); + } + if (other.payload_ != null) { + if (payload_ == null) { + Payload = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + Payload.MergeFrom(other.Payload); + } + repeatedChild_.Add(other.repeatedChild_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + if (child_ == null) { + Child = new global::Google.Protobuf.TestProtos.Proto2.NestedTestAllTypes(); + } + input.ReadMessage(Child); + break; + } + case 18: { + if (payload_ == null) { + Payload = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + input.ReadMessage(Payload); + break; + } + case 26: { + repeatedChild_.AddEntriesFrom(input, _repeated_repeatedChild_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + if (child_ == null) { + Child = new global::Google.Protobuf.TestProtos.Proto2.NestedTestAllTypes(); + } + input.ReadMessage(Child); + break; + } + case 18: { + if (payload_ == null) { + Payload = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + input.ReadMessage(Payload); + break; + } + case 26: { + repeatedChild_.AddEntriesFrom(ref input, _repeated_repeatedChild_codec); + break; + } + } + } + } + #endif + + } + + public sealed partial class TestDeprecatedFields : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestDeprecatedFields()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[2]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestDeprecatedFields() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestDeprecatedFields(TestDeprecatedFields other) : this() { + _hasBits0 = other._hasBits0; + deprecatedInt32_ = other.deprecatedInt32_; + switch (other.OneofFieldsCase) { + case OneofFieldsOneofCase.DeprecatedInt32InOneof: + DeprecatedInt32InOneof = other.DeprecatedInt32InOneof; + break; + } + + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestDeprecatedFields Clone() { + return new TestDeprecatedFields(this); + } + + /// Field number for the "deprecated_int32" field. + public const int DeprecatedInt32FieldNumber = 1; + private readonly static int DeprecatedInt32DefaultValue = 0; + + private int deprecatedInt32_; + [global::System.ObsoleteAttribute] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int DeprecatedInt32 { + get { if ((_hasBits0 & 1) != 0) { return deprecatedInt32_; } else { return DeprecatedInt32DefaultValue; } } + set { + _hasBits0 |= 1; + deprecatedInt32_ = value; + } + } + /// Gets whether the "deprecated_int32" field is set + [global::System.ObsoleteAttribute] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDeprecatedInt32 { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "deprecated_int32" field + [global::System.ObsoleteAttribute] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDeprecatedInt32() { + _hasBits0 &= ~1; + } + + /// Field number for the "deprecated_int32_in_oneof" field. + public const int DeprecatedInt32InOneofFieldNumber = 2; + [global::System.ObsoleteAttribute] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int DeprecatedInt32InOneof { + get { return HasDeprecatedInt32InOneof ? (int) oneofFields_ : 0; } + set { + oneofFields_ = value; + oneofFieldsCase_ = OneofFieldsOneofCase.DeprecatedInt32InOneof; + } + } + /// Gets whether the "deprecated_int32_in_oneof" field is set + [global::System.ObsoleteAttribute] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDeprecatedInt32InOneof { + get { return oneofFieldsCase_ == OneofFieldsOneofCase.DeprecatedInt32InOneof; } + } + /// Clears the value of the oneof if it's currently set to "deprecated_int32_in_oneof" + [global::System.ObsoleteAttribute] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDeprecatedInt32InOneof() { + if (HasDeprecatedInt32InOneof) { + ClearOneofFields(); + } + } + + private object oneofFields_; + /// Enum of possible cases for the "oneof_fields" oneof. + public enum OneofFieldsOneofCase { + None = 0, + DeprecatedInt32InOneof = 2, + } + private OneofFieldsOneofCase oneofFieldsCase_ = OneofFieldsOneofCase.None; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneofFieldsOneofCase OneofFieldsCase { + get { return oneofFieldsCase_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOneofFields() { + oneofFieldsCase_ = OneofFieldsOneofCase.None; + oneofFields_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestDeprecatedFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestDeprecatedFields other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (DeprecatedInt32 != other.DeprecatedInt32) return false; + if (DeprecatedInt32InOneof != other.DeprecatedInt32InOneof) return false; + if (OneofFieldsCase != other.OneofFieldsCase) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasDeprecatedInt32) hash ^= DeprecatedInt32.GetHashCode(); + if (HasDeprecatedInt32InOneof) hash ^= DeprecatedInt32InOneof.GetHashCode(); + hash ^= (int) oneofFieldsCase_; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasDeprecatedInt32) { + output.WriteRawTag(8); + output.WriteInt32(DeprecatedInt32); + } + if (HasDeprecatedInt32InOneof) { + output.WriteRawTag(16); + output.WriteInt32(DeprecatedInt32InOneof); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasDeprecatedInt32) { + output.WriteRawTag(8); + output.WriteInt32(DeprecatedInt32); + } + if (HasDeprecatedInt32InOneof) { + output.WriteRawTag(16); + output.WriteInt32(DeprecatedInt32InOneof); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasDeprecatedInt32) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(DeprecatedInt32); + } + if (HasDeprecatedInt32InOneof) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(DeprecatedInt32InOneof); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestDeprecatedFields other) { + if (other == null) { + return; + } + if (other.HasDeprecatedInt32) { + DeprecatedInt32 = other.DeprecatedInt32; + } + switch (other.OneofFieldsCase) { + case OneofFieldsOneofCase.DeprecatedInt32InOneof: + DeprecatedInt32InOneof = other.DeprecatedInt32InOneof; + break; + } + + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + DeprecatedInt32 = input.ReadInt32(); + break; + } + case 16: { + DeprecatedInt32InOneof = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + DeprecatedInt32 = input.ReadInt32(); + break; + } + case 16: { + DeprecatedInt32InOneof = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + [global::System.ObsoleteAttribute] + public sealed partial class TestDeprecatedMessage : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestDeprecatedMessage()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[3]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestDeprecatedMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestDeprecatedMessage(TestDeprecatedMessage other) : this() { + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestDeprecatedMessage Clone() { + return new TestDeprecatedMessage(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestDeprecatedMessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestDeprecatedMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestDeprecatedMessage other) { + if (other == null) { + return; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + } + } + } + #endif + + } + + /// + /// Define these after TestAllTypes to make sure the compiler can handle + /// that. + /// + public sealed partial class ForeignMessage : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ForeignMessage()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[4]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ForeignMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ForeignMessage(ForeignMessage other) : this() { + _hasBits0 = other._hasBits0; + c_ = other.c_; + d_ = other.d_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ForeignMessage Clone() { + return new ForeignMessage(this); + } + + /// Field number for the "c" field. + public const int CFieldNumber = 1; + private readonly static int CDefaultValue = 0; + + private int c_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int C { + get { if ((_hasBits0 & 1) != 0) { return c_; } else { return CDefaultValue; } } + set { + _hasBits0 |= 1; + c_ = value; + } + } + /// Gets whether the "c" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasC { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "c" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearC() { + _hasBits0 &= ~1; + } + + /// Field number for the "d" field. + public const int DFieldNumber = 2; + private readonly static int DDefaultValue = 0; + + private int d_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int D { + get { if ((_hasBits0 & 2) != 0) { return d_; } else { return DDefaultValue; } } + set { + _hasBits0 |= 2; + d_ = value; + } + } + /// Gets whether the "d" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasD { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "d" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearD() { + _hasBits0 &= ~2; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as ForeignMessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(ForeignMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (C != other.C) return false; + if (D != other.D) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasC) hash ^= C.GetHashCode(); + if (HasD) hash ^= D.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasC) { + output.WriteRawTag(8); + output.WriteInt32(C); + } + if (HasD) { + output.WriteRawTag(16); + output.WriteInt32(D); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasC) { + output.WriteRawTag(8); + output.WriteInt32(C); + } + if (HasD) { + output.WriteRawTag(16); + output.WriteInt32(D); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasC) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(C); + } + if (HasD) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(D); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(ForeignMessage other) { + if (other == null) { + return; + } + if (other.HasC) { + C = other.C; + } + if (other.HasD) { + D = other.D; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + C = input.ReadInt32(); + break; + } + case 16: { + D = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + C = input.ReadInt32(); + break; + } + case 16: { + D = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + public sealed partial class TestReservedFields : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestReservedFields()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[5]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestReservedFields() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestReservedFields(TestReservedFields other) : this() { + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestReservedFields Clone() { + return new TestReservedFields(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestReservedFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestReservedFields other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestReservedFields other) { + if (other == null) { + return; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + } + } + } + #endif + + } + + public sealed partial class TestAllExtensions : pb::IExtendableMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestAllExtensions()); + private pb::UnknownFieldSet _unknownFields; + private pb::ExtensionSet _extensions; + private pb::ExtensionSet _Extensions { get { return _extensions; } } + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[6]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestAllExtensions() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestAllExtensions(TestAllExtensions other) : this() { + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + _extensions = pb::ExtensionSet.Clone(other._extensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestAllExtensions Clone() { + return new TestAllExtensions(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestAllExtensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestAllExtensions other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!Equals(_extensions, other._extensions)) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (_extensions != null) { + hash ^= _extensions.GetHashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (_extensions != null) { + _extensions.WriteTo(output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (_extensions != null) { + _extensions.WriteTo(ref output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (_extensions != null) { + size += _extensions.CalculateSize(); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestAllExtensions other) { + if (other == null) { + return; + } + pb::ExtensionSet.MergeFrom(ref _extensions, other._extensions); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + } + break; + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + } + break; + } + } + } + #endif + + public TValue GetExtension(pb::Extension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetOrInitializeExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.GetOrInitialize(ref _extensions, extension); + } + public void SetExtension(pb::Extension extension, TValue value) { + pb::ExtensionSet.Set(ref _extensions, extension, value); + } + public bool HasExtension(pb::Extension extension) { + return pb::ExtensionSet.Has(ref _extensions, extension); + } + public void ClearExtension(pb::Extension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + public void ClearExtension(pb::RepeatedExtension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + + } + + public sealed partial class OptionalGroup_extension : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new OptionalGroup_extension()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[7]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OptionalGroup_extension() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OptionalGroup_extension(OptionalGroup_extension other) : this() { + _hasBits0 = other._hasBits0; + a_ = other.a_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OptionalGroup_extension Clone() { + return new OptionalGroup_extension(this); + } + + /// Field number for the "a" field. + public const int AFieldNumber = 17; + private readonly static int ADefaultValue = 0; + + private int a_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int A { + get { if ((_hasBits0 & 1) != 0) { return a_; } else { return ADefaultValue; } } + set { + _hasBits0 |= 1; + a_ = value; + } + } + /// Gets whether the "a" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasA { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "a" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearA() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as OptionalGroup_extension); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(OptionalGroup_extension other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (A != other.A) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasA) hash ^= A.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasA) { + output.WriteRawTag(136, 1); + output.WriteInt32(A); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasA) { + output.WriteRawTag(136, 1); + output.WriteInt32(A); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasA) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(A); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(OptionalGroup_extension other) { + if (other == null) { + return; + } + if (other.HasA) { + A = other.A; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 132: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 136: { + A = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 132: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 136: { + A = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + public sealed partial class RepeatedGroup_extension : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new RepeatedGroup_extension()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[8]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public RepeatedGroup_extension() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public RepeatedGroup_extension(RepeatedGroup_extension other) : this() { + _hasBits0 = other._hasBits0; + a_ = other.a_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public RepeatedGroup_extension Clone() { + return new RepeatedGroup_extension(this); + } + + /// Field number for the "a" field. + public const int AFieldNumber = 47; + private readonly static int ADefaultValue = 0; + + private int a_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int A { + get { if ((_hasBits0 & 1) != 0) { return a_; } else { return ADefaultValue; } } + set { + _hasBits0 |= 1; + a_ = value; + } + } + /// Gets whether the "a" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasA { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "a" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearA() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as RepeatedGroup_extension); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(RepeatedGroup_extension other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (A != other.A) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasA) hash ^= A.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasA) { + output.WriteRawTag(248, 2); + output.WriteInt32(A); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasA) { + output.WriteRawTag(248, 2); + output.WriteInt32(A); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasA) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(A); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(RepeatedGroup_extension other) { + if (other == null) { + return; + } + if (other.HasA) { + A = other.A; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 372: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 376: { + A = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 372: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 376: { + A = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + public sealed partial class TestGroup : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestGroup()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[9]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestGroup() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestGroup(TestGroup other) : this() { + _hasBits0 = other._hasBits0; + optionalGroup_ = other.HasOptionalGroup ? other.optionalGroup_.Clone() : null; + optionalForeignEnum_ = other.optionalForeignEnum_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestGroup Clone() { + return new TestGroup(this); + } + + /// Field number for the "optionalgroup" field. + public const int OptionalGroupFieldNumber = 16; + private global::Google.Protobuf.TestProtos.Proto2.TestGroup.Types.OptionalGroup optionalGroup_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestGroup.Types.OptionalGroup OptionalGroup { + get { return optionalGroup_; } + set { + optionalGroup_ = value; + } + } + /// Gets whether the optionalgroup field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalGroup { + get { return optionalGroup_ != null; } + } + /// Clears the value of the optionalgroup field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalGroup() { + optionalGroup_ = null; + } + + /// Field number for the "optional_foreign_enum" field. + public const int OptionalForeignEnumFieldNumber = 22; + private readonly static global::Google.Protobuf.TestProtos.Proto2.ForeignEnum OptionalForeignEnumDefaultValue = global::Google.Protobuf.TestProtos.Proto2.ForeignEnum.ForeignFoo; + + private global::Google.Protobuf.TestProtos.Proto2.ForeignEnum optionalForeignEnum_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.ForeignEnum OptionalForeignEnum { + get { if ((_hasBits0 & 1) != 0) { return optionalForeignEnum_; } else { return OptionalForeignEnumDefaultValue; } } + set { + _hasBits0 |= 1; + optionalForeignEnum_ = value; + } + } + /// Gets whether the "optional_foreign_enum" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalForeignEnum { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "optional_foreign_enum" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalForeignEnum() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestGroup); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestGroup other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(OptionalGroup, other.OptionalGroup)) return false; + if (OptionalForeignEnum != other.OptionalForeignEnum) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasOptionalGroup) hash ^= OptionalGroup.GetHashCode(); + if (HasOptionalForeignEnum) hash ^= OptionalForeignEnum.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasOptionalGroup) { + output.WriteRawTag(131, 1); + output.WriteGroup(OptionalGroup); + output.WriteRawTag(132, 1); + } + if (HasOptionalForeignEnum) { + output.WriteRawTag(176, 1); + output.WriteEnum((int) OptionalForeignEnum); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasOptionalGroup) { + output.WriteRawTag(131, 1); + output.WriteGroup(OptionalGroup); + output.WriteRawTag(132, 1); + } + if (HasOptionalForeignEnum) { + output.WriteRawTag(176, 1); + output.WriteEnum((int) OptionalForeignEnum); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasOptionalGroup) { + size += 4 + pb::CodedOutputStream.ComputeGroupSize(OptionalGroup); + } + if (HasOptionalForeignEnum) { + size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) OptionalForeignEnum); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestGroup other) { + if (other == null) { + return; + } + if (other.HasOptionalGroup) { + if (!HasOptionalGroup) { + OptionalGroup = new global::Google.Protobuf.TestProtos.Proto2.TestGroup.Types.OptionalGroup(); + } + OptionalGroup.MergeFrom(other.OptionalGroup); + } + if (other.HasOptionalForeignEnum) { + OptionalForeignEnum = other.OptionalForeignEnum; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 131: { + if (!HasOptionalGroup) { + OptionalGroup = new global::Google.Protobuf.TestProtos.Proto2.TestGroup.Types.OptionalGroup(); + } + input.ReadGroup(OptionalGroup); + break; + } + case 176: { + OptionalForeignEnum = (global::Google.Protobuf.TestProtos.Proto2.ForeignEnum) input.ReadEnum(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 131: { + if (!HasOptionalGroup) { + OptionalGroup = new global::Google.Protobuf.TestProtos.Proto2.TestGroup.Types.OptionalGroup(); + } + input.ReadGroup(OptionalGroup); + break; + } + case 176: { + OptionalForeignEnum = (global::Google.Protobuf.TestProtos.Proto2.ForeignEnum) input.ReadEnum(); + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the TestGroup message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public sealed partial class OptionalGroup : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new OptionalGroup()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestGroup.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OptionalGroup() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OptionalGroup(OptionalGroup other) : this() { + _hasBits0 = other._hasBits0; + a_ = other.a_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OptionalGroup Clone() { + return new OptionalGroup(this); + } + + /// Field number for the "a" field. + public const int AFieldNumber = 17; + private readonly static int ADefaultValue = 0; + + private int a_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int A { + get { if ((_hasBits0 & 1) != 0) { return a_; } else { return ADefaultValue; } } + set { + _hasBits0 |= 1; + a_ = value; + } + } + /// Gets whether the "a" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasA { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "a" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearA() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as OptionalGroup); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(OptionalGroup other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (A != other.A) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasA) hash ^= A.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasA) { + output.WriteRawTag(136, 1); + output.WriteInt32(A); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasA) { + output.WriteRawTag(136, 1); + output.WriteInt32(A); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasA) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(A); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(OptionalGroup other) { + if (other == null) { + return; + } + if (other.HasA) { + A = other.A; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 132: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 136: { + A = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 132: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 136: { + A = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + } + #endregion + + } + + public sealed partial class TestGroupExtension : pb::IExtendableMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestGroupExtension()); + private pb::UnknownFieldSet _unknownFields; + private pb::ExtensionSet _extensions; + private pb::ExtensionSet _Extensions { get { return _extensions; } } + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[10]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestGroupExtension() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestGroupExtension(TestGroupExtension other) : this() { + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + _extensions = pb::ExtensionSet.Clone(other._extensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestGroupExtension Clone() { + return new TestGroupExtension(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestGroupExtension); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestGroupExtension other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!Equals(_extensions, other._extensions)) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (_extensions != null) { + hash ^= _extensions.GetHashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (_extensions != null) { + _extensions.WriteTo(output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (_extensions != null) { + _extensions.WriteTo(ref output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (_extensions != null) { + size += _extensions.CalculateSize(); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestGroupExtension other) { + if (other == null) { + return; + } + pb::ExtensionSet.MergeFrom(ref _extensions, other._extensions); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + } + break; + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + } + break; + } + } + } + #endif + + public TValue GetExtension(pb::Extension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetOrInitializeExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.GetOrInitialize(ref _extensions, extension); + } + public void SetExtension(pb::Extension extension, TValue value) { + pb::ExtensionSet.Set(ref _extensions, extension, value); + } + public bool HasExtension(pb::Extension extension) { + return pb::ExtensionSet.Has(ref _extensions, extension); + } + public void ClearExtension(pb::Extension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + public void ClearExtension(pb::RepeatedExtension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + + } + + public sealed partial class TestNestedExtension : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestNestedExtension()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[11]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestNestedExtension() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestNestedExtension(TestNestedExtension other) : this() { + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestNestedExtension Clone() { + return new TestNestedExtension(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestNestedExtension); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestNestedExtension other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestNestedExtension other) { + if (other == null) { + return; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the TestNestedExtension message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public sealed partial class OptionalGroup_extension : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new OptionalGroup_extension()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestNestedExtension.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OptionalGroup_extension() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OptionalGroup_extension(OptionalGroup_extension other) : this() { + _hasBits0 = other._hasBits0; + a_ = other.a_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OptionalGroup_extension Clone() { + return new OptionalGroup_extension(this); + } + + /// Field number for the "a" field. + public const int AFieldNumber = 17; + private readonly static int ADefaultValue = 0; + + private int a_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int A { + get { if ((_hasBits0 & 1) != 0) { return a_; } else { return ADefaultValue; } } + set { + _hasBits0 |= 1; + a_ = value; + } + } + /// Gets whether the "a" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasA { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "a" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearA() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as OptionalGroup_extension); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(OptionalGroup_extension other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (A != other.A) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasA) hash ^= A.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasA) { + output.WriteRawTag(136, 1); + output.WriteInt32(A); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasA) { + output.WriteRawTag(136, 1); + output.WriteInt32(A); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasA) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(A); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(OptionalGroup_extension other) { + if (other == null) { + return; + } + if (other.HasA) { + A = other.A; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 132: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 136: { + A = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 132: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 136: { + A = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + } + #endregion + + #region Extensions + /// Container for extensions for other messages declared in the TestNestedExtension message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Extensions { + /// + /// Check for bug where string extensions declared in tested scope did not + /// compile. + /// + public static readonly pb::Extension Test = + new pb::Extension(1002, pb::FieldCodec.ForString(8018, global::System.Text.Encoding.UTF8.GetString(global::System.Convert.FromBase64String("dGVzdA=="), 0, 4))); + /// + /// Used to test if generated extension name is correct when there are + /// underscores. + /// + public static readonly pb::Extension NestedStringExtension = + new pb::Extension(1003, pb::FieldCodec.ForString(8026, "")); + public static readonly pb::Extension OptionalGroupExtension = + new pb::Extension(16, pb::FieldCodec.ForGroup(131, 132, global::Google.Protobuf.TestProtos.Proto2.TestNestedExtension.Types.OptionalGroup_extension.Parser)); + public static readonly pb::Extension OptionalForeignEnumExtension = + new pb::Extension(22, pb::FieldCodec.ForEnum(176, x => (int) x, x => (global::Google.Protobuf.TestProtos.Proto2.ForeignEnum) x, global::Google.Protobuf.TestProtos.Proto2.ForeignEnum.ForeignFoo)); + } + #endregion + + } + + /// + /// We have separate messages for testing required fields because it's + /// annoying to have to fill in required fields in TestProto in order to + /// do anything with it. Note that we don't need to test every type of + /// required filed because the code output is basically identical to + /// optional fields for all types. + /// + public sealed partial class TestRequired : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestRequired()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + private int _hasBits1; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[12]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestRequired() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestRequired(TestRequired other) : this() { + _hasBits0 = other._hasBits0; + _hasBits1 = other._hasBits1; + a_ = other.a_; + dummy2_ = other.dummy2_; + b_ = other.b_; + dummy4_ = other.dummy4_; + dummy5_ = other.dummy5_; + dummy6_ = other.dummy6_; + dummy7_ = other.dummy7_; + dummy8_ = other.dummy8_; + dummy9_ = other.dummy9_; + dummy10_ = other.dummy10_; + dummy11_ = other.dummy11_; + dummy12_ = other.dummy12_; + dummy13_ = other.dummy13_; + dummy14_ = other.dummy14_; + dummy15_ = other.dummy15_; + dummy16_ = other.dummy16_; + dummy17_ = other.dummy17_; + dummy18_ = other.dummy18_; + dummy19_ = other.dummy19_; + dummy20_ = other.dummy20_; + dummy21_ = other.dummy21_; + dummy22_ = other.dummy22_; + dummy23_ = other.dummy23_; + dummy24_ = other.dummy24_; + dummy25_ = other.dummy25_; + dummy26_ = other.dummy26_; + dummy27_ = other.dummy27_; + dummy28_ = other.dummy28_; + dummy29_ = other.dummy29_; + dummy30_ = other.dummy30_; + dummy31_ = other.dummy31_; + dummy32_ = other.dummy32_; + c_ = other.c_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestRequired Clone() { + return new TestRequired(this); + } + + /// Field number for the "a" field. + public const int AFieldNumber = 1; + private readonly static int ADefaultValue = 0; + + private int a_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int A { + get { if ((_hasBits0 & 1) != 0) { return a_; } else { return ADefaultValue; } } + set { + _hasBits0 |= 1; + a_ = value; + } + } + /// Gets whether the "a" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasA { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "a" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearA() { + _hasBits0 &= ~1; + } + + /// Field number for the "dummy2" field. + public const int Dummy2FieldNumber = 2; + private readonly static int Dummy2DefaultValue = 0; + + private int dummy2_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy2 { + get { if ((_hasBits0 & 2) != 0) { return dummy2_; } else { return Dummy2DefaultValue; } } + set { + _hasBits0 |= 2; + dummy2_ = value; + } + } + /// Gets whether the "dummy2" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy2 { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "dummy2" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy2() { + _hasBits0 &= ~2; + } + + /// Field number for the "b" field. + public const int BFieldNumber = 3; + private readonly static int BDefaultValue = 0; + + private int b_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int B { + get { if ((_hasBits0 & 4) != 0) { return b_; } else { return BDefaultValue; } } + set { + _hasBits0 |= 4; + b_ = value; + } + } + /// Gets whether the "b" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasB { + get { return (_hasBits0 & 4) != 0; } + } + /// Clears the value of the "b" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearB() { + _hasBits0 &= ~4; + } + + /// Field number for the "dummy4" field. + public const int Dummy4FieldNumber = 4; + private readonly static int Dummy4DefaultValue = 0; + + private int dummy4_; + /// + /// Pad the field count to 32 so that we can test that IsInitialized() + /// properly checks multiple elements of has_bits_. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy4 { + get { if ((_hasBits0 & 8) != 0) { return dummy4_; } else { return Dummy4DefaultValue; } } + set { + _hasBits0 |= 8; + dummy4_ = value; + } + } + /// Gets whether the "dummy4" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy4 { + get { return (_hasBits0 & 8) != 0; } + } + /// Clears the value of the "dummy4" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy4() { + _hasBits0 &= ~8; + } + + /// Field number for the "dummy5" field. + public const int Dummy5FieldNumber = 5; + private readonly static int Dummy5DefaultValue = 0; + + private int dummy5_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy5 { + get { if ((_hasBits0 & 16) != 0) { return dummy5_; } else { return Dummy5DefaultValue; } } + set { + _hasBits0 |= 16; + dummy5_ = value; + } + } + /// Gets whether the "dummy5" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy5 { + get { return (_hasBits0 & 16) != 0; } + } + /// Clears the value of the "dummy5" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy5() { + _hasBits0 &= ~16; + } + + /// Field number for the "dummy6" field. + public const int Dummy6FieldNumber = 6; + private readonly static int Dummy6DefaultValue = 0; + + private int dummy6_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy6 { + get { if ((_hasBits0 & 32) != 0) { return dummy6_; } else { return Dummy6DefaultValue; } } + set { + _hasBits0 |= 32; + dummy6_ = value; + } + } + /// Gets whether the "dummy6" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy6 { + get { return (_hasBits0 & 32) != 0; } + } + /// Clears the value of the "dummy6" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy6() { + _hasBits0 &= ~32; + } + + /// Field number for the "dummy7" field. + public const int Dummy7FieldNumber = 7; + private readonly static int Dummy7DefaultValue = 0; + + private int dummy7_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy7 { + get { if ((_hasBits0 & 64) != 0) { return dummy7_; } else { return Dummy7DefaultValue; } } + set { + _hasBits0 |= 64; + dummy7_ = value; + } + } + /// Gets whether the "dummy7" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy7 { + get { return (_hasBits0 & 64) != 0; } + } + /// Clears the value of the "dummy7" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy7() { + _hasBits0 &= ~64; + } + + /// Field number for the "dummy8" field. + public const int Dummy8FieldNumber = 8; + private readonly static int Dummy8DefaultValue = 0; + + private int dummy8_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy8 { + get { if ((_hasBits0 & 128) != 0) { return dummy8_; } else { return Dummy8DefaultValue; } } + set { + _hasBits0 |= 128; + dummy8_ = value; + } + } + /// Gets whether the "dummy8" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy8 { + get { return (_hasBits0 & 128) != 0; } + } + /// Clears the value of the "dummy8" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy8() { + _hasBits0 &= ~128; + } + + /// Field number for the "dummy9" field. + public const int Dummy9FieldNumber = 9; + private readonly static int Dummy9DefaultValue = 0; + + private int dummy9_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy9 { + get { if ((_hasBits0 & 256) != 0) { return dummy9_; } else { return Dummy9DefaultValue; } } + set { + _hasBits0 |= 256; + dummy9_ = value; + } + } + /// Gets whether the "dummy9" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy9 { + get { return (_hasBits0 & 256) != 0; } + } + /// Clears the value of the "dummy9" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy9() { + _hasBits0 &= ~256; + } + + /// Field number for the "dummy10" field. + public const int Dummy10FieldNumber = 10; + private readonly static int Dummy10DefaultValue = 0; + + private int dummy10_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy10 { + get { if ((_hasBits0 & 512) != 0) { return dummy10_; } else { return Dummy10DefaultValue; } } + set { + _hasBits0 |= 512; + dummy10_ = value; + } + } + /// Gets whether the "dummy10" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy10 { + get { return (_hasBits0 & 512) != 0; } + } + /// Clears the value of the "dummy10" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy10() { + _hasBits0 &= ~512; + } + + /// Field number for the "dummy11" field. + public const int Dummy11FieldNumber = 11; + private readonly static int Dummy11DefaultValue = 0; + + private int dummy11_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy11 { + get { if ((_hasBits0 & 1024) != 0) { return dummy11_; } else { return Dummy11DefaultValue; } } + set { + _hasBits0 |= 1024; + dummy11_ = value; + } + } + /// Gets whether the "dummy11" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy11 { + get { return (_hasBits0 & 1024) != 0; } + } + /// Clears the value of the "dummy11" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy11() { + _hasBits0 &= ~1024; + } + + /// Field number for the "dummy12" field. + public const int Dummy12FieldNumber = 12; + private readonly static int Dummy12DefaultValue = 0; + + private int dummy12_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy12 { + get { if ((_hasBits0 & 2048) != 0) { return dummy12_; } else { return Dummy12DefaultValue; } } + set { + _hasBits0 |= 2048; + dummy12_ = value; + } + } + /// Gets whether the "dummy12" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy12 { + get { return (_hasBits0 & 2048) != 0; } + } + /// Clears the value of the "dummy12" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy12() { + _hasBits0 &= ~2048; + } + + /// Field number for the "dummy13" field. + public const int Dummy13FieldNumber = 13; + private readonly static int Dummy13DefaultValue = 0; + + private int dummy13_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy13 { + get { if ((_hasBits0 & 4096) != 0) { return dummy13_; } else { return Dummy13DefaultValue; } } + set { + _hasBits0 |= 4096; + dummy13_ = value; + } + } + /// Gets whether the "dummy13" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy13 { + get { return (_hasBits0 & 4096) != 0; } + } + /// Clears the value of the "dummy13" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy13() { + _hasBits0 &= ~4096; + } + + /// Field number for the "dummy14" field. + public const int Dummy14FieldNumber = 14; + private readonly static int Dummy14DefaultValue = 0; + + private int dummy14_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy14 { + get { if ((_hasBits0 & 8192) != 0) { return dummy14_; } else { return Dummy14DefaultValue; } } + set { + _hasBits0 |= 8192; + dummy14_ = value; + } + } + /// Gets whether the "dummy14" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy14 { + get { return (_hasBits0 & 8192) != 0; } + } + /// Clears the value of the "dummy14" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy14() { + _hasBits0 &= ~8192; + } + + /// Field number for the "dummy15" field. + public const int Dummy15FieldNumber = 15; + private readonly static int Dummy15DefaultValue = 0; + + private int dummy15_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy15 { + get { if ((_hasBits0 & 16384) != 0) { return dummy15_; } else { return Dummy15DefaultValue; } } + set { + _hasBits0 |= 16384; + dummy15_ = value; + } + } + /// Gets whether the "dummy15" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy15 { + get { return (_hasBits0 & 16384) != 0; } + } + /// Clears the value of the "dummy15" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy15() { + _hasBits0 &= ~16384; + } + + /// Field number for the "dummy16" field. + public const int Dummy16FieldNumber = 16; + private readonly static int Dummy16DefaultValue = 0; + + private int dummy16_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy16 { + get { if ((_hasBits0 & 32768) != 0) { return dummy16_; } else { return Dummy16DefaultValue; } } + set { + _hasBits0 |= 32768; + dummy16_ = value; + } + } + /// Gets whether the "dummy16" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy16 { + get { return (_hasBits0 & 32768) != 0; } + } + /// Clears the value of the "dummy16" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy16() { + _hasBits0 &= ~32768; + } + + /// Field number for the "dummy17" field. + public const int Dummy17FieldNumber = 17; + private readonly static int Dummy17DefaultValue = 0; + + private int dummy17_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy17 { + get { if ((_hasBits0 & 65536) != 0) { return dummy17_; } else { return Dummy17DefaultValue; } } + set { + _hasBits0 |= 65536; + dummy17_ = value; + } + } + /// Gets whether the "dummy17" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy17 { + get { return (_hasBits0 & 65536) != 0; } + } + /// Clears the value of the "dummy17" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy17() { + _hasBits0 &= ~65536; + } + + /// Field number for the "dummy18" field. + public const int Dummy18FieldNumber = 18; + private readonly static int Dummy18DefaultValue = 0; + + private int dummy18_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy18 { + get { if ((_hasBits0 & 131072) != 0) { return dummy18_; } else { return Dummy18DefaultValue; } } + set { + _hasBits0 |= 131072; + dummy18_ = value; + } + } + /// Gets whether the "dummy18" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy18 { + get { return (_hasBits0 & 131072) != 0; } + } + /// Clears the value of the "dummy18" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy18() { + _hasBits0 &= ~131072; + } + + /// Field number for the "dummy19" field. + public const int Dummy19FieldNumber = 19; + private readonly static int Dummy19DefaultValue = 0; + + private int dummy19_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy19 { + get { if ((_hasBits0 & 262144) != 0) { return dummy19_; } else { return Dummy19DefaultValue; } } + set { + _hasBits0 |= 262144; + dummy19_ = value; + } + } + /// Gets whether the "dummy19" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy19 { + get { return (_hasBits0 & 262144) != 0; } + } + /// Clears the value of the "dummy19" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy19() { + _hasBits0 &= ~262144; + } + + /// Field number for the "dummy20" field. + public const int Dummy20FieldNumber = 20; + private readonly static int Dummy20DefaultValue = 0; + + private int dummy20_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy20 { + get { if ((_hasBits0 & 524288) != 0) { return dummy20_; } else { return Dummy20DefaultValue; } } + set { + _hasBits0 |= 524288; + dummy20_ = value; + } + } + /// Gets whether the "dummy20" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy20 { + get { return (_hasBits0 & 524288) != 0; } + } + /// Clears the value of the "dummy20" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy20() { + _hasBits0 &= ~524288; + } + + /// Field number for the "dummy21" field. + public const int Dummy21FieldNumber = 21; + private readonly static int Dummy21DefaultValue = 0; + + private int dummy21_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy21 { + get { if ((_hasBits0 & 1048576) != 0) { return dummy21_; } else { return Dummy21DefaultValue; } } + set { + _hasBits0 |= 1048576; + dummy21_ = value; + } + } + /// Gets whether the "dummy21" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy21 { + get { return (_hasBits0 & 1048576) != 0; } + } + /// Clears the value of the "dummy21" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy21() { + _hasBits0 &= ~1048576; + } + + /// Field number for the "dummy22" field. + public const int Dummy22FieldNumber = 22; + private readonly static int Dummy22DefaultValue = 0; + + private int dummy22_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy22 { + get { if ((_hasBits0 & 2097152) != 0) { return dummy22_; } else { return Dummy22DefaultValue; } } + set { + _hasBits0 |= 2097152; + dummy22_ = value; + } + } + /// Gets whether the "dummy22" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy22 { + get { return (_hasBits0 & 2097152) != 0; } + } + /// Clears the value of the "dummy22" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy22() { + _hasBits0 &= ~2097152; + } + + /// Field number for the "dummy23" field. + public const int Dummy23FieldNumber = 23; + private readonly static int Dummy23DefaultValue = 0; + + private int dummy23_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy23 { + get { if ((_hasBits0 & 4194304) != 0) { return dummy23_; } else { return Dummy23DefaultValue; } } + set { + _hasBits0 |= 4194304; + dummy23_ = value; + } + } + /// Gets whether the "dummy23" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy23 { + get { return (_hasBits0 & 4194304) != 0; } + } + /// Clears the value of the "dummy23" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy23() { + _hasBits0 &= ~4194304; + } + + /// Field number for the "dummy24" field. + public const int Dummy24FieldNumber = 24; + private readonly static int Dummy24DefaultValue = 0; + + private int dummy24_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy24 { + get { if ((_hasBits0 & 8388608) != 0) { return dummy24_; } else { return Dummy24DefaultValue; } } + set { + _hasBits0 |= 8388608; + dummy24_ = value; + } + } + /// Gets whether the "dummy24" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy24 { + get { return (_hasBits0 & 8388608) != 0; } + } + /// Clears the value of the "dummy24" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy24() { + _hasBits0 &= ~8388608; + } + + /// Field number for the "dummy25" field. + public const int Dummy25FieldNumber = 25; + private readonly static int Dummy25DefaultValue = 0; + + private int dummy25_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy25 { + get { if ((_hasBits0 & 16777216) != 0) { return dummy25_; } else { return Dummy25DefaultValue; } } + set { + _hasBits0 |= 16777216; + dummy25_ = value; + } + } + /// Gets whether the "dummy25" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy25 { + get { return (_hasBits0 & 16777216) != 0; } + } + /// Clears the value of the "dummy25" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy25() { + _hasBits0 &= ~16777216; + } + + /// Field number for the "dummy26" field. + public const int Dummy26FieldNumber = 26; + private readonly static int Dummy26DefaultValue = 0; + + private int dummy26_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy26 { + get { if ((_hasBits0 & 33554432) != 0) { return dummy26_; } else { return Dummy26DefaultValue; } } + set { + _hasBits0 |= 33554432; + dummy26_ = value; + } + } + /// Gets whether the "dummy26" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy26 { + get { return (_hasBits0 & 33554432) != 0; } + } + /// Clears the value of the "dummy26" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy26() { + _hasBits0 &= ~33554432; + } + + /// Field number for the "dummy27" field. + public const int Dummy27FieldNumber = 27; + private readonly static int Dummy27DefaultValue = 0; + + private int dummy27_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy27 { + get { if ((_hasBits0 & 67108864) != 0) { return dummy27_; } else { return Dummy27DefaultValue; } } + set { + _hasBits0 |= 67108864; + dummy27_ = value; + } + } + /// Gets whether the "dummy27" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy27 { + get { return (_hasBits0 & 67108864) != 0; } + } + /// Clears the value of the "dummy27" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy27() { + _hasBits0 &= ~67108864; + } + + /// Field number for the "dummy28" field. + public const int Dummy28FieldNumber = 28; + private readonly static int Dummy28DefaultValue = 0; + + private int dummy28_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy28 { + get { if ((_hasBits0 & 134217728) != 0) { return dummy28_; } else { return Dummy28DefaultValue; } } + set { + _hasBits0 |= 134217728; + dummy28_ = value; + } + } + /// Gets whether the "dummy28" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy28 { + get { return (_hasBits0 & 134217728) != 0; } + } + /// Clears the value of the "dummy28" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy28() { + _hasBits0 &= ~134217728; + } + + /// Field number for the "dummy29" field. + public const int Dummy29FieldNumber = 29; + private readonly static int Dummy29DefaultValue = 0; + + private int dummy29_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy29 { + get { if ((_hasBits0 & 268435456) != 0) { return dummy29_; } else { return Dummy29DefaultValue; } } + set { + _hasBits0 |= 268435456; + dummy29_ = value; + } + } + /// Gets whether the "dummy29" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy29 { + get { return (_hasBits0 & 268435456) != 0; } + } + /// Clears the value of the "dummy29" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy29() { + _hasBits0 &= ~268435456; + } + + /// Field number for the "dummy30" field. + public const int Dummy30FieldNumber = 30; + private readonly static int Dummy30DefaultValue = 0; + + private int dummy30_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy30 { + get { if ((_hasBits0 & 536870912) != 0) { return dummy30_; } else { return Dummy30DefaultValue; } } + set { + _hasBits0 |= 536870912; + dummy30_ = value; + } + } + /// Gets whether the "dummy30" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy30 { + get { return (_hasBits0 & 536870912) != 0; } + } + /// Clears the value of the "dummy30" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy30() { + _hasBits0 &= ~536870912; + } + + /// Field number for the "dummy31" field. + public const int Dummy31FieldNumber = 31; + private readonly static int Dummy31DefaultValue = 0; + + private int dummy31_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy31 { + get { if ((_hasBits0 & 1073741824) != 0) { return dummy31_; } else { return Dummy31DefaultValue; } } + set { + _hasBits0 |= 1073741824; + dummy31_ = value; + } + } + /// Gets whether the "dummy31" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy31 { + get { return (_hasBits0 & 1073741824) != 0; } + } + /// Clears the value of the "dummy31" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy31() { + _hasBits0 &= ~1073741824; + } + + /// Field number for the "dummy32" field. + public const int Dummy32FieldNumber = 32; + private readonly static int Dummy32DefaultValue = 0; + + private int dummy32_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy32 { + get { if ((_hasBits0 & -2147483648) != 0) { return dummy32_; } else { return Dummy32DefaultValue; } } + set { + _hasBits0 |= -2147483648; + dummy32_ = value; + } + } + /// Gets whether the "dummy32" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy32 { + get { return (_hasBits0 & -2147483648) != 0; } + } + /// Clears the value of the "dummy32" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy32() { + _hasBits0 &= ~-2147483648; + } + + /// Field number for the "c" field. + public const int CFieldNumber = 33; + private readonly static int CDefaultValue = 0; + + private int c_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int C { + get { if ((_hasBits1 & 1) != 0) { return c_; } else { return CDefaultValue; } } + set { + _hasBits1 |= 1; + c_ = value; + } + } + /// Gets whether the "c" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasC { + get { return (_hasBits1 & 1) != 0; } + } + /// Clears the value of the "c" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearC() { + _hasBits1 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestRequired); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestRequired other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (A != other.A) return false; + if (Dummy2 != other.Dummy2) return false; + if (B != other.B) return false; + if (Dummy4 != other.Dummy4) return false; + if (Dummy5 != other.Dummy5) return false; + if (Dummy6 != other.Dummy6) return false; + if (Dummy7 != other.Dummy7) return false; + if (Dummy8 != other.Dummy8) return false; + if (Dummy9 != other.Dummy9) return false; + if (Dummy10 != other.Dummy10) return false; + if (Dummy11 != other.Dummy11) return false; + if (Dummy12 != other.Dummy12) return false; + if (Dummy13 != other.Dummy13) return false; + if (Dummy14 != other.Dummy14) return false; + if (Dummy15 != other.Dummy15) return false; + if (Dummy16 != other.Dummy16) return false; + if (Dummy17 != other.Dummy17) return false; + if (Dummy18 != other.Dummy18) return false; + if (Dummy19 != other.Dummy19) return false; + if (Dummy20 != other.Dummy20) return false; + if (Dummy21 != other.Dummy21) return false; + if (Dummy22 != other.Dummy22) return false; + if (Dummy23 != other.Dummy23) return false; + if (Dummy24 != other.Dummy24) return false; + if (Dummy25 != other.Dummy25) return false; + if (Dummy26 != other.Dummy26) return false; + if (Dummy27 != other.Dummy27) return false; + if (Dummy28 != other.Dummy28) return false; + if (Dummy29 != other.Dummy29) return false; + if (Dummy30 != other.Dummy30) return false; + if (Dummy31 != other.Dummy31) return false; + if (Dummy32 != other.Dummy32) return false; + if (C != other.C) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasA) hash ^= A.GetHashCode(); + if (HasDummy2) hash ^= Dummy2.GetHashCode(); + if (HasB) hash ^= B.GetHashCode(); + if (HasDummy4) hash ^= Dummy4.GetHashCode(); + if (HasDummy5) hash ^= Dummy5.GetHashCode(); + if (HasDummy6) hash ^= Dummy6.GetHashCode(); + if (HasDummy7) hash ^= Dummy7.GetHashCode(); + if (HasDummy8) hash ^= Dummy8.GetHashCode(); + if (HasDummy9) hash ^= Dummy9.GetHashCode(); + if (HasDummy10) hash ^= Dummy10.GetHashCode(); + if (HasDummy11) hash ^= Dummy11.GetHashCode(); + if (HasDummy12) hash ^= Dummy12.GetHashCode(); + if (HasDummy13) hash ^= Dummy13.GetHashCode(); + if (HasDummy14) hash ^= Dummy14.GetHashCode(); + if (HasDummy15) hash ^= Dummy15.GetHashCode(); + if (HasDummy16) hash ^= Dummy16.GetHashCode(); + if (HasDummy17) hash ^= Dummy17.GetHashCode(); + if (HasDummy18) hash ^= Dummy18.GetHashCode(); + if (HasDummy19) hash ^= Dummy19.GetHashCode(); + if (HasDummy20) hash ^= Dummy20.GetHashCode(); + if (HasDummy21) hash ^= Dummy21.GetHashCode(); + if (HasDummy22) hash ^= Dummy22.GetHashCode(); + if (HasDummy23) hash ^= Dummy23.GetHashCode(); + if (HasDummy24) hash ^= Dummy24.GetHashCode(); + if (HasDummy25) hash ^= Dummy25.GetHashCode(); + if (HasDummy26) hash ^= Dummy26.GetHashCode(); + if (HasDummy27) hash ^= Dummy27.GetHashCode(); + if (HasDummy28) hash ^= Dummy28.GetHashCode(); + if (HasDummy29) hash ^= Dummy29.GetHashCode(); + if (HasDummy30) hash ^= Dummy30.GetHashCode(); + if (HasDummy31) hash ^= Dummy31.GetHashCode(); + if (HasDummy32) hash ^= Dummy32.GetHashCode(); + if (HasC) hash ^= C.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasA) { + output.WriteRawTag(8); + output.WriteInt32(A); + } + if (HasDummy2) { + output.WriteRawTag(16); + output.WriteInt32(Dummy2); + } + if (HasB) { + output.WriteRawTag(24); + output.WriteInt32(B); + } + if (HasDummy4) { + output.WriteRawTag(32); + output.WriteInt32(Dummy4); + } + if (HasDummy5) { + output.WriteRawTag(40); + output.WriteInt32(Dummy5); + } + if (HasDummy6) { + output.WriteRawTag(48); + output.WriteInt32(Dummy6); + } + if (HasDummy7) { + output.WriteRawTag(56); + output.WriteInt32(Dummy7); + } + if (HasDummy8) { + output.WriteRawTag(64); + output.WriteInt32(Dummy8); + } + if (HasDummy9) { + output.WriteRawTag(72); + output.WriteInt32(Dummy9); + } + if (HasDummy10) { + output.WriteRawTag(80); + output.WriteInt32(Dummy10); + } + if (HasDummy11) { + output.WriteRawTag(88); + output.WriteInt32(Dummy11); + } + if (HasDummy12) { + output.WriteRawTag(96); + output.WriteInt32(Dummy12); + } + if (HasDummy13) { + output.WriteRawTag(104); + output.WriteInt32(Dummy13); + } + if (HasDummy14) { + output.WriteRawTag(112); + output.WriteInt32(Dummy14); + } + if (HasDummy15) { + output.WriteRawTag(120); + output.WriteInt32(Dummy15); + } + if (HasDummy16) { + output.WriteRawTag(128, 1); + output.WriteInt32(Dummy16); + } + if (HasDummy17) { + output.WriteRawTag(136, 1); + output.WriteInt32(Dummy17); + } + if (HasDummy18) { + output.WriteRawTag(144, 1); + output.WriteInt32(Dummy18); + } + if (HasDummy19) { + output.WriteRawTag(152, 1); + output.WriteInt32(Dummy19); + } + if (HasDummy20) { + output.WriteRawTag(160, 1); + output.WriteInt32(Dummy20); + } + if (HasDummy21) { + output.WriteRawTag(168, 1); + output.WriteInt32(Dummy21); + } + if (HasDummy22) { + output.WriteRawTag(176, 1); + output.WriteInt32(Dummy22); + } + if (HasDummy23) { + output.WriteRawTag(184, 1); + output.WriteInt32(Dummy23); + } + if (HasDummy24) { + output.WriteRawTag(192, 1); + output.WriteInt32(Dummy24); + } + if (HasDummy25) { + output.WriteRawTag(200, 1); + output.WriteInt32(Dummy25); + } + if (HasDummy26) { + output.WriteRawTag(208, 1); + output.WriteInt32(Dummy26); + } + if (HasDummy27) { + output.WriteRawTag(216, 1); + output.WriteInt32(Dummy27); + } + if (HasDummy28) { + output.WriteRawTag(224, 1); + output.WriteInt32(Dummy28); + } + if (HasDummy29) { + output.WriteRawTag(232, 1); + output.WriteInt32(Dummy29); + } + if (HasDummy30) { + output.WriteRawTag(240, 1); + output.WriteInt32(Dummy30); + } + if (HasDummy31) { + output.WriteRawTag(248, 1); + output.WriteInt32(Dummy31); + } + if (HasDummy32) { + output.WriteRawTag(128, 2); + output.WriteInt32(Dummy32); + } + if (HasC) { + output.WriteRawTag(136, 2); + output.WriteInt32(C); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasA) { + output.WriteRawTag(8); + output.WriteInt32(A); + } + if (HasDummy2) { + output.WriteRawTag(16); + output.WriteInt32(Dummy2); + } + if (HasB) { + output.WriteRawTag(24); + output.WriteInt32(B); + } + if (HasDummy4) { + output.WriteRawTag(32); + output.WriteInt32(Dummy4); + } + if (HasDummy5) { + output.WriteRawTag(40); + output.WriteInt32(Dummy5); + } + if (HasDummy6) { + output.WriteRawTag(48); + output.WriteInt32(Dummy6); + } + if (HasDummy7) { + output.WriteRawTag(56); + output.WriteInt32(Dummy7); + } + if (HasDummy8) { + output.WriteRawTag(64); + output.WriteInt32(Dummy8); + } + if (HasDummy9) { + output.WriteRawTag(72); + output.WriteInt32(Dummy9); + } + if (HasDummy10) { + output.WriteRawTag(80); + output.WriteInt32(Dummy10); + } + if (HasDummy11) { + output.WriteRawTag(88); + output.WriteInt32(Dummy11); + } + if (HasDummy12) { + output.WriteRawTag(96); + output.WriteInt32(Dummy12); + } + if (HasDummy13) { + output.WriteRawTag(104); + output.WriteInt32(Dummy13); + } + if (HasDummy14) { + output.WriteRawTag(112); + output.WriteInt32(Dummy14); + } + if (HasDummy15) { + output.WriteRawTag(120); + output.WriteInt32(Dummy15); + } + if (HasDummy16) { + output.WriteRawTag(128, 1); + output.WriteInt32(Dummy16); + } + if (HasDummy17) { + output.WriteRawTag(136, 1); + output.WriteInt32(Dummy17); + } + if (HasDummy18) { + output.WriteRawTag(144, 1); + output.WriteInt32(Dummy18); + } + if (HasDummy19) { + output.WriteRawTag(152, 1); + output.WriteInt32(Dummy19); + } + if (HasDummy20) { + output.WriteRawTag(160, 1); + output.WriteInt32(Dummy20); + } + if (HasDummy21) { + output.WriteRawTag(168, 1); + output.WriteInt32(Dummy21); + } + if (HasDummy22) { + output.WriteRawTag(176, 1); + output.WriteInt32(Dummy22); + } + if (HasDummy23) { + output.WriteRawTag(184, 1); + output.WriteInt32(Dummy23); + } + if (HasDummy24) { + output.WriteRawTag(192, 1); + output.WriteInt32(Dummy24); + } + if (HasDummy25) { + output.WriteRawTag(200, 1); + output.WriteInt32(Dummy25); + } + if (HasDummy26) { + output.WriteRawTag(208, 1); + output.WriteInt32(Dummy26); + } + if (HasDummy27) { + output.WriteRawTag(216, 1); + output.WriteInt32(Dummy27); + } + if (HasDummy28) { + output.WriteRawTag(224, 1); + output.WriteInt32(Dummy28); + } + if (HasDummy29) { + output.WriteRawTag(232, 1); + output.WriteInt32(Dummy29); + } + if (HasDummy30) { + output.WriteRawTag(240, 1); + output.WriteInt32(Dummy30); + } + if (HasDummy31) { + output.WriteRawTag(248, 1); + output.WriteInt32(Dummy31); + } + if (HasDummy32) { + output.WriteRawTag(128, 2); + output.WriteInt32(Dummy32); + } + if (HasC) { + output.WriteRawTag(136, 2); + output.WriteInt32(C); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasA) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(A); + } + if (HasDummy2) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Dummy2); + } + if (HasB) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(B); + } + if (HasDummy4) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Dummy4); + } + if (HasDummy5) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Dummy5); + } + if (HasDummy6) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Dummy6); + } + if (HasDummy7) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Dummy7); + } + if (HasDummy8) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Dummy8); + } + if (HasDummy9) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Dummy9); + } + if (HasDummy10) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Dummy10); + } + if (HasDummy11) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Dummy11); + } + if (HasDummy12) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Dummy12); + } + if (HasDummy13) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Dummy13); + } + if (HasDummy14) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Dummy14); + } + if (HasDummy15) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Dummy15); + } + if (HasDummy16) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(Dummy16); + } + if (HasDummy17) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(Dummy17); + } + if (HasDummy18) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(Dummy18); + } + if (HasDummy19) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(Dummy19); + } + if (HasDummy20) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(Dummy20); + } + if (HasDummy21) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(Dummy21); + } + if (HasDummy22) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(Dummy22); + } + if (HasDummy23) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(Dummy23); + } + if (HasDummy24) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(Dummy24); + } + if (HasDummy25) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(Dummy25); + } + if (HasDummy26) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(Dummy26); + } + if (HasDummy27) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(Dummy27); + } + if (HasDummy28) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(Dummy28); + } + if (HasDummy29) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(Dummy29); + } + if (HasDummy30) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(Dummy30); + } + if (HasDummy31) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(Dummy31); + } + if (HasDummy32) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(Dummy32); + } + if (HasC) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(C); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestRequired other) { + if (other == null) { + return; + } + if (other.HasA) { + A = other.A; + } + if (other.HasDummy2) { + Dummy2 = other.Dummy2; + } + if (other.HasB) { + B = other.B; + } + if (other.HasDummy4) { + Dummy4 = other.Dummy4; + } + if (other.HasDummy5) { + Dummy5 = other.Dummy5; + } + if (other.HasDummy6) { + Dummy6 = other.Dummy6; + } + if (other.HasDummy7) { + Dummy7 = other.Dummy7; + } + if (other.HasDummy8) { + Dummy8 = other.Dummy8; + } + if (other.HasDummy9) { + Dummy9 = other.Dummy9; + } + if (other.HasDummy10) { + Dummy10 = other.Dummy10; + } + if (other.HasDummy11) { + Dummy11 = other.Dummy11; + } + if (other.HasDummy12) { + Dummy12 = other.Dummy12; + } + if (other.HasDummy13) { + Dummy13 = other.Dummy13; + } + if (other.HasDummy14) { + Dummy14 = other.Dummy14; + } + if (other.HasDummy15) { + Dummy15 = other.Dummy15; + } + if (other.HasDummy16) { + Dummy16 = other.Dummy16; + } + if (other.HasDummy17) { + Dummy17 = other.Dummy17; + } + if (other.HasDummy18) { + Dummy18 = other.Dummy18; + } + if (other.HasDummy19) { + Dummy19 = other.Dummy19; + } + if (other.HasDummy20) { + Dummy20 = other.Dummy20; + } + if (other.HasDummy21) { + Dummy21 = other.Dummy21; + } + if (other.HasDummy22) { + Dummy22 = other.Dummy22; + } + if (other.HasDummy23) { + Dummy23 = other.Dummy23; + } + if (other.HasDummy24) { + Dummy24 = other.Dummy24; + } + if (other.HasDummy25) { + Dummy25 = other.Dummy25; + } + if (other.HasDummy26) { + Dummy26 = other.Dummy26; + } + if (other.HasDummy27) { + Dummy27 = other.Dummy27; + } + if (other.HasDummy28) { + Dummy28 = other.Dummy28; + } + if (other.HasDummy29) { + Dummy29 = other.Dummy29; + } + if (other.HasDummy30) { + Dummy30 = other.Dummy30; + } + if (other.HasDummy31) { + Dummy31 = other.Dummy31; + } + if (other.HasDummy32) { + Dummy32 = other.Dummy32; + } + if (other.HasC) { + C = other.C; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + A = input.ReadInt32(); + break; + } + case 16: { + Dummy2 = input.ReadInt32(); + break; + } + case 24: { + B = input.ReadInt32(); + break; + } + case 32: { + Dummy4 = input.ReadInt32(); + break; + } + case 40: { + Dummy5 = input.ReadInt32(); + break; + } + case 48: { + Dummy6 = input.ReadInt32(); + break; + } + case 56: { + Dummy7 = input.ReadInt32(); + break; + } + case 64: { + Dummy8 = input.ReadInt32(); + break; + } + case 72: { + Dummy9 = input.ReadInt32(); + break; + } + case 80: { + Dummy10 = input.ReadInt32(); + break; + } + case 88: { + Dummy11 = input.ReadInt32(); + break; + } + case 96: { + Dummy12 = input.ReadInt32(); + break; + } + case 104: { + Dummy13 = input.ReadInt32(); + break; + } + case 112: { + Dummy14 = input.ReadInt32(); + break; + } + case 120: { + Dummy15 = input.ReadInt32(); + break; + } + case 128: { + Dummy16 = input.ReadInt32(); + break; + } + case 136: { + Dummy17 = input.ReadInt32(); + break; + } + case 144: { + Dummy18 = input.ReadInt32(); + break; + } + case 152: { + Dummy19 = input.ReadInt32(); + break; + } + case 160: { + Dummy20 = input.ReadInt32(); + break; + } + case 168: { + Dummy21 = input.ReadInt32(); + break; + } + case 176: { + Dummy22 = input.ReadInt32(); + break; + } + case 184: { + Dummy23 = input.ReadInt32(); + break; + } + case 192: { + Dummy24 = input.ReadInt32(); + break; + } + case 200: { + Dummy25 = input.ReadInt32(); + break; + } + case 208: { + Dummy26 = input.ReadInt32(); + break; + } + case 216: { + Dummy27 = input.ReadInt32(); + break; + } + case 224: { + Dummy28 = input.ReadInt32(); + break; + } + case 232: { + Dummy29 = input.ReadInt32(); + break; + } + case 240: { + Dummy30 = input.ReadInt32(); + break; + } + case 248: { + Dummy31 = input.ReadInt32(); + break; + } + case 256: { + Dummy32 = input.ReadInt32(); + break; + } + case 264: { + C = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + A = input.ReadInt32(); + break; + } + case 16: { + Dummy2 = input.ReadInt32(); + break; + } + case 24: { + B = input.ReadInt32(); + break; + } + case 32: { + Dummy4 = input.ReadInt32(); + break; + } + case 40: { + Dummy5 = input.ReadInt32(); + break; + } + case 48: { + Dummy6 = input.ReadInt32(); + break; + } + case 56: { + Dummy7 = input.ReadInt32(); + break; + } + case 64: { + Dummy8 = input.ReadInt32(); + break; + } + case 72: { + Dummy9 = input.ReadInt32(); + break; + } + case 80: { + Dummy10 = input.ReadInt32(); + break; + } + case 88: { + Dummy11 = input.ReadInt32(); + break; + } + case 96: { + Dummy12 = input.ReadInt32(); + break; + } + case 104: { + Dummy13 = input.ReadInt32(); + break; + } + case 112: { + Dummy14 = input.ReadInt32(); + break; + } + case 120: { + Dummy15 = input.ReadInt32(); + break; + } + case 128: { + Dummy16 = input.ReadInt32(); + break; + } + case 136: { + Dummy17 = input.ReadInt32(); + break; + } + case 144: { + Dummy18 = input.ReadInt32(); + break; + } + case 152: { + Dummy19 = input.ReadInt32(); + break; + } + case 160: { + Dummy20 = input.ReadInt32(); + break; + } + case 168: { + Dummy21 = input.ReadInt32(); + break; + } + case 176: { + Dummy22 = input.ReadInt32(); + break; + } + case 184: { + Dummy23 = input.ReadInt32(); + break; + } + case 192: { + Dummy24 = input.ReadInt32(); + break; + } + case 200: { + Dummy25 = input.ReadInt32(); + break; + } + case 208: { + Dummy26 = input.ReadInt32(); + break; + } + case 216: { + Dummy27 = input.ReadInt32(); + break; + } + case 224: { + Dummy28 = input.ReadInt32(); + break; + } + case 232: { + Dummy29 = input.ReadInt32(); + break; + } + case 240: { + Dummy30 = input.ReadInt32(); + break; + } + case 248: { + Dummy31 = input.ReadInt32(); + break; + } + case 256: { + Dummy32 = input.ReadInt32(); + break; + } + case 264: { + C = input.ReadInt32(); + break; + } + } + } + } + #endif + + #region Extensions + /// Container for extensions for other messages declared in the TestRequired message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Extensions { + public static readonly pb::Extension Single = + new pb::Extension(1000, pb::FieldCodec.ForMessage(8002, global::Google.Protobuf.TestProtos.Proto2.TestRequired.Parser)); + public static readonly pb::RepeatedExtension Multi = + new pb::RepeatedExtension(1001, pb::FieldCodec.ForMessage(8010, global::Google.Protobuf.TestProtos.Proto2.TestRequired.Parser)); + } + #endregion + + } + + public sealed partial class TestRequiredForeign : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestRequiredForeign()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[13]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestRequiredForeign() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestRequiredForeign(TestRequiredForeign other) : this() { + _hasBits0 = other._hasBits0; + optionalMessage_ = other.optionalMessage_ != null ? other.optionalMessage_.Clone() : null; + repeatedMessage_ = other.repeatedMessage_.Clone(); + dummy_ = other.dummy_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestRequiredForeign Clone() { + return new TestRequiredForeign(this); + } + + /// Field number for the "optional_message" field. + public const int OptionalMessageFieldNumber = 1; + private global::Google.Protobuf.TestProtos.Proto2.TestRequired optionalMessage_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestRequired OptionalMessage { + get { return optionalMessage_; } + set { + optionalMessage_ = value; + } + } + + /// Field number for the "repeated_message" field. + public const int RepeatedMessageFieldNumber = 2; + private static readonly pb::FieldCodec _repeated_repeatedMessage_codec + = pb::FieldCodec.ForMessage(18, global::Google.Protobuf.TestProtos.Proto2.TestRequired.Parser); + private readonly pbc::RepeatedField repeatedMessage_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedMessage { + get { return repeatedMessage_; } + } + + /// Field number for the "dummy" field. + public const int DummyFieldNumber = 3; + private readonly static int DummyDefaultValue = 0; + + private int dummy_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Dummy { + get { if ((_hasBits0 & 1) != 0) { return dummy_; } else { return DummyDefaultValue; } } + set { + _hasBits0 |= 1; + dummy_ = value; + } + } + /// Gets whether the "dummy" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDummy { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "dummy" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDummy() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestRequiredForeign); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestRequiredForeign other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(OptionalMessage, other.OptionalMessage)) return false; + if(!repeatedMessage_.Equals(other.repeatedMessage_)) return false; + if (Dummy != other.Dummy) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (optionalMessage_ != null) hash ^= OptionalMessage.GetHashCode(); + hash ^= repeatedMessage_.GetHashCode(); + if (HasDummy) hash ^= Dummy.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (optionalMessage_ != null) { + output.WriteRawTag(10); + output.WriteMessage(OptionalMessage); + } + repeatedMessage_.WriteTo(output, _repeated_repeatedMessage_codec); + if (HasDummy) { + output.WriteRawTag(24); + output.WriteInt32(Dummy); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (optionalMessage_ != null) { + output.WriteRawTag(10); + output.WriteMessage(OptionalMessage); + } + repeatedMessage_.WriteTo(ref output, _repeated_repeatedMessage_codec); + if (HasDummy) { + output.WriteRawTag(24); + output.WriteInt32(Dummy); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (optionalMessage_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(OptionalMessage); + } + size += repeatedMessage_.CalculateSize(_repeated_repeatedMessage_codec); + if (HasDummy) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Dummy); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestRequiredForeign other) { + if (other == null) { + return; + } + if (other.optionalMessage_ != null) { + if (optionalMessage_ == null) { + OptionalMessage = new global::Google.Protobuf.TestProtos.Proto2.TestRequired(); + } + OptionalMessage.MergeFrom(other.OptionalMessage); + } + repeatedMessage_.Add(other.repeatedMessage_); + if (other.HasDummy) { + Dummy = other.Dummy; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + if (optionalMessage_ == null) { + OptionalMessage = new global::Google.Protobuf.TestProtos.Proto2.TestRequired(); + } + input.ReadMessage(OptionalMessage); + break; + } + case 18: { + repeatedMessage_.AddEntriesFrom(input, _repeated_repeatedMessage_codec); + break; + } + case 24: { + Dummy = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + if (optionalMessage_ == null) { + OptionalMessage = new global::Google.Protobuf.TestProtos.Proto2.TestRequired(); + } + input.ReadMessage(OptionalMessage); + break; + } + case 18: { + repeatedMessage_.AddEntriesFrom(ref input, _repeated_repeatedMessage_codec); + break; + } + case 24: { + Dummy = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + public sealed partial class TestRequiredMessage : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestRequiredMessage()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[14]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestRequiredMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestRequiredMessage(TestRequiredMessage other) : this() { + optionalMessage_ = other.optionalMessage_ != null ? other.optionalMessage_.Clone() : null; + repeatedMessage_ = other.repeatedMessage_.Clone(); + requiredMessage_ = other.requiredMessage_ != null ? other.requiredMessage_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestRequiredMessage Clone() { + return new TestRequiredMessage(this); + } + + /// Field number for the "optional_message" field. + public const int OptionalMessageFieldNumber = 1; + private global::Google.Protobuf.TestProtos.Proto2.TestRequired optionalMessage_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestRequired OptionalMessage { + get { return optionalMessage_; } + set { + optionalMessage_ = value; + } + } + + /// Field number for the "repeated_message" field. + public const int RepeatedMessageFieldNumber = 2; + private static readonly pb::FieldCodec _repeated_repeatedMessage_codec + = pb::FieldCodec.ForMessage(18, global::Google.Protobuf.TestProtos.Proto2.TestRequired.Parser); + private readonly pbc::RepeatedField repeatedMessage_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedMessage { + get { return repeatedMessage_; } + } + + /// Field number for the "required_message" field. + public const int RequiredMessageFieldNumber = 3; + private global::Google.Protobuf.TestProtos.Proto2.TestRequired requiredMessage_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestRequired RequiredMessage { + get { return requiredMessage_; } + set { + requiredMessage_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestRequiredMessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestRequiredMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(OptionalMessage, other.OptionalMessage)) return false; + if(!repeatedMessage_.Equals(other.repeatedMessage_)) return false; + if (!object.Equals(RequiredMessage, other.RequiredMessage)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (optionalMessage_ != null) hash ^= OptionalMessage.GetHashCode(); + hash ^= repeatedMessage_.GetHashCode(); + if (requiredMessage_ != null) hash ^= RequiredMessage.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (optionalMessage_ != null) { + output.WriteRawTag(10); + output.WriteMessage(OptionalMessage); + } + repeatedMessage_.WriteTo(output, _repeated_repeatedMessage_codec); + if (requiredMessage_ != null) { + output.WriteRawTag(26); + output.WriteMessage(RequiredMessage); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (optionalMessage_ != null) { + output.WriteRawTag(10); + output.WriteMessage(OptionalMessage); + } + repeatedMessage_.WriteTo(ref output, _repeated_repeatedMessage_codec); + if (requiredMessage_ != null) { + output.WriteRawTag(26); + output.WriteMessage(RequiredMessage); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (optionalMessage_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(OptionalMessage); + } + size += repeatedMessage_.CalculateSize(_repeated_repeatedMessage_codec); + if (requiredMessage_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(RequiredMessage); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestRequiredMessage other) { + if (other == null) { + return; + } + if (other.optionalMessage_ != null) { + if (optionalMessage_ == null) { + OptionalMessage = new global::Google.Protobuf.TestProtos.Proto2.TestRequired(); + } + OptionalMessage.MergeFrom(other.OptionalMessage); + } + repeatedMessage_.Add(other.repeatedMessage_); + if (other.requiredMessage_ != null) { + if (requiredMessage_ == null) { + RequiredMessage = new global::Google.Protobuf.TestProtos.Proto2.TestRequired(); + } + RequiredMessage.MergeFrom(other.RequiredMessage); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + if (optionalMessage_ == null) { + OptionalMessage = new global::Google.Protobuf.TestProtos.Proto2.TestRequired(); + } + input.ReadMessage(OptionalMessage); + break; + } + case 18: { + repeatedMessage_.AddEntriesFrom(input, _repeated_repeatedMessage_codec); + break; + } + case 26: { + if (requiredMessage_ == null) { + RequiredMessage = new global::Google.Protobuf.TestProtos.Proto2.TestRequired(); + } + input.ReadMessage(RequiredMessage); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + if (optionalMessage_ == null) { + OptionalMessage = new global::Google.Protobuf.TestProtos.Proto2.TestRequired(); + } + input.ReadMessage(OptionalMessage); + break; + } + case 18: { + repeatedMessage_.AddEntriesFrom(ref input, _repeated_repeatedMessage_codec); + break; + } + case 26: { + if (requiredMessage_ == null) { + RequiredMessage = new global::Google.Protobuf.TestProtos.Proto2.TestRequired(); + } + input.ReadMessage(RequiredMessage); + break; + } + } + } + } + #endif + + } + + /// + /// Test that we can use NestedMessage from outside TestAllTypes. + /// + public sealed partial class TestForeignNested : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestForeignNested()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[15]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestForeignNested() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestForeignNested(TestForeignNested other) : this() { + foreignNested_ = other.foreignNested_ != null ? other.foreignNested_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestForeignNested Clone() { + return new TestForeignNested(this); + } + + /// Field number for the "foreign_nested" field. + public const int ForeignNestedFieldNumber = 1; + private global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage foreignNested_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage ForeignNested { + get { return foreignNested_; } + set { + foreignNested_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestForeignNested); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestForeignNested other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(ForeignNested, other.ForeignNested)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (foreignNested_ != null) hash ^= ForeignNested.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (foreignNested_ != null) { + output.WriteRawTag(10); + output.WriteMessage(ForeignNested); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (foreignNested_ != null) { + output.WriteRawTag(10); + output.WriteMessage(ForeignNested); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (foreignNested_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(ForeignNested); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestForeignNested other) { + if (other == null) { + return; + } + if (other.foreignNested_ != null) { + if (foreignNested_ == null) { + ForeignNested = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage(); + } + ForeignNested.MergeFrom(other.ForeignNested); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + if (foreignNested_ == null) { + ForeignNested = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage(); + } + input.ReadMessage(ForeignNested); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + if (foreignNested_ == null) { + ForeignNested = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Types.NestedMessage(); + } + input.ReadMessage(ForeignNested); + break; + } + } + } + } + #endif + + } + + /// + /// TestEmptyMessage is used to test unknown field support. + /// + public sealed partial class TestEmptyMessage : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestEmptyMessage()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[16]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestEmptyMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestEmptyMessage(TestEmptyMessage other) : this() { + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestEmptyMessage Clone() { + return new TestEmptyMessage(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestEmptyMessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestEmptyMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestEmptyMessage other) { + if (other == null) { + return; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + } + } + } + #endif + + } + + /// + /// Like above, but declare all field numbers as potential extensions. No + /// actual extensions should ever be defined for this type. + /// + public sealed partial class TestEmptyMessageWithExtensions : pb::IExtendableMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestEmptyMessageWithExtensions()); + private pb::UnknownFieldSet _unknownFields; + private pb::ExtensionSet _extensions; + private pb::ExtensionSet _Extensions { get { return _extensions; } } + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[17]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestEmptyMessageWithExtensions() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestEmptyMessageWithExtensions(TestEmptyMessageWithExtensions other) : this() { + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + _extensions = pb::ExtensionSet.Clone(other._extensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestEmptyMessageWithExtensions Clone() { + return new TestEmptyMessageWithExtensions(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestEmptyMessageWithExtensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestEmptyMessageWithExtensions other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!Equals(_extensions, other._extensions)) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (_extensions != null) { + hash ^= _extensions.GetHashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (_extensions != null) { + _extensions.WriteTo(output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (_extensions != null) { + _extensions.WriteTo(ref output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (_extensions != null) { + size += _extensions.CalculateSize(); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestEmptyMessageWithExtensions other) { + if (other == null) { + return; + } + pb::ExtensionSet.MergeFrom(ref _extensions, other._extensions); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + } + break; + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + } + break; + } + } + } + #endif + + public TValue GetExtension(pb::Extension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetOrInitializeExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.GetOrInitialize(ref _extensions, extension); + } + public void SetExtension(pb::Extension extension, TValue value) { + pb::ExtensionSet.Set(ref _extensions, extension, value); + } + public bool HasExtension(pb::Extension extension) { + return pb::ExtensionSet.Has(ref _extensions, extension); + } + public void ClearExtension(pb::Extension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + public void ClearExtension(pb::RepeatedExtension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + + } + + public sealed partial class TestMultipleExtensionRanges : pb::IExtendableMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestMultipleExtensionRanges()); + private pb::UnknownFieldSet _unknownFields; + private pb::ExtensionSet _extensions; + private pb::ExtensionSet _Extensions { get { return _extensions; } } + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[18]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestMultipleExtensionRanges() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestMultipleExtensionRanges(TestMultipleExtensionRanges other) : this() { + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + _extensions = pb::ExtensionSet.Clone(other._extensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestMultipleExtensionRanges Clone() { + return new TestMultipleExtensionRanges(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestMultipleExtensionRanges); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestMultipleExtensionRanges other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!Equals(_extensions, other._extensions)) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (_extensions != null) { + hash ^= _extensions.GetHashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (_extensions != null) { + _extensions.WriteTo(output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (_extensions != null) { + _extensions.WriteTo(ref output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (_extensions != null) { + size += _extensions.CalculateSize(); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestMultipleExtensionRanges other) { + if (other == null) { + return; + } + pb::ExtensionSet.MergeFrom(ref _extensions, other._extensions); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + } + break; + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + } + break; + } + } + } + #endif + + public TValue GetExtension(pb::Extension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetOrInitializeExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.GetOrInitialize(ref _extensions, extension); + } + public void SetExtension(pb::Extension extension, TValue value) { + pb::ExtensionSet.Set(ref _extensions, extension, value); + } + public bool HasExtension(pb::Extension extension) { + return pb::ExtensionSet.Has(ref _extensions, extension); + } + public void ClearExtension(pb::Extension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + public void ClearExtension(pb::RepeatedExtension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + + } + + /// + /// Test that really large tag numbers don't break anything. + /// + public sealed partial class TestReallyLargeTagNumber : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestReallyLargeTagNumber()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[19]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestReallyLargeTagNumber() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestReallyLargeTagNumber(TestReallyLargeTagNumber other) : this() { + _hasBits0 = other._hasBits0; + a_ = other.a_; + bb_ = other.bb_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestReallyLargeTagNumber Clone() { + return new TestReallyLargeTagNumber(this); + } + + /// Field number for the "a" field. + public const int AFieldNumber = 1; + private readonly static int ADefaultValue = 0; + + private int a_; + /// + /// The largest possible tag number is 2^28 - 1, since the wire format uses + /// three bits to communicate wire type. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int A { + get { if ((_hasBits0 & 1) != 0) { return a_; } else { return ADefaultValue; } } + set { + _hasBits0 |= 1; + a_ = value; + } + } + /// Gets whether the "a" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasA { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "a" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearA() { + _hasBits0 &= ~1; + } + + /// Field number for the "bb" field. + public const int BbFieldNumber = 268435455; + private readonly static int BbDefaultValue = 0; + + private int bb_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Bb { + get { if ((_hasBits0 & 2) != 0) { return bb_; } else { return BbDefaultValue; } } + set { + _hasBits0 |= 2; + bb_ = value; + } + } + /// Gets whether the "bb" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasBb { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "bb" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearBb() { + _hasBits0 &= ~2; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestReallyLargeTagNumber); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestReallyLargeTagNumber other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (A != other.A) return false; + if (Bb != other.Bb) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasA) hash ^= A.GetHashCode(); + if (HasBb) hash ^= Bb.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasA) { + output.WriteRawTag(8); + output.WriteInt32(A); + } + if (HasBb) { + output.WriteRawTag(248, 255, 255, 255, 7); + output.WriteInt32(Bb); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasA) { + output.WriteRawTag(8); + output.WriteInt32(A); + } + if (HasBb) { + output.WriteRawTag(248, 255, 255, 255, 7); + output.WriteInt32(Bb); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasA) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(A); + } + if (HasBb) { + size += 5 + pb::CodedOutputStream.ComputeInt32Size(Bb); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestReallyLargeTagNumber other) { + if (other == null) { + return; + } + if (other.HasA) { + A = other.A; + } + if (other.HasBb) { + Bb = other.Bb; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + A = input.ReadInt32(); + break; + } + case 2147483640: { + Bb = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + A = input.ReadInt32(); + break; + } + case 2147483640: { + Bb = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + public sealed partial class TestRecursiveMessage : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestRecursiveMessage()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[20]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestRecursiveMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestRecursiveMessage(TestRecursiveMessage other) : this() { + _hasBits0 = other._hasBits0; + a_ = other.a_ != null ? other.a_.Clone() : null; + i_ = other.i_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestRecursiveMessage Clone() { + return new TestRecursiveMessage(this); + } + + /// Field number for the "a" field. + public const int AFieldNumber = 1; + private global::Google.Protobuf.TestProtos.Proto2.TestRecursiveMessage a_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestRecursiveMessage A { + get { return a_; } + set { + a_ = value; + } + } + + /// Field number for the "i" field. + public const int IFieldNumber = 2; + private readonly static int IDefaultValue = 0; + + private int i_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int I { + get { if ((_hasBits0 & 1) != 0) { return i_; } else { return IDefaultValue; } } + set { + _hasBits0 |= 1; + i_ = value; + } + } + /// Gets whether the "i" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasI { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "i" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearI() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestRecursiveMessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestRecursiveMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(A, other.A)) return false; + if (I != other.I) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (a_ != null) hash ^= A.GetHashCode(); + if (HasI) hash ^= I.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (a_ != null) { + output.WriteRawTag(10); + output.WriteMessage(A); + } + if (HasI) { + output.WriteRawTag(16); + output.WriteInt32(I); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (a_ != null) { + output.WriteRawTag(10); + output.WriteMessage(A); + } + if (HasI) { + output.WriteRawTag(16); + output.WriteInt32(I); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (a_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(A); + } + if (HasI) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(I); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestRecursiveMessage other) { + if (other == null) { + return; + } + if (other.a_ != null) { + if (a_ == null) { + A = new global::Google.Protobuf.TestProtos.Proto2.TestRecursiveMessage(); + } + A.MergeFrom(other.A); + } + if (other.HasI) { + I = other.I; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + if (a_ == null) { + A = new global::Google.Protobuf.TestProtos.Proto2.TestRecursiveMessage(); + } + input.ReadMessage(A); + break; + } + case 16: { + I = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + if (a_ == null) { + A = new global::Google.Protobuf.TestProtos.Proto2.TestRecursiveMessage(); + } + input.ReadMessage(A); + break; + } + case 16: { + I = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + /// + /// Test that mutual recursion works. + /// + public sealed partial class TestMutualRecursionA : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestMutualRecursionA()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[21]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestMutualRecursionA() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestMutualRecursionA(TestMutualRecursionA other) : this() { + bb_ = other.bb_ != null ? other.bb_.Clone() : null; + subGroup_ = other.HasSubGroup ? other.subGroup_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestMutualRecursionA Clone() { + return new TestMutualRecursionA(this); + } + + /// Field number for the "bb" field. + public const int BbFieldNumber = 1; + private global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionB bb_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionB Bb { + get { return bb_; } + set { + bb_ = value; + } + } + + /// Field number for the "subgroup" field. + public const int SubGroupFieldNumber = 2; + private global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA.Types.SubGroup subGroup_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA.Types.SubGroup SubGroup { + get { return subGroup_; } + set { + subGroup_ = value; + } + } + /// Gets whether the subgroup field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasSubGroup { + get { return subGroup_ != null; } + } + /// Clears the value of the subgroup field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearSubGroup() { + subGroup_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestMutualRecursionA); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestMutualRecursionA other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(Bb, other.Bb)) return false; + if (!object.Equals(SubGroup, other.SubGroup)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (bb_ != null) hash ^= Bb.GetHashCode(); + if (HasSubGroup) hash ^= SubGroup.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (bb_ != null) { + output.WriteRawTag(10); + output.WriteMessage(Bb); + } + if (HasSubGroup) { + output.WriteRawTag(19); + output.WriteGroup(SubGroup); + output.WriteRawTag(20); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (bb_ != null) { + output.WriteRawTag(10); + output.WriteMessage(Bb); + } + if (HasSubGroup) { + output.WriteRawTag(19); + output.WriteGroup(SubGroup); + output.WriteRawTag(20); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (bb_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Bb); + } + if (HasSubGroup) { + size += 2 + pb::CodedOutputStream.ComputeGroupSize(SubGroup); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestMutualRecursionA other) { + if (other == null) { + return; + } + if (other.bb_ != null) { + if (bb_ == null) { + Bb = new global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionB(); + } + Bb.MergeFrom(other.Bb); + } + if (other.HasSubGroup) { + if (!HasSubGroup) { + SubGroup = new global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA.Types.SubGroup(); + } + SubGroup.MergeFrom(other.SubGroup); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + if (bb_ == null) { + Bb = new global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionB(); + } + input.ReadMessage(Bb); + break; + } + case 19: { + if (!HasSubGroup) { + SubGroup = new global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA.Types.SubGroup(); + } + input.ReadGroup(SubGroup); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + if (bb_ == null) { + Bb = new global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionB(); + } + input.ReadMessage(Bb); + break; + } + case 19: { + if (!HasSubGroup) { + SubGroup = new global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA.Types.SubGroup(); + } + input.ReadGroup(SubGroup); + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the TestMutualRecursionA message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public sealed partial class SubMessage : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new SubMessage()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public SubMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public SubMessage(SubMessage other) : this() { + b_ = other.b_ != null ? other.b_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public SubMessage Clone() { + return new SubMessage(this); + } + + /// Field number for the "b" field. + public const int BFieldNumber = 1; + private global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionB b_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionB B { + get { return b_; } + set { + b_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as SubMessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(SubMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(B, other.B)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (b_ != null) hash ^= B.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (b_ != null) { + output.WriteRawTag(10); + output.WriteMessage(B); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (b_ != null) { + output.WriteRawTag(10); + output.WriteMessage(B); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (b_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(B); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(SubMessage other) { + if (other == null) { + return; + } + if (other.b_ != null) { + if (b_ == null) { + B = new global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionB(); + } + B.MergeFrom(other.B); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + if (b_ == null) { + B = new global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionB(); + } + input.ReadMessage(B); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + if (b_ == null) { + B = new global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionB(); + } + input.ReadMessage(B); + break; + } + } + } + } + #endif + + } + + public sealed partial class SubGroup : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new SubGroup()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA.Descriptor.NestedTypes[1]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public SubGroup() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public SubGroup(SubGroup other) : this() { + subMessage_ = other.subMessage_ != null ? other.subMessage_.Clone() : null; + notInThisScc_ = other.notInThisScc_ != null ? other.notInThisScc_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public SubGroup Clone() { + return new SubGroup(this); + } + + /// Field number for the "sub_message" field. + public const int SubMessageFieldNumber = 3; + private global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA.Types.SubMessage subMessage_; + /// + /// Needed because of bug in javatest + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA.Types.SubMessage SubMessage { + get { return subMessage_; } + set { + subMessage_ = value; + } + } + + /// Field number for the "not_in_this_scc" field. + public const int NotInThisSccFieldNumber = 4; + private global::Google.Protobuf.TestProtos.Proto2.TestAllTypes notInThisScc_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestAllTypes NotInThisScc { + get { return notInThisScc_; } + set { + notInThisScc_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as SubGroup); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(SubGroup other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(SubMessage, other.SubMessage)) return false; + if (!object.Equals(NotInThisScc, other.NotInThisScc)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (subMessage_ != null) hash ^= SubMessage.GetHashCode(); + if (notInThisScc_ != null) hash ^= NotInThisScc.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (subMessage_ != null) { + output.WriteRawTag(26); + output.WriteMessage(SubMessage); + } + if (notInThisScc_ != null) { + output.WriteRawTag(34); + output.WriteMessage(NotInThisScc); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (subMessage_ != null) { + output.WriteRawTag(26); + output.WriteMessage(SubMessage); + } + if (notInThisScc_ != null) { + output.WriteRawTag(34); + output.WriteMessage(NotInThisScc); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (subMessage_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(SubMessage); + } + if (notInThisScc_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(NotInThisScc); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(SubGroup other) { + if (other == null) { + return; + } + if (other.subMessage_ != null) { + if (subMessage_ == null) { + SubMessage = new global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA.Types.SubMessage(); + } + SubMessage.MergeFrom(other.SubMessage); + } + if (other.notInThisScc_ != null) { + if (notInThisScc_ == null) { + NotInThisScc = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + NotInThisScc.MergeFrom(other.NotInThisScc); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 20: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 26: { + if (subMessage_ == null) { + SubMessage = new global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA.Types.SubMessage(); + } + input.ReadMessage(SubMessage); + break; + } + case 34: { + if (notInThisScc_ == null) { + NotInThisScc = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + input.ReadMessage(NotInThisScc); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 20: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 26: { + if (subMessage_ == null) { + SubMessage = new global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA.Types.SubMessage(); + } + input.ReadMessage(SubMessage); + break; + } + case 34: { + if (notInThisScc_ == null) { + NotInThisScc = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + input.ReadMessage(NotInThisScc); + break; + } + } + } + } + #endif + + } + + } + #endregion + + } + + public sealed partial class TestMutualRecursionB : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestMutualRecursionB()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[22]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestMutualRecursionB() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestMutualRecursionB(TestMutualRecursionB other) : this() { + _hasBits0 = other._hasBits0; + a_ = other.a_ != null ? other.a_.Clone() : null; + optionalInt32_ = other.optionalInt32_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestMutualRecursionB Clone() { + return new TestMutualRecursionB(this); + } + + /// Field number for the "a" field. + public const int AFieldNumber = 1; + private global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA a_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA A { + get { return a_; } + set { + a_ = value; + } + } + + /// Field number for the "optional_int32" field. + public const int OptionalInt32FieldNumber = 2; + private readonly static int OptionalInt32DefaultValue = 0; + + private int optionalInt32_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int OptionalInt32 { + get { if ((_hasBits0 & 1) != 0) { return optionalInt32_; } else { return OptionalInt32DefaultValue; } } + set { + _hasBits0 |= 1; + optionalInt32_ = value; + } + } + /// Gets whether the "optional_int32" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalInt32 { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "optional_int32" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalInt32() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestMutualRecursionB); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestMutualRecursionB other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(A, other.A)) return false; + if (OptionalInt32 != other.OptionalInt32) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (a_ != null) hash ^= A.GetHashCode(); + if (HasOptionalInt32) hash ^= OptionalInt32.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (a_ != null) { + output.WriteRawTag(10); + output.WriteMessage(A); + } + if (HasOptionalInt32) { + output.WriteRawTag(16); + output.WriteInt32(OptionalInt32); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (a_ != null) { + output.WriteRawTag(10); + output.WriteMessage(A); + } + if (HasOptionalInt32) { + output.WriteRawTag(16); + output.WriteInt32(OptionalInt32); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (a_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(A); + } + if (HasOptionalInt32) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(OptionalInt32); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestMutualRecursionB other) { + if (other == null) { + return; + } + if (other.a_ != null) { + if (a_ == null) { + A = new global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA(); + } + A.MergeFrom(other.A); + } + if (other.HasOptionalInt32) { + OptionalInt32 = other.OptionalInt32; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + if (a_ == null) { + A = new global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA(); + } + input.ReadMessage(A); + break; + } + case 16: { + OptionalInt32 = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + if (a_ == null) { + A = new global::Google.Protobuf.TestProtos.Proto2.TestMutualRecursionA(); + } + input.ReadMessage(A); + break; + } + case 16: { + OptionalInt32 = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + public sealed partial class TestIsInitialized : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestIsInitialized()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[23]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestIsInitialized() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestIsInitialized(TestIsInitialized other) : this() { + subMessage_ = other.subMessage_ != null ? other.subMessage_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestIsInitialized Clone() { + return new TestIsInitialized(this); + } + + /// Field number for the "sub_message" field. + public const int SubMessageFieldNumber = 1; + private global::Google.Protobuf.TestProtos.Proto2.TestIsInitialized.Types.SubMessage subMessage_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestIsInitialized.Types.SubMessage SubMessage { + get { return subMessage_; } + set { + subMessage_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestIsInitialized); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestIsInitialized other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(SubMessage, other.SubMessage)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (subMessage_ != null) hash ^= SubMessage.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (subMessage_ != null) { + output.WriteRawTag(10); + output.WriteMessage(SubMessage); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (subMessage_ != null) { + output.WriteRawTag(10); + output.WriteMessage(SubMessage); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (subMessage_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(SubMessage); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestIsInitialized other) { + if (other == null) { + return; + } + if (other.subMessage_ != null) { + if (subMessage_ == null) { + SubMessage = new global::Google.Protobuf.TestProtos.Proto2.TestIsInitialized.Types.SubMessage(); + } + SubMessage.MergeFrom(other.SubMessage); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + if (subMessage_ == null) { + SubMessage = new global::Google.Protobuf.TestProtos.Proto2.TestIsInitialized.Types.SubMessage(); + } + input.ReadMessage(SubMessage); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + if (subMessage_ == null) { + SubMessage = new global::Google.Protobuf.TestProtos.Proto2.TestIsInitialized.Types.SubMessage(); + } + input.ReadMessage(SubMessage); + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the TestIsInitialized message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public sealed partial class SubMessage : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new SubMessage()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestIsInitialized.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public SubMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public SubMessage(SubMessage other) : this() { + subGroup_ = other.HasSubGroup ? other.subGroup_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public SubMessage Clone() { + return new SubMessage(this); + } + + /// Field number for the "subgroup" field. + public const int SubGroupFieldNumber = 1; + private global::Google.Protobuf.TestProtos.Proto2.TestIsInitialized.Types.SubMessage.Types.SubGroup subGroup_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestIsInitialized.Types.SubMessage.Types.SubGroup SubGroup { + get { return subGroup_; } + set { + subGroup_ = value; + } + } + /// Gets whether the subgroup field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasSubGroup { + get { return subGroup_ != null; } + } + /// Clears the value of the subgroup field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearSubGroup() { + subGroup_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as SubMessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(SubMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(SubGroup, other.SubGroup)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasSubGroup) hash ^= SubGroup.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasSubGroup) { + output.WriteRawTag(11); + output.WriteGroup(SubGroup); + output.WriteRawTag(12); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasSubGroup) { + output.WriteRawTag(11); + output.WriteGroup(SubGroup); + output.WriteRawTag(12); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasSubGroup) { + size += 2 + pb::CodedOutputStream.ComputeGroupSize(SubGroup); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(SubMessage other) { + if (other == null) { + return; + } + if (other.HasSubGroup) { + if (!HasSubGroup) { + SubGroup = new global::Google.Protobuf.TestProtos.Proto2.TestIsInitialized.Types.SubMessage.Types.SubGroup(); + } + SubGroup.MergeFrom(other.SubGroup); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 11: { + if (!HasSubGroup) { + SubGroup = new global::Google.Protobuf.TestProtos.Proto2.TestIsInitialized.Types.SubMessage.Types.SubGroup(); + } + input.ReadGroup(SubGroup); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 11: { + if (!HasSubGroup) { + SubGroup = new global::Google.Protobuf.TestProtos.Proto2.TestIsInitialized.Types.SubMessage.Types.SubGroup(); + } + input.ReadGroup(SubGroup); + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the SubMessage message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public sealed partial class SubGroup : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new SubGroup()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestIsInitialized.Types.SubMessage.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public SubGroup() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public SubGroup(SubGroup other) : this() { + _hasBits0 = other._hasBits0; + i_ = other.i_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public SubGroup Clone() { + return new SubGroup(this); + } + + /// Field number for the "i" field. + public const int IFieldNumber = 2; + private readonly static int IDefaultValue = 0; + + private int i_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int I { + get { if ((_hasBits0 & 1) != 0) { return i_; } else { return IDefaultValue; } } + set { + _hasBits0 |= 1; + i_ = value; + } + } + /// Gets whether the "i" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasI { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "i" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearI() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as SubGroup); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(SubGroup other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (I != other.I) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasI) hash ^= I.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasI) { + output.WriteRawTag(16); + output.WriteInt32(I); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasI) { + output.WriteRawTag(16); + output.WriteInt32(I); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasI) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(I); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(SubGroup other) { + if (other == null) { + return; + } + if (other.HasI) { + I = other.I; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 12: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 16: { + I = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 12: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 16: { + I = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + } + #endregion + + } + + } + #endregion + + } + + /// + /// Test that groups have disjoint field numbers from their siblings and + /// parents. This is NOT possible in proto1; only google.protobuf. When attempting + /// to compile with proto1, this will emit an error; so we only include it + /// in protobuf_unittest_proto. + /// + public sealed partial class TestDupFieldNumber : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestDupFieldNumber()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[24]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestDupFieldNumber() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestDupFieldNumber(TestDupFieldNumber other) : this() { + _hasBits0 = other._hasBits0; + a_ = other.a_; + foo_ = other.HasFoo ? other.foo_.Clone() : null; + bar_ = other.HasBar ? other.bar_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestDupFieldNumber Clone() { + return new TestDupFieldNumber(this); + } + + /// Field number for the "a" field. + public const int AFieldNumber = 1; + private readonly static int ADefaultValue = 0; + + private int a_; + /// + /// NO_PROTO1 + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int A { + get { if ((_hasBits0 & 1) != 0) { return a_; } else { return ADefaultValue; } } + set { + _hasBits0 |= 1; + a_ = value; + } + } + /// Gets whether the "a" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasA { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "a" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearA() { + _hasBits0 &= ~1; + } + + /// Field number for the "foo" field. + public const int FooFieldNumber = 2; + private global::Google.Protobuf.TestProtos.Proto2.TestDupFieldNumber.Types.Foo foo_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestDupFieldNumber.Types.Foo Foo { + get { return foo_; } + set { + foo_ = value; + } + } + /// Gets whether the foo field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFoo { + get { return foo_ != null; } + } + /// Clears the value of the foo field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFoo() { + foo_ = null; + } + + /// Field number for the "bar" field. + public const int BarFieldNumber = 3; + private global::Google.Protobuf.TestProtos.Proto2.TestDupFieldNumber.Types.Bar bar_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestDupFieldNumber.Types.Bar Bar { + get { return bar_; } + set { + bar_ = value; + } + } + /// Gets whether the bar field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasBar { + get { return bar_ != null; } + } + /// Clears the value of the bar field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearBar() { + bar_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestDupFieldNumber); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestDupFieldNumber other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (A != other.A) return false; + if (!object.Equals(Foo, other.Foo)) return false; + if (!object.Equals(Bar, other.Bar)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasA) hash ^= A.GetHashCode(); + if (HasFoo) hash ^= Foo.GetHashCode(); + if (HasBar) hash ^= Bar.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasA) { + output.WriteRawTag(8); + output.WriteInt32(A); + } + if (HasFoo) { + output.WriteRawTag(19); + output.WriteGroup(Foo); + output.WriteRawTag(20); + } + if (HasBar) { + output.WriteRawTag(27); + output.WriteGroup(Bar); + output.WriteRawTag(28); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasA) { + output.WriteRawTag(8); + output.WriteInt32(A); + } + if (HasFoo) { + output.WriteRawTag(19); + output.WriteGroup(Foo); + output.WriteRawTag(20); + } + if (HasBar) { + output.WriteRawTag(27); + output.WriteGroup(Bar); + output.WriteRawTag(28); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasA) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(A); + } + if (HasFoo) { + size += 2 + pb::CodedOutputStream.ComputeGroupSize(Foo); + } + if (HasBar) { + size += 2 + pb::CodedOutputStream.ComputeGroupSize(Bar); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestDupFieldNumber other) { + if (other == null) { + return; + } + if (other.HasA) { + A = other.A; + } + if (other.HasFoo) { + if (!HasFoo) { + Foo = new global::Google.Protobuf.TestProtos.Proto2.TestDupFieldNumber.Types.Foo(); + } + Foo.MergeFrom(other.Foo); + } + if (other.HasBar) { + if (!HasBar) { + Bar = new global::Google.Protobuf.TestProtos.Proto2.TestDupFieldNumber.Types.Bar(); + } + Bar.MergeFrom(other.Bar); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + A = input.ReadInt32(); + break; + } + case 19: { + if (!HasFoo) { + Foo = new global::Google.Protobuf.TestProtos.Proto2.TestDupFieldNumber.Types.Foo(); + } + input.ReadGroup(Foo); + break; + } + case 27: { + if (!HasBar) { + Bar = new global::Google.Protobuf.TestProtos.Proto2.TestDupFieldNumber.Types.Bar(); + } + input.ReadGroup(Bar); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + A = input.ReadInt32(); + break; + } + case 19: { + if (!HasFoo) { + Foo = new global::Google.Protobuf.TestProtos.Proto2.TestDupFieldNumber.Types.Foo(); + } + input.ReadGroup(Foo); + break; + } + case 27: { + if (!HasBar) { + Bar = new global::Google.Protobuf.TestProtos.Proto2.TestDupFieldNumber.Types.Bar(); + } + input.ReadGroup(Bar); + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the TestDupFieldNumber message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public sealed partial class Foo : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Foo()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestDupFieldNumber.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Foo() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Foo(Foo other) : this() { + _hasBits0 = other._hasBits0; + a_ = other.a_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Foo Clone() { + return new Foo(this); + } + + /// Field number for the "a" field. + public const int AFieldNumber = 1; + private readonly static int ADefaultValue = 0; + + private int a_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int A { + get { if ((_hasBits0 & 1) != 0) { return a_; } else { return ADefaultValue; } } + set { + _hasBits0 |= 1; + a_ = value; + } + } + /// Gets whether the "a" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasA { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "a" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearA() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as Foo); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(Foo other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (A != other.A) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasA) hash ^= A.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasA) { + output.WriteRawTag(8); + output.WriteInt32(A); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasA) { + output.WriteRawTag(8); + output.WriteInt32(A); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasA) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(A); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(Foo other) { + if (other == null) { + return; + } + if (other.HasA) { + A = other.A; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 20: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + A = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 20: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + A = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + public sealed partial class Bar : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Bar()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestDupFieldNumber.Descriptor.NestedTypes[1]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Bar() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Bar(Bar other) : this() { + _hasBits0 = other._hasBits0; + a_ = other.a_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Bar Clone() { + return new Bar(this); + } + + /// Field number for the "a" field. + public const int AFieldNumber = 1; + private readonly static int ADefaultValue = 0; + + private int a_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int A { + get { if ((_hasBits0 & 1) != 0) { return a_; } else { return ADefaultValue; } } + set { + _hasBits0 |= 1; + a_ = value; + } + } + /// Gets whether the "a" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasA { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "a" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearA() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as Bar); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(Bar other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (A != other.A) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasA) hash ^= A.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasA) { + output.WriteRawTag(8); + output.WriteInt32(A); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasA) { + output.WriteRawTag(8); + output.WriteInt32(A); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasA) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(A); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(Bar other) { + if (other == null) { + return; + } + if (other.HasA) { + A = other.A; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 28: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + A = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 28: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + A = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + } + #endregion + + } + + /// + /// Additional messages for testing lazy fields. + /// + public sealed partial class TestEagerMessage : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestEagerMessage()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[25]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestEagerMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestEagerMessage(TestEagerMessage other) : this() { + subMessage_ = other.subMessage_ != null ? other.subMessage_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestEagerMessage Clone() { + return new TestEagerMessage(this); + } + + /// Field number for the "sub_message" field. + public const int SubMessageFieldNumber = 1; + private global::Google.Protobuf.TestProtos.Proto2.TestAllTypes subMessage_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestAllTypes SubMessage { + get { return subMessage_; } + set { + subMessage_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestEagerMessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestEagerMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(SubMessage, other.SubMessage)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (subMessage_ != null) hash ^= SubMessage.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (subMessage_ != null) { + output.WriteRawTag(10); + output.WriteMessage(SubMessage); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (subMessage_ != null) { + output.WriteRawTag(10); + output.WriteMessage(SubMessage); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (subMessage_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(SubMessage); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestEagerMessage other) { + if (other == null) { + return; + } + if (other.subMessage_ != null) { + if (subMessage_ == null) { + SubMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + SubMessage.MergeFrom(other.SubMessage); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + if (subMessage_ == null) { + SubMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + input.ReadMessage(SubMessage); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + if (subMessage_ == null) { + SubMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + input.ReadMessage(SubMessage); + break; + } + } + } + } + #endif + + } + + public sealed partial class TestLazyMessage : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestLazyMessage()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[26]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestLazyMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestLazyMessage(TestLazyMessage other) : this() { + subMessage_ = other.subMessage_ != null ? other.subMessage_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestLazyMessage Clone() { + return new TestLazyMessage(this); + } + + /// Field number for the "sub_message" field. + public const int SubMessageFieldNumber = 1; + private global::Google.Protobuf.TestProtos.Proto2.TestAllTypes subMessage_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestAllTypes SubMessage { + get { return subMessage_; } + set { + subMessage_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestLazyMessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestLazyMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(SubMessage, other.SubMessage)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (subMessage_ != null) hash ^= SubMessage.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (subMessage_ != null) { + output.WriteRawTag(10); + output.WriteMessage(SubMessage); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (subMessage_ != null) { + output.WriteRawTag(10); + output.WriteMessage(SubMessage); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (subMessage_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(SubMessage); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestLazyMessage other) { + if (other == null) { + return; + } + if (other.subMessage_ != null) { + if (subMessage_ == null) { + SubMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + SubMessage.MergeFrom(other.SubMessage); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + if (subMessage_ == null) { + SubMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + input.ReadMessage(SubMessage); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + if (subMessage_ == null) { + SubMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + input.ReadMessage(SubMessage); + break; + } + } + } + } + #endif + + } + + /// + /// Needed for a Python test. + /// + public sealed partial class TestNestedMessageHasBits : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestNestedMessageHasBits()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[27]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestNestedMessageHasBits() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestNestedMessageHasBits(TestNestedMessageHasBits other) : this() { + optionalNestedMessage_ = other.optionalNestedMessage_ != null ? other.optionalNestedMessage_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestNestedMessageHasBits Clone() { + return new TestNestedMessageHasBits(this); + } + + /// Field number for the "optional_nested_message" field. + public const int OptionalNestedMessageFieldNumber = 1; + private global::Google.Protobuf.TestProtos.Proto2.TestNestedMessageHasBits.Types.NestedMessage optionalNestedMessage_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestNestedMessageHasBits.Types.NestedMessage OptionalNestedMessage { + get { return optionalNestedMessage_; } + set { + optionalNestedMessage_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestNestedMessageHasBits); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestNestedMessageHasBits other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(OptionalNestedMessage, other.OptionalNestedMessage)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (optionalNestedMessage_ != null) hash ^= OptionalNestedMessage.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (optionalNestedMessage_ != null) { + output.WriteRawTag(10); + output.WriteMessage(OptionalNestedMessage); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (optionalNestedMessage_ != null) { + output.WriteRawTag(10); + output.WriteMessage(OptionalNestedMessage); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (optionalNestedMessage_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(OptionalNestedMessage); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestNestedMessageHasBits other) { + if (other == null) { + return; + } + if (other.optionalNestedMessage_ != null) { + if (optionalNestedMessage_ == null) { + OptionalNestedMessage = new global::Google.Protobuf.TestProtos.Proto2.TestNestedMessageHasBits.Types.NestedMessage(); + } + OptionalNestedMessage.MergeFrom(other.OptionalNestedMessage); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + if (optionalNestedMessage_ == null) { + OptionalNestedMessage = new global::Google.Protobuf.TestProtos.Proto2.TestNestedMessageHasBits.Types.NestedMessage(); + } + input.ReadMessage(OptionalNestedMessage); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + if (optionalNestedMessage_ == null) { + OptionalNestedMessage = new global::Google.Protobuf.TestProtos.Proto2.TestNestedMessageHasBits.Types.NestedMessage(); + } + input.ReadMessage(OptionalNestedMessage); + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the TestNestedMessageHasBits message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public sealed partial class NestedMessage : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new NestedMessage()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestNestedMessageHasBits.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedMessage(NestedMessage other) : this() { + nestedmessageRepeatedInt32_ = other.nestedmessageRepeatedInt32_.Clone(); + nestedmessageRepeatedForeignmessage_ = other.nestedmessageRepeatedForeignmessage_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedMessage Clone() { + return new NestedMessage(this); + } + + /// Field number for the "nestedmessage_repeated_int32" field. + public const int NestedmessageRepeatedInt32FieldNumber = 1; + private static readonly pb::FieldCodec _repeated_nestedmessageRepeatedInt32_codec + = pb::FieldCodec.ForInt32(8); + private readonly pbc::RepeatedField nestedmessageRepeatedInt32_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField NestedmessageRepeatedInt32 { + get { return nestedmessageRepeatedInt32_; } + } + + /// Field number for the "nestedmessage_repeated_foreignmessage" field. + public const int NestedmessageRepeatedForeignmessageFieldNumber = 2; + private static readonly pb::FieldCodec _repeated_nestedmessageRepeatedForeignmessage_codec + = pb::FieldCodec.ForMessage(18, global::Google.Protobuf.TestProtos.Proto2.ForeignMessage.Parser); + private readonly pbc::RepeatedField nestedmessageRepeatedForeignmessage_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField NestedmessageRepeatedForeignmessage { + get { return nestedmessageRepeatedForeignmessage_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as NestedMessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(NestedMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!nestedmessageRepeatedInt32_.Equals(other.nestedmessageRepeatedInt32_)) return false; + if(!nestedmessageRepeatedForeignmessage_.Equals(other.nestedmessageRepeatedForeignmessage_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + hash ^= nestedmessageRepeatedInt32_.GetHashCode(); + hash ^= nestedmessageRepeatedForeignmessage_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + nestedmessageRepeatedInt32_.WriteTo(output, _repeated_nestedmessageRepeatedInt32_codec); + nestedmessageRepeatedForeignmessage_.WriteTo(output, _repeated_nestedmessageRepeatedForeignmessage_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + nestedmessageRepeatedInt32_.WriteTo(ref output, _repeated_nestedmessageRepeatedInt32_codec); + nestedmessageRepeatedForeignmessage_.WriteTo(ref output, _repeated_nestedmessageRepeatedForeignmessage_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + size += nestedmessageRepeatedInt32_.CalculateSize(_repeated_nestedmessageRepeatedInt32_codec); + size += nestedmessageRepeatedForeignmessage_.CalculateSize(_repeated_nestedmessageRepeatedForeignmessage_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(NestedMessage other) { + if (other == null) { + return; + } + nestedmessageRepeatedInt32_.Add(other.nestedmessageRepeatedInt32_); + nestedmessageRepeatedForeignmessage_.Add(other.nestedmessageRepeatedForeignmessage_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: + case 8: { + nestedmessageRepeatedInt32_.AddEntriesFrom(input, _repeated_nestedmessageRepeatedInt32_codec); + break; + } + case 18: { + nestedmessageRepeatedForeignmessage_.AddEntriesFrom(input, _repeated_nestedmessageRepeatedForeignmessage_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: + case 8: { + nestedmessageRepeatedInt32_.AddEntriesFrom(ref input, _repeated_nestedmessageRepeatedInt32_codec); + break; + } + case 18: { + nestedmessageRepeatedForeignmessage_.AddEntriesFrom(ref input, _repeated_nestedmessageRepeatedForeignmessage_codec); + break; + } + } + } + } + #endif + + } + + } + #endregion + + } + + /// + /// Test message with CamelCase field names. This violates Protocol Buffer + /// standard style. + /// + public sealed partial class TestCamelCaseFieldNames : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestCamelCaseFieldNames()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[28]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestCamelCaseFieldNames() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestCamelCaseFieldNames(TestCamelCaseFieldNames other) : this() { + _hasBits0 = other._hasBits0; + primitiveField_ = other.primitiveField_; + stringField_ = other.stringField_; + enumField_ = other.enumField_; + messageField_ = other.messageField_ != null ? other.messageField_.Clone() : null; + stringPieceField_ = other.stringPieceField_; + cordField_ = other.cordField_; + repeatedPrimitiveField_ = other.repeatedPrimitiveField_.Clone(); + repeatedStringField_ = other.repeatedStringField_.Clone(); + repeatedEnumField_ = other.repeatedEnumField_.Clone(); + repeatedMessageField_ = other.repeatedMessageField_.Clone(); + repeatedStringPieceField_ = other.repeatedStringPieceField_.Clone(); + repeatedCordField_ = other.repeatedCordField_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestCamelCaseFieldNames Clone() { + return new TestCamelCaseFieldNames(this); + } + + /// Field number for the "PrimitiveField" field. + public const int PrimitiveFieldFieldNumber = 1; + private readonly static int PrimitiveFieldDefaultValue = 0; + + private int primitiveField_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int PrimitiveField { + get { if ((_hasBits0 & 1) != 0) { return primitiveField_; } else { return PrimitiveFieldDefaultValue; } } + set { + _hasBits0 |= 1; + primitiveField_ = value; + } + } + /// Gets whether the "PrimitiveField" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasPrimitiveField { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "PrimitiveField" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearPrimitiveField() { + _hasBits0 &= ~1; + } + + /// Field number for the "StringField" field. + public const int StringFieldFieldNumber = 2; + private readonly static string StringFieldDefaultValue = ""; + + private string stringField_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string StringField { + get { return stringField_ ?? StringFieldDefaultValue; } + set { + stringField_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "StringField" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasStringField { + get { return stringField_ != null; } + } + /// Clears the value of the "StringField" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearStringField() { + stringField_ = null; + } + + /// Field number for the "EnumField" field. + public const int EnumFieldFieldNumber = 3; + private readonly static global::Google.Protobuf.TestProtos.Proto2.ForeignEnum EnumFieldDefaultValue = global::Google.Protobuf.TestProtos.Proto2.ForeignEnum.ForeignFoo; + + private global::Google.Protobuf.TestProtos.Proto2.ForeignEnum enumField_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.ForeignEnum EnumField { + get { if ((_hasBits0 & 2) != 0) { return enumField_; } else { return EnumFieldDefaultValue; } } + set { + _hasBits0 |= 2; + enumField_ = value; + } + } + /// Gets whether the "EnumField" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasEnumField { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "EnumField" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearEnumField() { + _hasBits0 &= ~2; + } + + /// Field number for the "MessageField" field. + public const int MessageFieldFieldNumber = 4; + private global::Google.Protobuf.TestProtos.Proto2.ForeignMessage messageField_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.ForeignMessage MessageField { + get { return messageField_; } + set { + messageField_ = value; + } + } + + /// Field number for the "StringPieceField" field. + public const int StringPieceFieldFieldNumber = 5; + private readonly static string StringPieceFieldDefaultValue = ""; + + private string stringPieceField_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string StringPieceField { + get { return stringPieceField_ ?? StringPieceFieldDefaultValue; } + set { + stringPieceField_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "StringPieceField" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasStringPieceField { + get { return stringPieceField_ != null; } + } + /// Clears the value of the "StringPieceField" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearStringPieceField() { + stringPieceField_ = null; + } + + /// Field number for the "CordField" field. + public const int CordFieldFieldNumber = 6; + private readonly static string CordFieldDefaultValue = ""; + + private string cordField_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string CordField { + get { return cordField_ ?? CordFieldDefaultValue; } + set { + cordField_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "CordField" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasCordField { + get { return cordField_ != null; } + } + /// Clears the value of the "CordField" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearCordField() { + cordField_ = null; + } + + /// Field number for the "RepeatedPrimitiveField" field. + public const int RepeatedPrimitiveFieldFieldNumber = 7; + private static readonly pb::FieldCodec _repeated_repeatedPrimitiveField_codec + = pb::FieldCodec.ForInt32(56); + private readonly pbc::RepeatedField repeatedPrimitiveField_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedPrimitiveField { + get { return repeatedPrimitiveField_; } + } + + /// Field number for the "RepeatedStringField" field. + public const int RepeatedStringFieldFieldNumber = 8; + private static readonly pb::FieldCodec _repeated_repeatedStringField_codec + = pb::FieldCodec.ForString(66); + private readonly pbc::RepeatedField repeatedStringField_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedStringField { + get { return repeatedStringField_; } + } + + /// Field number for the "RepeatedEnumField" field. + public const int RepeatedEnumFieldFieldNumber = 9; + private static readonly pb::FieldCodec _repeated_repeatedEnumField_codec + = pb::FieldCodec.ForEnum(72, x => (int) x, x => (global::Google.Protobuf.TestProtos.Proto2.ForeignEnum) x); + private readonly pbc::RepeatedField repeatedEnumField_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedEnumField { + get { return repeatedEnumField_; } + } + + /// Field number for the "RepeatedMessageField" field. + public const int RepeatedMessageFieldFieldNumber = 10; + private static readonly pb::FieldCodec _repeated_repeatedMessageField_codec + = pb::FieldCodec.ForMessage(82, global::Google.Protobuf.TestProtos.Proto2.ForeignMessage.Parser); + private readonly pbc::RepeatedField repeatedMessageField_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedMessageField { + get { return repeatedMessageField_; } + } + + /// Field number for the "RepeatedStringPieceField" field. + public const int RepeatedStringPieceFieldFieldNumber = 11; + private static readonly pb::FieldCodec _repeated_repeatedStringPieceField_codec + = pb::FieldCodec.ForString(90); + private readonly pbc::RepeatedField repeatedStringPieceField_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedStringPieceField { + get { return repeatedStringPieceField_; } + } + + /// Field number for the "RepeatedCordField" field. + public const int RepeatedCordFieldFieldNumber = 12; + private static readonly pb::FieldCodec _repeated_repeatedCordField_codec + = pb::FieldCodec.ForString(98); + private readonly pbc::RepeatedField repeatedCordField_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedCordField { + get { return repeatedCordField_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestCamelCaseFieldNames); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestCamelCaseFieldNames other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (PrimitiveField != other.PrimitiveField) return false; + if (StringField != other.StringField) return false; + if (EnumField != other.EnumField) return false; + if (!object.Equals(MessageField, other.MessageField)) return false; + if (StringPieceField != other.StringPieceField) return false; + if (CordField != other.CordField) return false; + if(!repeatedPrimitiveField_.Equals(other.repeatedPrimitiveField_)) return false; + if(!repeatedStringField_.Equals(other.repeatedStringField_)) return false; + if(!repeatedEnumField_.Equals(other.repeatedEnumField_)) return false; + if(!repeatedMessageField_.Equals(other.repeatedMessageField_)) return false; + if(!repeatedStringPieceField_.Equals(other.repeatedStringPieceField_)) return false; + if(!repeatedCordField_.Equals(other.repeatedCordField_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasPrimitiveField) hash ^= PrimitiveField.GetHashCode(); + if (HasStringField) hash ^= StringField.GetHashCode(); + if (HasEnumField) hash ^= EnumField.GetHashCode(); + if (messageField_ != null) hash ^= MessageField.GetHashCode(); + if (HasStringPieceField) hash ^= StringPieceField.GetHashCode(); + if (HasCordField) hash ^= CordField.GetHashCode(); + hash ^= repeatedPrimitiveField_.GetHashCode(); + hash ^= repeatedStringField_.GetHashCode(); + hash ^= repeatedEnumField_.GetHashCode(); + hash ^= repeatedMessageField_.GetHashCode(); + hash ^= repeatedStringPieceField_.GetHashCode(); + hash ^= repeatedCordField_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasPrimitiveField) { + output.WriteRawTag(8); + output.WriteInt32(PrimitiveField); + } + if (HasStringField) { + output.WriteRawTag(18); + output.WriteString(StringField); + } + if (HasEnumField) { + output.WriteRawTag(24); + output.WriteEnum((int) EnumField); + } + if (messageField_ != null) { + output.WriteRawTag(34); + output.WriteMessage(MessageField); + } + if (HasStringPieceField) { + output.WriteRawTag(42); + output.WriteString(StringPieceField); + } + if (HasCordField) { + output.WriteRawTag(50); + output.WriteString(CordField); + } + repeatedPrimitiveField_.WriteTo(output, _repeated_repeatedPrimitiveField_codec); + repeatedStringField_.WriteTo(output, _repeated_repeatedStringField_codec); + repeatedEnumField_.WriteTo(output, _repeated_repeatedEnumField_codec); + repeatedMessageField_.WriteTo(output, _repeated_repeatedMessageField_codec); + repeatedStringPieceField_.WriteTo(output, _repeated_repeatedStringPieceField_codec); + repeatedCordField_.WriteTo(output, _repeated_repeatedCordField_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasPrimitiveField) { + output.WriteRawTag(8); + output.WriteInt32(PrimitiveField); + } + if (HasStringField) { + output.WriteRawTag(18); + output.WriteString(StringField); + } + if (HasEnumField) { + output.WriteRawTag(24); + output.WriteEnum((int) EnumField); + } + if (messageField_ != null) { + output.WriteRawTag(34); + output.WriteMessage(MessageField); + } + if (HasStringPieceField) { + output.WriteRawTag(42); + output.WriteString(StringPieceField); + } + if (HasCordField) { + output.WriteRawTag(50); + output.WriteString(CordField); + } + repeatedPrimitiveField_.WriteTo(ref output, _repeated_repeatedPrimitiveField_codec); + repeatedStringField_.WriteTo(ref output, _repeated_repeatedStringField_codec); + repeatedEnumField_.WriteTo(ref output, _repeated_repeatedEnumField_codec); + repeatedMessageField_.WriteTo(ref output, _repeated_repeatedMessageField_codec); + repeatedStringPieceField_.WriteTo(ref output, _repeated_repeatedStringPieceField_codec); + repeatedCordField_.WriteTo(ref output, _repeated_repeatedCordField_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasPrimitiveField) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(PrimitiveField); + } + if (HasStringField) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(StringField); + } + if (HasEnumField) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) EnumField); + } + if (messageField_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(MessageField); + } + if (HasStringPieceField) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(StringPieceField); + } + if (HasCordField) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(CordField); + } + size += repeatedPrimitiveField_.CalculateSize(_repeated_repeatedPrimitiveField_codec); + size += repeatedStringField_.CalculateSize(_repeated_repeatedStringField_codec); + size += repeatedEnumField_.CalculateSize(_repeated_repeatedEnumField_codec); + size += repeatedMessageField_.CalculateSize(_repeated_repeatedMessageField_codec); + size += repeatedStringPieceField_.CalculateSize(_repeated_repeatedStringPieceField_codec); + size += repeatedCordField_.CalculateSize(_repeated_repeatedCordField_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestCamelCaseFieldNames other) { + if (other == null) { + return; + } + if (other.HasPrimitiveField) { + PrimitiveField = other.PrimitiveField; + } + if (other.HasStringField) { + StringField = other.StringField; + } + if (other.HasEnumField) { + EnumField = other.EnumField; + } + if (other.messageField_ != null) { + if (messageField_ == null) { + MessageField = new global::Google.Protobuf.TestProtos.Proto2.ForeignMessage(); + } + MessageField.MergeFrom(other.MessageField); + } + if (other.HasStringPieceField) { + StringPieceField = other.StringPieceField; + } + if (other.HasCordField) { + CordField = other.CordField; + } + repeatedPrimitiveField_.Add(other.repeatedPrimitiveField_); + repeatedStringField_.Add(other.repeatedStringField_); + repeatedEnumField_.Add(other.repeatedEnumField_); + repeatedMessageField_.Add(other.repeatedMessageField_); + repeatedStringPieceField_.Add(other.repeatedStringPieceField_); + repeatedCordField_.Add(other.repeatedCordField_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + PrimitiveField = input.ReadInt32(); + break; + } + case 18: { + StringField = input.ReadString(); + break; + } + case 24: { + EnumField = (global::Google.Protobuf.TestProtos.Proto2.ForeignEnum) input.ReadEnum(); + break; + } + case 34: { + if (messageField_ == null) { + MessageField = new global::Google.Protobuf.TestProtos.Proto2.ForeignMessage(); + } + input.ReadMessage(MessageField); + break; + } + case 42: { + StringPieceField = input.ReadString(); + break; + } + case 50: { + CordField = input.ReadString(); + break; + } + case 58: + case 56: { + repeatedPrimitiveField_.AddEntriesFrom(input, _repeated_repeatedPrimitiveField_codec); + break; + } + case 66: { + repeatedStringField_.AddEntriesFrom(input, _repeated_repeatedStringField_codec); + break; + } + case 74: + case 72: { + repeatedEnumField_.AddEntriesFrom(input, _repeated_repeatedEnumField_codec); + break; + } + case 82: { + repeatedMessageField_.AddEntriesFrom(input, _repeated_repeatedMessageField_codec); + break; + } + case 90: { + repeatedStringPieceField_.AddEntriesFrom(input, _repeated_repeatedStringPieceField_codec); + break; + } + case 98: { + repeatedCordField_.AddEntriesFrom(input, _repeated_repeatedCordField_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + PrimitiveField = input.ReadInt32(); + break; + } + case 18: { + StringField = input.ReadString(); + break; + } + case 24: { + EnumField = (global::Google.Protobuf.TestProtos.Proto2.ForeignEnum) input.ReadEnum(); + break; + } + case 34: { + if (messageField_ == null) { + MessageField = new global::Google.Protobuf.TestProtos.Proto2.ForeignMessage(); + } + input.ReadMessage(MessageField); + break; + } + case 42: { + StringPieceField = input.ReadString(); + break; + } + case 50: { + CordField = input.ReadString(); + break; + } + case 58: + case 56: { + repeatedPrimitiveField_.AddEntriesFrom(ref input, _repeated_repeatedPrimitiveField_codec); + break; + } + case 66: { + repeatedStringField_.AddEntriesFrom(ref input, _repeated_repeatedStringField_codec); + break; + } + case 74: + case 72: { + repeatedEnumField_.AddEntriesFrom(ref input, _repeated_repeatedEnumField_codec); + break; + } + case 82: { + repeatedMessageField_.AddEntriesFrom(ref input, _repeated_repeatedMessageField_codec); + break; + } + case 90: { + repeatedStringPieceField_.AddEntriesFrom(ref input, _repeated_repeatedStringPieceField_codec); + break; + } + case 98: { + repeatedCordField_.AddEntriesFrom(ref input, _repeated_repeatedCordField_codec); + break; + } + } + } + } + #endif + + } + + /// + /// We list fields out of order, to ensure that we're using field number and not + /// field index to determine serialization order. + /// + public sealed partial class TestFieldOrderings : pb::IExtendableMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestFieldOrderings()); + private pb::UnknownFieldSet _unknownFields; + private pb::ExtensionSet _extensions; + private pb::ExtensionSet _Extensions { get { return _extensions; } } + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[29]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestFieldOrderings() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestFieldOrderings(TestFieldOrderings other) : this() { + _hasBits0 = other._hasBits0; + myString_ = other.myString_; + myInt_ = other.myInt_; + myFloat_ = other.myFloat_; + optionalNestedMessage_ = other.optionalNestedMessage_ != null ? other.optionalNestedMessage_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + _extensions = pb::ExtensionSet.Clone(other._extensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestFieldOrderings Clone() { + return new TestFieldOrderings(this); + } + + /// Field number for the "my_string" field. + public const int MyStringFieldNumber = 11; + private readonly static string MyStringDefaultValue = ""; + + private string myString_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string MyString { + get { return myString_ ?? MyStringDefaultValue; } + set { + myString_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "my_string" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasMyString { + get { return myString_ != null; } + } + /// Clears the value of the "my_string" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearMyString() { + myString_ = null; + } + + /// Field number for the "my_int" field. + public const int MyIntFieldNumber = 1; + private readonly static long MyIntDefaultValue = 0L; + + private long myInt_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public long MyInt { + get { if ((_hasBits0 & 1) != 0) { return myInt_; } else { return MyIntDefaultValue; } } + set { + _hasBits0 |= 1; + myInt_ = value; + } + } + /// Gets whether the "my_int" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasMyInt { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "my_int" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearMyInt() { + _hasBits0 &= ~1; + } + + /// Field number for the "my_float" field. + public const int MyFloatFieldNumber = 101; + private readonly static float MyFloatDefaultValue = 0F; + + private float myFloat_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public float MyFloat { + get { if ((_hasBits0 & 2) != 0) { return myFloat_; } else { return MyFloatDefaultValue; } } + set { + _hasBits0 |= 2; + myFloat_ = value; + } + } + /// Gets whether the "my_float" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasMyFloat { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "my_float" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearMyFloat() { + _hasBits0 &= ~2; + } + + /// Field number for the "optional_nested_message" field. + public const int OptionalNestedMessageFieldNumber = 200; + private global::Google.Protobuf.TestProtos.Proto2.TestFieldOrderings.Types.NestedMessage optionalNestedMessage_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestFieldOrderings.Types.NestedMessage OptionalNestedMessage { + get { return optionalNestedMessage_; } + set { + optionalNestedMessage_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestFieldOrderings); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestFieldOrderings other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (MyString != other.MyString) return false; + if (MyInt != other.MyInt) return false; + if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(MyFloat, other.MyFloat)) return false; + if (!object.Equals(OptionalNestedMessage, other.OptionalNestedMessage)) return false; + if (!Equals(_extensions, other._extensions)) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasMyString) hash ^= MyString.GetHashCode(); + if (HasMyInt) hash ^= MyInt.GetHashCode(); + if (HasMyFloat) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(MyFloat); + if (optionalNestedMessage_ != null) hash ^= OptionalNestedMessage.GetHashCode(); + if (_extensions != null) { + hash ^= _extensions.GetHashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasMyInt) { + output.WriteRawTag(8); + output.WriteInt64(MyInt); + } + if (HasMyString) { + output.WriteRawTag(90); + output.WriteString(MyString); + } + if (HasMyFloat) { + output.WriteRawTag(173, 6); + output.WriteFloat(MyFloat); + } + if (optionalNestedMessage_ != null) { + output.WriteRawTag(194, 12); + output.WriteMessage(OptionalNestedMessage); + } + if (_extensions != null) { + _extensions.WriteTo(output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasMyInt) { + output.WriteRawTag(8); + output.WriteInt64(MyInt); + } + if (HasMyString) { + output.WriteRawTag(90); + output.WriteString(MyString); + } + if (HasMyFloat) { + output.WriteRawTag(173, 6); + output.WriteFloat(MyFloat); + } + if (optionalNestedMessage_ != null) { + output.WriteRawTag(194, 12); + output.WriteMessage(OptionalNestedMessage); + } + if (_extensions != null) { + _extensions.WriteTo(ref output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasMyString) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(MyString); + } + if (HasMyInt) { + size += 1 + pb::CodedOutputStream.ComputeInt64Size(MyInt); + } + if (HasMyFloat) { + size += 2 + 4; + } + if (optionalNestedMessage_ != null) { + size += 2 + pb::CodedOutputStream.ComputeMessageSize(OptionalNestedMessage); + } + if (_extensions != null) { + size += _extensions.CalculateSize(); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestFieldOrderings other) { + if (other == null) { + return; + } + if (other.HasMyString) { + MyString = other.MyString; + } + if (other.HasMyInt) { + MyInt = other.MyInt; + } + if (other.HasMyFloat) { + MyFloat = other.MyFloat; + } + if (other.optionalNestedMessage_ != null) { + if (optionalNestedMessage_ == null) { + OptionalNestedMessage = new global::Google.Protobuf.TestProtos.Proto2.TestFieldOrderings.Types.NestedMessage(); + } + OptionalNestedMessage.MergeFrom(other.OptionalNestedMessage); + } + pb::ExtensionSet.MergeFrom(ref _extensions, other._extensions); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + } + break; + case 8: { + MyInt = input.ReadInt64(); + break; + } + case 90: { + MyString = input.ReadString(); + break; + } + case 813: { + MyFloat = input.ReadFloat(); + break; + } + case 1602: { + if (optionalNestedMessage_ == null) { + OptionalNestedMessage = new global::Google.Protobuf.TestProtos.Proto2.TestFieldOrderings.Types.NestedMessage(); + } + input.ReadMessage(OptionalNestedMessage); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + } + break; + case 8: { + MyInt = input.ReadInt64(); + break; + } + case 90: { + MyString = input.ReadString(); + break; + } + case 813: { + MyFloat = input.ReadFloat(); + break; + } + case 1602: { + if (optionalNestedMessage_ == null) { + OptionalNestedMessage = new global::Google.Protobuf.TestProtos.Proto2.TestFieldOrderings.Types.NestedMessage(); + } + input.ReadMessage(OptionalNestedMessage); + break; + } + } + } + } + #endif + + public TValue GetExtension(pb::Extension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetOrInitializeExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.GetOrInitialize(ref _extensions, extension); + } + public void SetExtension(pb::Extension extension, TValue value) { + pb::ExtensionSet.Set(ref _extensions, extension, value); + } + public bool HasExtension(pb::Extension extension) { + return pb::ExtensionSet.Has(ref _extensions, extension); + } + public void ClearExtension(pb::Extension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + public void ClearExtension(pb::RepeatedExtension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + + #region Nested types + /// Container for nested types declared in the TestFieldOrderings message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public sealed partial class NestedMessage : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new NestedMessage()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestFieldOrderings.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedMessage(NestedMessage other) : this() { + _hasBits0 = other._hasBits0; + oo_ = other.oo_; + bb_ = other.bb_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedMessage Clone() { + return new NestedMessage(this); + } + + /// Field number for the "oo" field. + public const int OoFieldNumber = 2; + private readonly static long OoDefaultValue = 0L; + + private long oo_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public long Oo { + get { if ((_hasBits0 & 2) != 0) { return oo_; } else { return OoDefaultValue; } } + set { + _hasBits0 |= 2; + oo_ = value; + } + } + /// Gets whether the "oo" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOo { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "oo" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOo() { + _hasBits0 &= ~2; + } + + /// Field number for the "bb" field. + public const int BbFieldNumber = 1; + private readonly static int BbDefaultValue = 0; + + private int bb_; + /// + /// The field name "b" fails to compile in proto1 because it conflicts with + /// a local variable named "b" in one of the generated methods. Doh. + /// This file needs to compile in proto1 to test backwards-compatibility. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Bb { + get { if ((_hasBits0 & 1) != 0) { return bb_; } else { return BbDefaultValue; } } + set { + _hasBits0 |= 1; + bb_ = value; + } + } + /// Gets whether the "bb" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasBb { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "bb" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearBb() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as NestedMessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(NestedMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Oo != other.Oo) return false; + if (Bb != other.Bb) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasOo) hash ^= Oo.GetHashCode(); + if (HasBb) hash ^= Bb.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasBb) { + output.WriteRawTag(8); + output.WriteInt32(Bb); + } + if (HasOo) { + output.WriteRawTag(16); + output.WriteInt64(Oo); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasBb) { + output.WriteRawTag(8); + output.WriteInt32(Bb); + } + if (HasOo) { + output.WriteRawTag(16); + output.WriteInt64(Oo); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasOo) { + size += 1 + pb::CodedOutputStream.ComputeInt64Size(Oo); + } + if (HasBb) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Bb); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(NestedMessage other) { + if (other == null) { + return; + } + if (other.HasOo) { + Oo = other.Oo; + } + if (other.HasBb) { + Bb = other.Bb; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Bb = input.ReadInt32(); + break; + } + case 16: { + Oo = input.ReadInt64(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Bb = input.ReadInt32(); + break; + } + case 16: { + Oo = input.ReadInt64(); + break; + } + } + } + } + #endif + + } + + } + #endregion + + } + + public sealed partial class TestExtensionOrderings1 : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestExtensionOrderings1()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[30]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestExtensionOrderings1() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestExtensionOrderings1(TestExtensionOrderings1 other) : this() { + myString_ = other.myString_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestExtensionOrderings1 Clone() { + return new TestExtensionOrderings1(this); + } + + /// Field number for the "my_string" field. + public const int MyStringFieldNumber = 1; + private readonly static string MyStringDefaultValue = ""; + + private string myString_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string MyString { + get { return myString_ ?? MyStringDefaultValue; } + set { + myString_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "my_string" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasMyString { + get { return myString_ != null; } + } + /// Clears the value of the "my_string" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearMyString() { + myString_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestExtensionOrderings1); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestExtensionOrderings1 other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (MyString != other.MyString) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasMyString) hash ^= MyString.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasMyString) { + output.WriteRawTag(10); + output.WriteString(MyString); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasMyString) { + output.WriteRawTag(10); + output.WriteString(MyString); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasMyString) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(MyString); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestExtensionOrderings1 other) { + if (other == null) { + return; + } + if (other.HasMyString) { + MyString = other.MyString; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + MyString = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + MyString = input.ReadString(); + break; + } + } + } + } + #endif + + #region Extensions + /// Container for extensions for other messages declared in the TestExtensionOrderings1 message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Extensions { + public static readonly pb::Extension TestExtOrderings1 = + new pb::Extension(13, pb::FieldCodec.ForMessage(106, global::Google.Protobuf.TestProtos.Proto2.TestExtensionOrderings1.Parser)); + } + #endregion + + } + + public sealed partial class TestExtensionOrderings2 : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestExtensionOrderings2()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[31]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestExtensionOrderings2() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestExtensionOrderings2(TestExtensionOrderings2 other) : this() { + myString_ = other.myString_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestExtensionOrderings2 Clone() { + return new TestExtensionOrderings2(this); + } + + /// Field number for the "my_string" field. + public const int MyStringFieldNumber = 1; + private readonly static string MyStringDefaultValue = ""; + + private string myString_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string MyString { + get { return myString_ ?? MyStringDefaultValue; } + set { + myString_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "my_string" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasMyString { + get { return myString_ != null; } + } + /// Clears the value of the "my_string" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearMyString() { + myString_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestExtensionOrderings2); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestExtensionOrderings2 other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (MyString != other.MyString) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasMyString) hash ^= MyString.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasMyString) { + output.WriteRawTag(10); + output.WriteString(MyString); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasMyString) { + output.WriteRawTag(10); + output.WriteString(MyString); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasMyString) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(MyString); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestExtensionOrderings2 other) { + if (other == null) { + return; + } + if (other.HasMyString) { + MyString = other.MyString; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + MyString = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + MyString = input.ReadString(); + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the TestExtensionOrderings2 message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public sealed partial class TestExtensionOrderings3 : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestExtensionOrderings3()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestExtensionOrderings2.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestExtensionOrderings3() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestExtensionOrderings3(TestExtensionOrderings3 other) : this() { + myString_ = other.myString_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestExtensionOrderings3 Clone() { + return new TestExtensionOrderings3(this); + } + + /// Field number for the "my_string" field. + public const int MyStringFieldNumber = 1; + private readonly static string MyStringDefaultValue = ""; + + private string myString_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string MyString { + get { return myString_ ?? MyStringDefaultValue; } + set { + myString_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "my_string" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasMyString { + get { return myString_ != null; } + } + /// Clears the value of the "my_string" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearMyString() { + myString_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestExtensionOrderings3); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestExtensionOrderings3 other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (MyString != other.MyString) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasMyString) hash ^= MyString.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasMyString) { + output.WriteRawTag(10); + output.WriteString(MyString); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasMyString) { + output.WriteRawTag(10); + output.WriteString(MyString); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasMyString) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(MyString); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestExtensionOrderings3 other) { + if (other == null) { + return; + } + if (other.HasMyString) { + MyString = other.MyString; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + MyString = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + MyString = input.ReadString(); + break; + } + } + } + } + #endif + + #region Extensions + /// Container for extensions for other messages declared in the TestExtensionOrderings3 message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Extensions { + public static readonly pb::Extension TestExtOrderings3 = + new pb::Extension(14, pb::FieldCodec.ForMessage(114, global::Google.Protobuf.TestProtos.Proto2.TestExtensionOrderings2.Types.TestExtensionOrderings3.Parser)); + } + #endregion + + } + + } + #endregion + + #region Extensions + /// Container for extensions for other messages declared in the TestExtensionOrderings2 message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Extensions { + public static readonly pb::Extension TestExtOrderings2 = + new pb::Extension(12, pb::FieldCodec.ForMessage(98, global::Google.Protobuf.TestProtos.Proto2.TestExtensionOrderings2.Parser)); + } + #endregion + + } + + public sealed partial class TestExtremeDefaultValues : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestExtremeDefaultValues()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[32]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestExtremeDefaultValues() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestExtremeDefaultValues(TestExtremeDefaultValues other) : this() { + _hasBits0 = other._hasBits0; + escapedBytes_ = other.escapedBytes_; + largeUint32_ = other.largeUint32_; + largeUint64_ = other.largeUint64_; + smallInt32_ = other.smallInt32_; + smallInt64_ = other.smallInt64_; + reallySmallInt32_ = other.reallySmallInt32_; + reallySmallInt64_ = other.reallySmallInt64_; + utf8String_ = other.utf8String_; + zeroFloat_ = other.zeroFloat_; + oneFloat_ = other.oneFloat_; + smallFloat_ = other.smallFloat_; + negativeOneFloat_ = other.negativeOneFloat_; + negativeFloat_ = other.negativeFloat_; + largeFloat_ = other.largeFloat_; + smallNegativeFloat_ = other.smallNegativeFloat_; + infDouble_ = other.infDouble_; + negInfDouble_ = other.negInfDouble_; + nanDouble_ = other.nanDouble_; + infFloat_ = other.infFloat_; + negInfFloat_ = other.negInfFloat_; + nanFloat_ = other.nanFloat_; + cppTrigraph_ = other.cppTrigraph_; + stringWithZero_ = other.stringWithZero_; + bytesWithZero_ = other.bytesWithZero_; + stringPieceWithZero_ = other.stringPieceWithZero_; + cordWithZero_ = other.cordWithZero_; + replacementString_ = other.replacementString_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestExtremeDefaultValues Clone() { + return new TestExtremeDefaultValues(this); + } + + /// Field number for the "escaped_bytes" field. + public const int EscapedBytesFieldNumber = 1; + private readonly static pb::ByteString EscapedBytesDefaultValue = pb::ByteString.FromBase64("AAEHCAwKDQkLXCci/g=="); + + private pb::ByteString escapedBytes_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pb::ByteString EscapedBytes { + get { return escapedBytes_ ?? EscapedBytesDefaultValue; } + set { + escapedBytes_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "escaped_bytes" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasEscapedBytes { + get { return escapedBytes_ != null; } + } + /// Clears the value of the "escaped_bytes" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearEscapedBytes() { + escapedBytes_ = null; + } + + /// Field number for the "large_uint32" field. + public const int LargeUint32FieldNumber = 2; + private readonly static uint LargeUint32DefaultValue = 4294967295; + + private uint largeUint32_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public uint LargeUint32 { + get { if ((_hasBits0 & 1) != 0) { return largeUint32_; } else { return LargeUint32DefaultValue; } } + set { + _hasBits0 |= 1; + largeUint32_ = value; + } + } + /// Gets whether the "large_uint32" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasLargeUint32 { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "large_uint32" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearLargeUint32() { + _hasBits0 &= ~1; + } + + /// Field number for the "large_uint64" field. + public const int LargeUint64FieldNumber = 3; + private readonly static ulong LargeUint64DefaultValue = 18446744073709551615UL; + + private ulong largeUint64_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ulong LargeUint64 { + get { if ((_hasBits0 & 2) != 0) { return largeUint64_; } else { return LargeUint64DefaultValue; } } + set { + _hasBits0 |= 2; + largeUint64_ = value; + } + } + /// Gets whether the "large_uint64" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasLargeUint64 { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "large_uint64" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearLargeUint64() { + _hasBits0 &= ~2; + } + + /// Field number for the "small_int32" field. + public const int SmallInt32FieldNumber = 4; + private readonly static int SmallInt32DefaultValue = -2147483647; + + private int smallInt32_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int SmallInt32 { + get { if ((_hasBits0 & 4) != 0) { return smallInt32_; } else { return SmallInt32DefaultValue; } } + set { + _hasBits0 |= 4; + smallInt32_ = value; + } + } + /// Gets whether the "small_int32" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasSmallInt32 { + get { return (_hasBits0 & 4) != 0; } + } + /// Clears the value of the "small_int32" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearSmallInt32() { + _hasBits0 &= ~4; + } + + /// Field number for the "small_int64" field. + public const int SmallInt64FieldNumber = 5; + private readonly static long SmallInt64DefaultValue = -9223372036854775807L; + + private long smallInt64_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public long SmallInt64 { + get { if ((_hasBits0 & 8) != 0) { return smallInt64_; } else { return SmallInt64DefaultValue; } } + set { + _hasBits0 |= 8; + smallInt64_ = value; + } + } + /// Gets whether the "small_int64" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasSmallInt64 { + get { return (_hasBits0 & 8) != 0; } + } + /// Clears the value of the "small_int64" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearSmallInt64() { + _hasBits0 &= ~8; + } + + /// Field number for the "really_small_int32" field. + public const int ReallySmallInt32FieldNumber = 21; + private readonly static int ReallySmallInt32DefaultValue = -2147483648; + + private int reallySmallInt32_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int ReallySmallInt32 { + get { if ((_hasBits0 & 131072) != 0) { return reallySmallInt32_; } else { return ReallySmallInt32DefaultValue; } } + set { + _hasBits0 |= 131072; + reallySmallInt32_ = value; + } + } + /// Gets whether the "really_small_int32" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasReallySmallInt32 { + get { return (_hasBits0 & 131072) != 0; } + } + /// Clears the value of the "really_small_int32" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearReallySmallInt32() { + _hasBits0 &= ~131072; + } + + /// Field number for the "really_small_int64" field. + public const int ReallySmallInt64FieldNumber = 22; + private readonly static long ReallySmallInt64DefaultValue = -9223372036854775808L; + + private long reallySmallInt64_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public long ReallySmallInt64 { + get { if ((_hasBits0 & 262144) != 0) { return reallySmallInt64_; } else { return ReallySmallInt64DefaultValue; } } + set { + _hasBits0 |= 262144; + reallySmallInt64_ = value; + } + } + /// Gets whether the "really_small_int64" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasReallySmallInt64 { + get { return (_hasBits0 & 262144) != 0; } + } + /// Clears the value of the "really_small_int64" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearReallySmallInt64() { + _hasBits0 &= ~262144; + } + + /// Field number for the "utf8_string" field. + public const int Utf8StringFieldNumber = 6; + private readonly static string Utf8StringDefaultValue = global::System.Text.Encoding.UTF8.GetString(global::System.Convert.FromBase64String("4Yi0"), 0, 3); + + private string utf8String_; + /// + /// The default value here is UTF-8 for "\u1234". (We could also just type + /// the UTF-8 text directly into this text file rather than escape it, but + /// lots of people use editors that would be confused by this.) + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string Utf8String { + get { return utf8String_ ?? Utf8StringDefaultValue; } + set { + utf8String_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "utf8_string" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasUtf8String { + get { return utf8String_ != null; } + } + /// Clears the value of the "utf8_string" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearUtf8String() { + utf8String_ = null; + } + + /// Field number for the "zero_float" field. + public const int ZeroFloatFieldNumber = 7; + private readonly static float ZeroFloatDefaultValue = 0F; + + private float zeroFloat_; + /// + /// Tests for single-precision floating-point values. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public float ZeroFloat { + get { if ((_hasBits0 & 16) != 0) { return zeroFloat_; } else { return ZeroFloatDefaultValue; } } + set { + _hasBits0 |= 16; + zeroFloat_ = value; + } + } + /// Gets whether the "zero_float" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasZeroFloat { + get { return (_hasBits0 & 16) != 0; } + } + /// Clears the value of the "zero_float" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearZeroFloat() { + _hasBits0 &= ~16; + } + + /// Field number for the "one_float" field. + public const int OneFloatFieldNumber = 8; + private readonly static float OneFloatDefaultValue = 1F; + + private float oneFloat_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public float OneFloat { + get { if ((_hasBits0 & 32) != 0) { return oneFloat_; } else { return OneFloatDefaultValue; } } + set { + _hasBits0 |= 32; + oneFloat_ = value; + } + } + /// Gets whether the "one_float" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOneFloat { + get { return (_hasBits0 & 32) != 0; } + } + /// Clears the value of the "one_float" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOneFloat() { + _hasBits0 &= ~32; + } + + /// Field number for the "small_float" field. + public const int SmallFloatFieldNumber = 9; + private readonly static float SmallFloatDefaultValue = 1.5F; + + private float smallFloat_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public float SmallFloat { + get { if ((_hasBits0 & 64) != 0) { return smallFloat_; } else { return SmallFloatDefaultValue; } } + set { + _hasBits0 |= 64; + smallFloat_ = value; + } + } + /// Gets whether the "small_float" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasSmallFloat { + get { return (_hasBits0 & 64) != 0; } + } + /// Clears the value of the "small_float" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearSmallFloat() { + _hasBits0 &= ~64; + } + + /// Field number for the "negative_one_float" field. + public const int NegativeOneFloatFieldNumber = 10; + private readonly static float NegativeOneFloatDefaultValue = -1F; + + private float negativeOneFloat_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public float NegativeOneFloat { + get { if ((_hasBits0 & 128) != 0) { return negativeOneFloat_; } else { return NegativeOneFloatDefaultValue; } } + set { + _hasBits0 |= 128; + negativeOneFloat_ = value; + } + } + /// Gets whether the "negative_one_float" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasNegativeOneFloat { + get { return (_hasBits0 & 128) != 0; } + } + /// Clears the value of the "negative_one_float" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearNegativeOneFloat() { + _hasBits0 &= ~128; + } + + /// Field number for the "negative_float" field. + public const int NegativeFloatFieldNumber = 11; + private readonly static float NegativeFloatDefaultValue = -1.5F; + + private float negativeFloat_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public float NegativeFloat { + get { if ((_hasBits0 & 256) != 0) { return negativeFloat_; } else { return NegativeFloatDefaultValue; } } + set { + _hasBits0 |= 256; + negativeFloat_ = value; + } + } + /// Gets whether the "negative_float" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasNegativeFloat { + get { return (_hasBits0 & 256) != 0; } + } + /// Clears the value of the "negative_float" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearNegativeFloat() { + _hasBits0 &= ~256; + } + + /// Field number for the "large_float" field. + public const int LargeFloatFieldNumber = 12; + private readonly static float LargeFloatDefaultValue = 2e+08F; + + private float largeFloat_; + /// + /// Using exponents + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public float LargeFloat { + get { if ((_hasBits0 & 512) != 0) { return largeFloat_; } else { return LargeFloatDefaultValue; } } + set { + _hasBits0 |= 512; + largeFloat_ = value; + } + } + /// Gets whether the "large_float" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasLargeFloat { + get { return (_hasBits0 & 512) != 0; } + } + /// Clears the value of the "large_float" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearLargeFloat() { + _hasBits0 &= ~512; + } + + /// Field number for the "small_negative_float" field. + public const int SmallNegativeFloatFieldNumber = 13; + private readonly static float SmallNegativeFloatDefaultValue = -8e-28F; + + private float smallNegativeFloat_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public float SmallNegativeFloat { + get { if ((_hasBits0 & 1024) != 0) { return smallNegativeFloat_; } else { return SmallNegativeFloatDefaultValue; } } + set { + _hasBits0 |= 1024; + smallNegativeFloat_ = value; + } + } + /// Gets whether the "small_negative_float" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasSmallNegativeFloat { + get { return (_hasBits0 & 1024) != 0; } + } + /// Clears the value of the "small_negative_float" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearSmallNegativeFloat() { + _hasBits0 &= ~1024; + } + + /// Field number for the "inf_double" field. + public const int InfDoubleFieldNumber = 14; + private readonly static double InfDoubleDefaultValue = double.PositiveInfinity; + + private double infDouble_; + /// + /// Text for nonfinite floating-point values. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public double InfDouble { + get { if ((_hasBits0 & 2048) != 0) { return infDouble_; } else { return InfDoubleDefaultValue; } } + set { + _hasBits0 |= 2048; + infDouble_ = value; + } + } + /// Gets whether the "inf_double" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasInfDouble { + get { return (_hasBits0 & 2048) != 0; } + } + /// Clears the value of the "inf_double" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearInfDouble() { + _hasBits0 &= ~2048; + } + + /// Field number for the "neg_inf_double" field. + public const int NegInfDoubleFieldNumber = 15; + private readonly static double NegInfDoubleDefaultValue = double.NegativeInfinity; + + private double negInfDouble_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public double NegInfDouble { + get { if ((_hasBits0 & 4096) != 0) { return negInfDouble_; } else { return NegInfDoubleDefaultValue; } } + set { + _hasBits0 |= 4096; + negInfDouble_ = value; + } + } + /// Gets whether the "neg_inf_double" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasNegInfDouble { + get { return (_hasBits0 & 4096) != 0; } + } + /// Clears the value of the "neg_inf_double" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearNegInfDouble() { + _hasBits0 &= ~4096; + } + + /// Field number for the "nan_double" field. + public const int NanDoubleFieldNumber = 16; + private readonly static double NanDoubleDefaultValue = double.NaN; + + private double nanDouble_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public double NanDouble { + get { if ((_hasBits0 & 8192) != 0) { return nanDouble_; } else { return NanDoubleDefaultValue; } } + set { + _hasBits0 |= 8192; + nanDouble_ = value; + } + } + /// Gets whether the "nan_double" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasNanDouble { + get { return (_hasBits0 & 8192) != 0; } + } + /// Clears the value of the "nan_double" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearNanDouble() { + _hasBits0 &= ~8192; + } + + /// Field number for the "inf_float" field. + public const int InfFloatFieldNumber = 17; + private readonly static float InfFloatDefaultValue = float.PositiveInfinity; + + private float infFloat_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public float InfFloat { + get { if ((_hasBits0 & 16384) != 0) { return infFloat_; } else { return InfFloatDefaultValue; } } + set { + _hasBits0 |= 16384; + infFloat_ = value; + } + } + /// Gets whether the "inf_float" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasInfFloat { + get { return (_hasBits0 & 16384) != 0; } + } + /// Clears the value of the "inf_float" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearInfFloat() { + _hasBits0 &= ~16384; + } + + /// Field number for the "neg_inf_float" field. + public const int NegInfFloatFieldNumber = 18; + private readonly static float NegInfFloatDefaultValue = float.NegativeInfinity; + + private float negInfFloat_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public float NegInfFloat { + get { if ((_hasBits0 & 32768) != 0) { return negInfFloat_; } else { return NegInfFloatDefaultValue; } } + set { + _hasBits0 |= 32768; + negInfFloat_ = value; + } + } + /// Gets whether the "neg_inf_float" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasNegInfFloat { + get { return (_hasBits0 & 32768) != 0; } + } + /// Clears the value of the "neg_inf_float" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearNegInfFloat() { + _hasBits0 &= ~32768; + } + + /// Field number for the "nan_float" field. + public const int NanFloatFieldNumber = 19; + private readonly static float NanFloatDefaultValue = float.NaN; + + private float nanFloat_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public float NanFloat { + get { if ((_hasBits0 & 65536) != 0) { return nanFloat_; } else { return NanFloatDefaultValue; } } + set { + _hasBits0 |= 65536; + nanFloat_ = value; + } + } + /// Gets whether the "nan_float" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasNanFloat { + get { return (_hasBits0 & 65536) != 0; } + } + /// Clears the value of the "nan_float" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearNanFloat() { + _hasBits0 &= ~65536; + } + + /// Field number for the "cpp_trigraph" field. + public const int CppTrigraphFieldNumber = 20; + private readonly static string CppTrigraphDefaultValue = global::System.Text.Encoding.UTF8.GetString(global::System.Convert.FromBase64String("PyA/ID8/ID8/ID8/PyA/Py8gPz8t"), 0, 21); + + private string cppTrigraph_; + /// + /// Tests for C++ trigraphs. + /// Trigraphs should be escaped in C++ generated files, but they should not be + /// escaped for other languages. + /// Note that in .proto file, "\?" is a valid way to escape ? in string + /// literals. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string CppTrigraph { + get { return cppTrigraph_ ?? CppTrigraphDefaultValue; } + set { + cppTrigraph_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "cpp_trigraph" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasCppTrigraph { + get { return cppTrigraph_ != null; } + } + /// Clears the value of the "cpp_trigraph" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearCppTrigraph() { + cppTrigraph_ = null; + } + + /// Field number for the "string_with_zero" field. + public const int StringWithZeroFieldNumber = 23; + private readonly static string StringWithZeroDefaultValue = global::System.Text.Encoding.UTF8.GetString(global::System.Convert.FromBase64String("aGVsAGxv"), 0, 6); + + private string stringWithZero_; + /// + /// String defaults containing the character '\000' + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string StringWithZero { + get { return stringWithZero_ ?? StringWithZeroDefaultValue; } + set { + stringWithZero_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "string_with_zero" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasStringWithZero { + get { return stringWithZero_ != null; } + } + /// Clears the value of the "string_with_zero" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearStringWithZero() { + stringWithZero_ = null; + } + + /// Field number for the "bytes_with_zero" field. + public const int BytesWithZeroFieldNumber = 24; + private readonly static pb::ByteString BytesWithZeroDefaultValue = pb::ByteString.FromBase64("d29yAGxk"); + + private pb::ByteString bytesWithZero_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pb::ByteString BytesWithZero { + get { return bytesWithZero_ ?? BytesWithZeroDefaultValue; } + set { + bytesWithZero_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "bytes_with_zero" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasBytesWithZero { + get { return bytesWithZero_ != null; } + } + /// Clears the value of the "bytes_with_zero" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearBytesWithZero() { + bytesWithZero_ = null; + } + + /// Field number for the "string_piece_with_zero" field. + public const int StringPieceWithZeroFieldNumber = 25; + private readonly static string StringPieceWithZeroDefaultValue = global::System.Text.Encoding.UTF8.GetString(global::System.Convert.FromBase64String("YWIAYw=="), 0, 4); + + private string stringPieceWithZero_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string StringPieceWithZero { + get { return stringPieceWithZero_ ?? StringPieceWithZeroDefaultValue; } + set { + stringPieceWithZero_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "string_piece_with_zero" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasStringPieceWithZero { + get { return stringPieceWithZero_ != null; } + } + /// Clears the value of the "string_piece_with_zero" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearStringPieceWithZero() { + stringPieceWithZero_ = null; + } + + /// Field number for the "cord_with_zero" field. + public const int CordWithZeroFieldNumber = 26; + private readonly static string CordWithZeroDefaultValue = global::System.Text.Encoding.UTF8.GetString(global::System.Convert.FromBase64String("MTIAMw=="), 0, 4); + + private string cordWithZero_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string CordWithZero { + get { return cordWithZero_ ?? CordWithZeroDefaultValue; } + set { + cordWithZero_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "cord_with_zero" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasCordWithZero { + get { return cordWithZero_ != null; } + } + /// Clears the value of the "cord_with_zero" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearCordWithZero() { + cordWithZero_ = null; + } + + /// Field number for the "replacement_string" field. + public const int ReplacementStringFieldNumber = 27; + private readonly static string ReplacementStringDefaultValue = global::System.Text.Encoding.UTF8.GetString(global::System.Convert.FromBase64String("JHt1bmtub3dufQ=="), 0, 10); + + private string replacementString_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string ReplacementString { + get { return replacementString_ ?? ReplacementStringDefaultValue; } + set { + replacementString_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "replacement_string" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasReplacementString { + get { return replacementString_ != null; } + } + /// Clears the value of the "replacement_string" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearReplacementString() { + replacementString_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestExtremeDefaultValues); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestExtremeDefaultValues other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (EscapedBytes != other.EscapedBytes) return false; + if (LargeUint32 != other.LargeUint32) return false; + if (LargeUint64 != other.LargeUint64) return false; + if (SmallInt32 != other.SmallInt32) return false; + if (SmallInt64 != other.SmallInt64) return false; + if (ReallySmallInt32 != other.ReallySmallInt32) return false; + if (ReallySmallInt64 != other.ReallySmallInt64) return false; + if (Utf8String != other.Utf8String) return false; + if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(ZeroFloat, other.ZeroFloat)) return false; + if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(OneFloat, other.OneFloat)) return false; + if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(SmallFloat, other.SmallFloat)) return false; + if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(NegativeOneFloat, other.NegativeOneFloat)) return false; + if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(NegativeFloat, other.NegativeFloat)) return false; + if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(LargeFloat, other.LargeFloat)) return false; + if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(SmallNegativeFloat, other.SmallNegativeFloat)) return false; + if (!pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.Equals(InfDouble, other.InfDouble)) return false; + if (!pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.Equals(NegInfDouble, other.NegInfDouble)) return false; + if (!pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.Equals(NanDouble, other.NanDouble)) return false; + if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(InfFloat, other.InfFloat)) return false; + if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(NegInfFloat, other.NegInfFloat)) return false; + if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(NanFloat, other.NanFloat)) return false; + if (CppTrigraph != other.CppTrigraph) return false; + if (StringWithZero != other.StringWithZero) return false; + if (BytesWithZero != other.BytesWithZero) return false; + if (StringPieceWithZero != other.StringPieceWithZero) return false; + if (CordWithZero != other.CordWithZero) return false; + if (ReplacementString != other.ReplacementString) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasEscapedBytes) hash ^= EscapedBytes.GetHashCode(); + if (HasLargeUint32) hash ^= LargeUint32.GetHashCode(); + if (HasLargeUint64) hash ^= LargeUint64.GetHashCode(); + if (HasSmallInt32) hash ^= SmallInt32.GetHashCode(); + if (HasSmallInt64) hash ^= SmallInt64.GetHashCode(); + if (HasReallySmallInt32) hash ^= ReallySmallInt32.GetHashCode(); + if (HasReallySmallInt64) hash ^= ReallySmallInt64.GetHashCode(); + if (HasUtf8String) hash ^= Utf8String.GetHashCode(); + if (HasZeroFloat) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(ZeroFloat); + if (HasOneFloat) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(OneFloat); + if (HasSmallFloat) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(SmallFloat); + if (HasNegativeOneFloat) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(NegativeOneFloat); + if (HasNegativeFloat) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(NegativeFloat); + if (HasLargeFloat) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(LargeFloat); + if (HasSmallNegativeFloat) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(SmallNegativeFloat); + if (HasInfDouble) hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(InfDouble); + if (HasNegInfDouble) hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(NegInfDouble); + if (HasNanDouble) hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(NanDouble); + if (HasInfFloat) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(InfFloat); + if (HasNegInfFloat) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(NegInfFloat); + if (HasNanFloat) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(NanFloat); + if (HasCppTrigraph) hash ^= CppTrigraph.GetHashCode(); + if (HasStringWithZero) hash ^= StringWithZero.GetHashCode(); + if (HasBytesWithZero) hash ^= BytesWithZero.GetHashCode(); + if (HasStringPieceWithZero) hash ^= StringPieceWithZero.GetHashCode(); + if (HasCordWithZero) hash ^= CordWithZero.GetHashCode(); + if (HasReplacementString) hash ^= ReplacementString.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasEscapedBytes) { + output.WriteRawTag(10); + output.WriteBytes(EscapedBytes); + } + if (HasLargeUint32) { + output.WriteRawTag(16); + output.WriteUInt32(LargeUint32); + } + if (HasLargeUint64) { + output.WriteRawTag(24); + output.WriteUInt64(LargeUint64); + } + if (HasSmallInt32) { + output.WriteRawTag(32); + output.WriteInt32(SmallInt32); + } + if (HasSmallInt64) { + output.WriteRawTag(40); + output.WriteInt64(SmallInt64); + } + if (HasUtf8String) { + output.WriteRawTag(50); + output.WriteString(Utf8String); + } + if (HasZeroFloat) { + output.WriteRawTag(61); + output.WriteFloat(ZeroFloat); + } + if (HasOneFloat) { + output.WriteRawTag(69); + output.WriteFloat(OneFloat); + } + if (HasSmallFloat) { + output.WriteRawTag(77); + output.WriteFloat(SmallFloat); + } + if (HasNegativeOneFloat) { + output.WriteRawTag(85); + output.WriteFloat(NegativeOneFloat); + } + if (HasNegativeFloat) { + output.WriteRawTag(93); + output.WriteFloat(NegativeFloat); + } + if (HasLargeFloat) { + output.WriteRawTag(101); + output.WriteFloat(LargeFloat); + } + if (HasSmallNegativeFloat) { + output.WriteRawTag(109); + output.WriteFloat(SmallNegativeFloat); + } + if (HasInfDouble) { + output.WriteRawTag(113); + output.WriteDouble(InfDouble); + } + if (HasNegInfDouble) { + output.WriteRawTag(121); + output.WriteDouble(NegInfDouble); + } + if (HasNanDouble) { + output.WriteRawTag(129, 1); + output.WriteDouble(NanDouble); + } + if (HasInfFloat) { + output.WriteRawTag(141, 1); + output.WriteFloat(InfFloat); + } + if (HasNegInfFloat) { + output.WriteRawTag(149, 1); + output.WriteFloat(NegInfFloat); + } + if (HasNanFloat) { + output.WriteRawTag(157, 1); + output.WriteFloat(NanFloat); + } + if (HasCppTrigraph) { + output.WriteRawTag(162, 1); + output.WriteString(CppTrigraph); + } + if (HasReallySmallInt32) { + output.WriteRawTag(168, 1); + output.WriteInt32(ReallySmallInt32); + } + if (HasReallySmallInt64) { + output.WriteRawTag(176, 1); + output.WriteInt64(ReallySmallInt64); + } + if (HasStringWithZero) { + output.WriteRawTag(186, 1); + output.WriteString(StringWithZero); + } + if (HasBytesWithZero) { + output.WriteRawTag(194, 1); + output.WriteBytes(BytesWithZero); + } + if (HasStringPieceWithZero) { + output.WriteRawTag(202, 1); + output.WriteString(StringPieceWithZero); + } + if (HasCordWithZero) { + output.WriteRawTag(210, 1); + output.WriteString(CordWithZero); + } + if (HasReplacementString) { + output.WriteRawTag(218, 1); + output.WriteString(ReplacementString); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasEscapedBytes) { + output.WriteRawTag(10); + output.WriteBytes(EscapedBytes); + } + if (HasLargeUint32) { + output.WriteRawTag(16); + output.WriteUInt32(LargeUint32); + } + if (HasLargeUint64) { + output.WriteRawTag(24); + output.WriteUInt64(LargeUint64); + } + if (HasSmallInt32) { + output.WriteRawTag(32); + output.WriteInt32(SmallInt32); + } + if (HasSmallInt64) { + output.WriteRawTag(40); + output.WriteInt64(SmallInt64); + } + if (HasUtf8String) { + output.WriteRawTag(50); + output.WriteString(Utf8String); + } + if (HasZeroFloat) { + output.WriteRawTag(61); + output.WriteFloat(ZeroFloat); + } + if (HasOneFloat) { + output.WriteRawTag(69); + output.WriteFloat(OneFloat); + } + if (HasSmallFloat) { + output.WriteRawTag(77); + output.WriteFloat(SmallFloat); + } + if (HasNegativeOneFloat) { + output.WriteRawTag(85); + output.WriteFloat(NegativeOneFloat); + } + if (HasNegativeFloat) { + output.WriteRawTag(93); + output.WriteFloat(NegativeFloat); + } + if (HasLargeFloat) { + output.WriteRawTag(101); + output.WriteFloat(LargeFloat); + } + if (HasSmallNegativeFloat) { + output.WriteRawTag(109); + output.WriteFloat(SmallNegativeFloat); + } + if (HasInfDouble) { + output.WriteRawTag(113); + output.WriteDouble(InfDouble); + } + if (HasNegInfDouble) { + output.WriteRawTag(121); + output.WriteDouble(NegInfDouble); + } + if (HasNanDouble) { + output.WriteRawTag(129, 1); + output.WriteDouble(NanDouble); + } + if (HasInfFloat) { + output.WriteRawTag(141, 1); + output.WriteFloat(InfFloat); + } + if (HasNegInfFloat) { + output.WriteRawTag(149, 1); + output.WriteFloat(NegInfFloat); + } + if (HasNanFloat) { + output.WriteRawTag(157, 1); + output.WriteFloat(NanFloat); + } + if (HasCppTrigraph) { + output.WriteRawTag(162, 1); + output.WriteString(CppTrigraph); + } + if (HasReallySmallInt32) { + output.WriteRawTag(168, 1); + output.WriteInt32(ReallySmallInt32); + } + if (HasReallySmallInt64) { + output.WriteRawTag(176, 1); + output.WriteInt64(ReallySmallInt64); + } + if (HasStringWithZero) { + output.WriteRawTag(186, 1); + output.WriteString(StringWithZero); + } + if (HasBytesWithZero) { + output.WriteRawTag(194, 1); + output.WriteBytes(BytesWithZero); + } + if (HasStringPieceWithZero) { + output.WriteRawTag(202, 1); + output.WriteString(StringPieceWithZero); + } + if (HasCordWithZero) { + output.WriteRawTag(210, 1); + output.WriteString(CordWithZero); + } + if (HasReplacementString) { + output.WriteRawTag(218, 1); + output.WriteString(ReplacementString); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasEscapedBytes) { + size += 1 + pb::CodedOutputStream.ComputeBytesSize(EscapedBytes); + } + if (HasLargeUint32) { + size += 1 + pb::CodedOutputStream.ComputeUInt32Size(LargeUint32); + } + if (HasLargeUint64) { + size += 1 + pb::CodedOutputStream.ComputeUInt64Size(LargeUint64); + } + if (HasSmallInt32) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(SmallInt32); + } + if (HasSmallInt64) { + size += 1 + pb::CodedOutputStream.ComputeInt64Size(SmallInt64); + } + if (HasReallySmallInt32) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(ReallySmallInt32); + } + if (HasReallySmallInt64) { + size += 2 + pb::CodedOutputStream.ComputeInt64Size(ReallySmallInt64); + } + if (HasUtf8String) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Utf8String); + } + if (HasZeroFloat) { + size += 1 + 4; + } + if (HasOneFloat) { + size += 1 + 4; + } + if (HasSmallFloat) { + size += 1 + 4; + } + if (HasNegativeOneFloat) { + size += 1 + 4; + } + if (HasNegativeFloat) { + size += 1 + 4; + } + if (HasLargeFloat) { + size += 1 + 4; + } + if (HasSmallNegativeFloat) { + size += 1 + 4; + } + if (HasInfDouble) { + size += 1 + 8; + } + if (HasNegInfDouble) { + size += 1 + 8; + } + if (HasNanDouble) { + size += 2 + 8; + } + if (HasInfFloat) { + size += 2 + 4; + } + if (HasNegInfFloat) { + size += 2 + 4; + } + if (HasNanFloat) { + size += 2 + 4; + } + if (HasCppTrigraph) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(CppTrigraph); + } + if (HasStringWithZero) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(StringWithZero); + } + if (HasBytesWithZero) { + size += 2 + pb::CodedOutputStream.ComputeBytesSize(BytesWithZero); + } + if (HasStringPieceWithZero) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(StringPieceWithZero); + } + if (HasCordWithZero) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(CordWithZero); + } + if (HasReplacementString) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(ReplacementString); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestExtremeDefaultValues other) { + if (other == null) { + return; + } + if (other.HasEscapedBytes) { + EscapedBytes = other.EscapedBytes; + } + if (other.HasLargeUint32) { + LargeUint32 = other.LargeUint32; + } + if (other.HasLargeUint64) { + LargeUint64 = other.LargeUint64; + } + if (other.HasSmallInt32) { + SmallInt32 = other.SmallInt32; + } + if (other.HasSmallInt64) { + SmallInt64 = other.SmallInt64; + } + if (other.HasReallySmallInt32) { + ReallySmallInt32 = other.ReallySmallInt32; + } + if (other.HasReallySmallInt64) { + ReallySmallInt64 = other.ReallySmallInt64; + } + if (other.HasUtf8String) { + Utf8String = other.Utf8String; + } + if (other.HasZeroFloat) { + ZeroFloat = other.ZeroFloat; + } + if (other.HasOneFloat) { + OneFloat = other.OneFloat; + } + if (other.HasSmallFloat) { + SmallFloat = other.SmallFloat; + } + if (other.HasNegativeOneFloat) { + NegativeOneFloat = other.NegativeOneFloat; + } + if (other.HasNegativeFloat) { + NegativeFloat = other.NegativeFloat; + } + if (other.HasLargeFloat) { + LargeFloat = other.LargeFloat; + } + if (other.HasSmallNegativeFloat) { + SmallNegativeFloat = other.SmallNegativeFloat; + } + if (other.HasInfDouble) { + InfDouble = other.InfDouble; + } + if (other.HasNegInfDouble) { + NegInfDouble = other.NegInfDouble; + } + if (other.HasNanDouble) { + NanDouble = other.NanDouble; + } + if (other.HasInfFloat) { + InfFloat = other.InfFloat; + } + if (other.HasNegInfFloat) { + NegInfFloat = other.NegInfFloat; + } + if (other.HasNanFloat) { + NanFloat = other.NanFloat; + } + if (other.HasCppTrigraph) { + CppTrigraph = other.CppTrigraph; + } + if (other.HasStringWithZero) { + StringWithZero = other.StringWithZero; + } + if (other.HasBytesWithZero) { + BytesWithZero = other.BytesWithZero; + } + if (other.HasStringPieceWithZero) { + StringPieceWithZero = other.StringPieceWithZero; + } + if (other.HasCordWithZero) { + CordWithZero = other.CordWithZero; + } + if (other.HasReplacementString) { + ReplacementString = other.ReplacementString; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + EscapedBytes = input.ReadBytes(); + break; + } + case 16: { + LargeUint32 = input.ReadUInt32(); + break; + } + case 24: { + LargeUint64 = input.ReadUInt64(); + break; + } + case 32: { + SmallInt32 = input.ReadInt32(); + break; + } + case 40: { + SmallInt64 = input.ReadInt64(); + break; + } + case 50: { + Utf8String = input.ReadString(); + break; + } + case 61: { + ZeroFloat = input.ReadFloat(); + break; + } + case 69: { + OneFloat = input.ReadFloat(); + break; + } + case 77: { + SmallFloat = input.ReadFloat(); + break; + } + case 85: { + NegativeOneFloat = input.ReadFloat(); + break; + } + case 93: { + NegativeFloat = input.ReadFloat(); + break; + } + case 101: { + LargeFloat = input.ReadFloat(); + break; + } + case 109: { + SmallNegativeFloat = input.ReadFloat(); + break; + } + case 113: { + InfDouble = input.ReadDouble(); + break; + } + case 121: { + NegInfDouble = input.ReadDouble(); + break; + } + case 129: { + NanDouble = input.ReadDouble(); + break; + } + case 141: { + InfFloat = input.ReadFloat(); + break; + } + case 149: { + NegInfFloat = input.ReadFloat(); + break; + } + case 157: { + NanFloat = input.ReadFloat(); + break; + } + case 162: { + CppTrigraph = input.ReadString(); + break; + } + case 168: { + ReallySmallInt32 = input.ReadInt32(); + break; + } + case 176: { + ReallySmallInt64 = input.ReadInt64(); + break; + } + case 186: { + StringWithZero = input.ReadString(); + break; + } + case 194: { + BytesWithZero = input.ReadBytes(); + break; + } + case 202: { + StringPieceWithZero = input.ReadString(); + break; + } + case 210: { + CordWithZero = input.ReadString(); + break; + } + case 218: { + ReplacementString = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + EscapedBytes = input.ReadBytes(); + break; + } + case 16: { + LargeUint32 = input.ReadUInt32(); + break; + } + case 24: { + LargeUint64 = input.ReadUInt64(); + break; + } + case 32: { + SmallInt32 = input.ReadInt32(); + break; + } + case 40: { + SmallInt64 = input.ReadInt64(); + break; + } + case 50: { + Utf8String = input.ReadString(); + break; + } + case 61: { + ZeroFloat = input.ReadFloat(); + break; + } + case 69: { + OneFloat = input.ReadFloat(); + break; + } + case 77: { + SmallFloat = input.ReadFloat(); + break; + } + case 85: { + NegativeOneFloat = input.ReadFloat(); + break; + } + case 93: { + NegativeFloat = input.ReadFloat(); + break; + } + case 101: { + LargeFloat = input.ReadFloat(); + break; + } + case 109: { + SmallNegativeFloat = input.ReadFloat(); + break; + } + case 113: { + InfDouble = input.ReadDouble(); + break; + } + case 121: { + NegInfDouble = input.ReadDouble(); + break; + } + case 129: { + NanDouble = input.ReadDouble(); + break; + } + case 141: { + InfFloat = input.ReadFloat(); + break; + } + case 149: { + NegInfFloat = input.ReadFloat(); + break; + } + case 157: { + NanFloat = input.ReadFloat(); + break; + } + case 162: { + CppTrigraph = input.ReadString(); + break; + } + case 168: { + ReallySmallInt32 = input.ReadInt32(); + break; + } + case 176: { + ReallySmallInt64 = input.ReadInt64(); + break; + } + case 186: { + StringWithZero = input.ReadString(); + break; + } + case 194: { + BytesWithZero = input.ReadBytes(); + break; + } + case 202: { + StringPieceWithZero = input.ReadString(); + break; + } + case 210: { + CordWithZero = input.ReadString(); + break; + } + case 218: { + ReplacementString = input.ReadString(); + break; + } + } + } + } + #endif + + } + + public sealed partial class SparseEnumMessage : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new SparseEnumMessage()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[33]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public SparseEnumMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public SparseEnumMessage(SparseEnumMessage other) : this() { + _hasBits0 = other._hasBits0; + sparseEnum_ = other.sparseEnum_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public SparseEnumMessage Clone() { + return new SparseEnumMessage(this); + } + + /// Field number for the "sparse_enum" field. + public const int SparseEnumFieldNumber = 1; + private readonly static global::Google.Protobuf.TestProtos.Proto2.TestSparseEnum SparseEnumDefaultValue = global::Google.Protobuf.TestProtos.Proto2.TestSparseEnum.SparseA; + + private global::Google.Protobuf.TestProtos.Proto2.TestSparseEnum sparseEnum_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestSparseEnum SparseEnum { + get { if ((_hasBits0 & 1) != 0) { return sparseEnum_; } else { return SparseEnumDefaultValue; } } + set { + _hasBits0 |= 1; + sparseEnum_ = value; + } + } + /// Gets whether the "sparse_enum" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasSparseEnum { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "sparse_enum" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearSparseEnum() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as SparseEnumMessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(SparseEnumMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (SparseEnum != other.SparseEnum) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasSparseEnum) hash ^= SparseEnum.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasSparseEnum) { + output.WriteRawTag(8); + output.WriteEnum((int) SparseEnum); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasSparseEnum) { + output.WriteRawTag(8); + output.WriteEnum((int) SparseEnum); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasSparseEnum) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) SparseEnum); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(SparseEnumMessage other) { + if (other == null) { + return; + } + if (other.HasSparseEnum) { + SparseEnum = other.SparseEnum; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + SparseEnum = (global::Google.Protobuf.TestProtos.Proto2.TestSparseEnum) input.ReadEnum(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + SparseEnum = (global::Google.Protobuf.TestProtos.Proto2.TestSparseEnum) input.ReadEnum(); + break; + } + } + } + } + #endif + + } + + /// + /// Test String and Bytes: string is for valid UTF-8 strings + /// + public sealed partial class OneString : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new OneString()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[34]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneString() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneString(OneString other) : this() { + data_ = other.data_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneString Clone() { + return new OneString(this); + } + + /// Field number for the "data" field. + public const int DataFieldNumber = 1; + private readonly static string DataDefaultValue = ""; + + private string data_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string Data { + get { return data_ ?? DataDefaultValue; } + set { + data_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "data" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasData { + get { return data_ != null; } + } + /// Clears the value of the "data" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearData() { + data_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as OneString); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(OneString other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Data != other.Data) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasData) hash ^= Data.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasData) { + output.WriteRawTag(10); + output.WriteString(Data); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasData) { + output.WriteRawTag(10); + output.WriteString(Data); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasData) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Data); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(OneString other) { + if (other == null) { + return; + } + if (other.HasData) { + Data = other.Data; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Data = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Data = input.ReadString(); + break; + } + } + } + } + #endif + + } + + public sealed partial class MoreString : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new MoreString()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[35]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MoreString() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MoreString(MoreString other) : this() { + data_ = other.data_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MoreString Clone() { + return new MoreString(this); + } + + /// Field number for the "data" field. + public const int DataFieldNumber = 1; + private static readonly pb::FieldCodec _repeated_data_codec + = pb::FieldCodec.ForString(10); + private readonly pbc::RepeatedField data_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Data { + get { return data_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as MoreString); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(MoreString other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!data_.Equals(other.data_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + hash ^= data_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + data_.WriteTo(output, _repeated_data_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + data_.WriteTo(ref output, _repeated_data_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + size += data_.CalculateSize(_repeated_data_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(MoreString other) { + if (other == null) { + return; + } + data_.Add(other.data_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + data_.AddEntriesFrom(input, _repeated_data_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + data_.AddEntriesFrom(ref input, _repeated_data_codec); + break; + } + } + } + } + #endif + + } + + public sealed partial class OneBytes : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new OneBytes()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[36]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneBytes() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneBytes(OneBytes other) : this() { + data_ = other.data_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneBytes Clone() { + return new OneBytes(this); + } + + /// Field number for the "data" field. + public const int DataFieldNumber = 1; + private readonly static pb::ByteString DataDefaultValue = pb::ByteString.Empty; + + private pb::ByteString data_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pb::ByteString Data { + get { return data_ ?? DataDefaultValue; } + set { + data_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "data" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasData { + get { return data_ != null; } + } + /// Clears the value of the "data" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearData() { + data_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as OneBytes); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(OneBytes other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Data != other.Data) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasData) hash ^= Data.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasData) { + output.WriteRawTag(10); + output.WriteBytes(Data); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasData) { + output.WriteRawTag(10); + output.WriteBytes(Data); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasData) { + size += 1 + pb::CodedOutputStream.ComputeBytesSize(Data); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(OneBytes other) { + if (other == null) { + return; + } + if (other.HasData) { + Data = other.Data; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Data = input.ReadBytes(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Data = input.ReadBytes(); + break; + } + } + } + } + #endif + + } + + public sealed partial class MoreBytes : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new MoreBytes()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[37]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MoreBytes() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MoreBytes(MoreBytes other) : this() { + data_ = other.data_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MoreBytes Clone() { + return new MoreBytes(this); + } + + /// Field number for the "data" field. + public const int DataFieldNumber = 1; + private static readonly pb::FieldCodec _repeated_data_codec + = pb::FieldCodec.ForBytes(10); + private readonly pbc::RepeatedField data_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Data { + get { return data_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as MoreBytes); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(MoreBytes other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!data_.Equals(other.data_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + hash ^= data_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + data_.WriteTo(output, _repeated_data_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + data_.WriteTo(ref output, _repeated_data_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + size += data_.CalculateSize(_repeated_data_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(MoreBytes other) { + if (other == null) { + return; + } + data_.Add(other.data_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + data_.AddEntriesFrom(input, _repeated_data_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + data_.AddEntriesFrom(ref input, _repeated_data_codec); + break; + } + } + } + } + #endif + + } + + /// + /// Test int32, uint32, int64, uint64, and bool are all compatible + /// + public sealed partial class Int32Message : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Int32Message()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[38]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Int32Message() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Int32Message(Int32Message other) : this() { + _hasBits0 = other._hasBits0; + data_ = other.data_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Int32Message Clone() { + return new Int32Message(this); + } + + /// Field number for the "data" field. + public const int DataFieldNumber = 1; + private readonly static int DataDefaultValue = 0; + + private int data_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Data { + get { if ((_hasBits0 & 1) != 0) { return data_; } else { return DataDefaultValue; } } + set { + _hasBits0 |= 1; + data_ = value; + } + } + /// Gets whether the "data" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasData { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "data" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearData() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as Int32Message); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(Int32Message other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Data != other.Data) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasData) hash ^= Data.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasData) { + output.WriteRawTag(8); + output.WriteInt32(Data); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasData) { + output.WriteRawTag(8); + output.WriteInt32(Data); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasData) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Data); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(Int32Message other) { + if (other == null) { + return; + } + if (other.HasData) { + Data = other.Data; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Data = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Data = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + public sealed partial class Uint32Message : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Uint32Message()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[39]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Uint32Message() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Uint32Message(Uint32Message other) : this() { + _hasBits0 = other._hasBits0; + data_ = other.data_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Uint32Message Clone() { + return new Uint32Message(this); + } + + /// Field number for the "data" field. + public const int DataFieldNumber = 1; + private readonly static uint DataDefaultValue = 0; + + private uint data_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public uint Data { + get { if ((_hasBits0 & 1) != 0) { return data_; } else { return DataDefaultValue; } } + set { + _hasBits0 |= 1; + data_ = value; + } + } + /// Gets whether the "data" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasData { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "data" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearData() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as Uint32Message); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(Uint32Message other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Data != other.Data) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasData) hash ^= Data.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasData) { + output.WriteRawTag(8); + output.WriteUInt32(Data); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasData) { + output.WriteRawTag(8); + output.WriteUInt32(Data); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasData) { + size += 1 + pb::CodedOutputStream.ComputeUInt32Size(Data); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(Uint32Message other) { + if (other == null) { + return; + } + if (other.HasData) { + Data = other.Data; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Data = input.ReadUInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Data = input.ReadUInt32(); + break; + } + } + } + } + #endif + + } + + public sealed partial class Int64Message : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Int64Message()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[40]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Int64Message() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Int64Message(Int64Message other) : this() { + _hasBits0 = other._hasBits0; + data_ = other.data_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Int64Message Clone() { + return new Int64Message(this); + } + + /// Field number for the "data" field. + public const int DataFieldNumber = 1; + private readonly static long DataDefaultValue = 0L; + + private long data_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public long Data { + get { if ((_hasBits0 & 1) != 0) { return data_; } else { return DataDefaultValue; } } + set { + _hasBits0 |= 1; + data_ = value; + } + } + /// Gets whether the "data" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasData { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "data" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearData() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as Int64Message); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(Int64Message other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Data != other.Data) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasData) hash ^= Data.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasData) { + output.WriteRawTag(8); + output.WriteInt64(Data); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasData) { + output.WriteRawTag(8); + output.WriteInt64(Data); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasData) { + size += 1 + pb::CodedOutputStream.ComputeInt64Size(Data); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(Int64Message other) { + if (other == null) { + return; + } + if (other.HasData) { + Data = other.Data; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Data = input.ReadInt64(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Data = input.ReadInt64(); + break; + } + } + } + } + #endif + + } + + public sealed partial class Uint64Message : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Uint64Message()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[41]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Uint64Message() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Uint64Message(Uint64Message other) : this() { + _hasBits0 = other._hasBits0; + data_ = other.data_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Uint64Message Clone() { + return new Uint64Message(this); + } + + /// Field number for the "data" field. + public const int DataFieldNumber = 1; + private readonly static ulong DataDefaultValue = 0UL; + + private ulong data_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ulong Data { + get { if ((_hasBits0 & 1) != 0) { return data_; } else { return DataDefaultValue; } } + set { + _hasBits0 |= 1; + data_ = value; + } + } + /// Gets whether the "data" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasData { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "data" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearData() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as Uint64Message); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(Uint64Message other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Data != other.Data) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasData) hash ^= Data.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasData) { + output.WriteRawTag(8); + output.WriteUInt64(Data); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasData) { + output.WriteRawTag(8); + output.WriteUInt64(Data); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasData) { + size += 1 + pb::CodedOutputStream.ComputeUInt64Size(Data); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(Uint64Message other) { + if (other == null) { + return; + } + if (other.HasData) { + Data = other.Data; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Data = input.ReadUInt64(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Data = input.ReadUInt64(); + break; + } + } + } + } + #endif + + } + + public sealed partial class BoolMessage : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new BoolMessage()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[42]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public BoolMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public BoolMessage(BoolMessage other) : this() { + _hasBits0 = other._hasBits0; + data_ = other.data_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public BoolMessage Clone() { + return new BoolMessage(this); + } + + /// Field number for the "data" field. + public const int DataFieldNumber = 1; + private readonly static bool DataDefaultValue = false; + + private bool data_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Data { + get { if ((_hasBits0 & 1) != 0) { return data_; } else { return DataDefaultValue; } } + set { + _hasBits0 |= 1; + data_ = value; + } + } + /// Gets whether the "data" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasData { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "data" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearData() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as BoolMessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(BoolMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Data != other.Data) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasData) hash ^= Data.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasData) { + output.WriteRawTag(8); + output.WriteBool(Data); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasData) { + output.WriteRawTag(8); + output.WriteBool(Data); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasData) { + size += 1 + 1; + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(BoolMessage other) { + if (other == null) { + return; + } + if (other.HasData) { + Data = other.Data; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Data = input.ReadBool(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Data = input.ReadBool(); + break; + } + } + } + } + #endif + + } + + /// + /// Test oneofs. + /// + public sealed partial class TestOneof : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestOneof()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[43]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestOneof() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestOneof(TestOneof other) : this() { + switch (other.FooCase) { + case FooOneofCase.FooInt: + FooInt = other.FooInt; + break; + case FooOneofCase.FooString: + FooString = other.FooString; + break; + case FooOneofCase.FooMessage: + FooMessage = other.FooMessage.Clone(); + break; + case FooOneofCase.FooGroup: + FooGroup = other.FooGroup.Clone(); + break; + } + + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestOneof Clone() { + return new TestOneof(this); + } + + /// Field number for the "foo_int" field. + public const int FooIntFieldNumber = 1; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int FooInt { + get { return HasFooInt ? (int) foo_ : 0; } + set { + foo_ = value; + fooCase_ = FooOneofCase.FooInt; + } + } + /// Gets whether the "foo_int" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFooInt { + get { return fooCase_ == FooOneofCase.FooInt; } + } + /// Clears the value of the oneof if it's currently set to "foo_int" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFooInt() { + if (HasFooInt) { + ClearFoo(); + } + } + + /// Field number for the "foo_string" field. + public const int FooStringFieldNumber = 2; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string FooString { + get { return HasFooString ? (string) foo_ : ""; } + set { + foo_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + fooCase_ = FooOneofCase.FooString; + } + } + /// Gets whether the "foo_string" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFooString { + get { return fooCase_ == FooOneofCase.FooString; } + } + /// Clears the value of the oneof if it's currently set to "foo_string" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFooString() { + if (HasFooString) { + ClearFoo(); + } + } + + /// Field number for the "foo_message" field. + public const int FooMessageFieldNumber = 3; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestAllTypes FooMessage { + get { return fooCase_ == FooOneofCase.FooMessage ? (global::Google.Protobuf.TestProtos.Proto2.TestAllTypes) foo_ : null; } + set { + foo_ = value; + fooCase_ = value == null ? FooOneofCase.None : FooOneofCase.FooMessage; + } + } + + /// Field number for the "foogroup" field. + public const int FooGroupFieldNumber = 4; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestOneof.Types.FooGroup FooGroup { + get { return HasFooGroup ? (global::Google.Protobuf.TestProtos.Proto2.TestOneof.Types.FooGroup) foo_ : null; } + set { + foo_ = value; + fooCase_ = value == null ? FooOneofCase.None : FooOneofCase.FooGroup; + } + } + /// Gets whether the "foogroup" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFooGroup { + get { return fooCase_ == FooOneofCase.FooGroup; } + } + /// Clears the value of the oneof if it's currently set to "foogroup" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFooGroup() { + if (HasFooGroup) { + ClearFoo(); + } + } + + private object foo_; + /// Enum of possible cases for the "foo" oneof. + public enum FooOneofCase { + None = 0, + FooInt = 1, + FooString = 2, + FooMessage = 3, + FooGroup = 4, + } + private FooOneofCase fooCase_ = FooOneofCase.None; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooOneofCase FooCase { + get { return fooCase_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFoo() { + fooCase_ = FooOneofCase.None; + foo_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestOneof); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestOneof other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (FooInt != other.FooInt) return false; + if (FooString != other.FooString) return false; + if (!object.Equals(FooMessage, other.FooMessage)) return false; + if (!object.Equals(FooGroup, other.FooGroup)) return false; + if (FooCase != other.FooCase) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasFooInt) hash ^= FooInt.GetHashCode(); + if (HasFooString) hash ^= FooString.GetHashCode(); + if (fooCase_ == FooOneofCase.FooMessage) hash ^= FooMessage.GetHashCode(); + if (HasFooGroup) hash ^= FooGroup.GetHashCode(); + hash ^= (int) fooCase_; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasFooInt) { + output.WriteRawTag(8); + output.WriteInt32(FooInt); + } + if (HasFooString) { + output.WriteRawTag(18); + output.WriteString(FooString); + } + if (fooCase_ == FooOneofCase.FooMessage) { + output.WriteRawTag(26); + output.WriteMessage(FooMessage); + } + if (HasFooGroup) { + output.WriteRawTag(35); + output.WriteGroup(FooGroup); + output.WriteRawTag(36); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasFooInt) { + output.WriteRawTag(8); + output.WriteInt32(FooInt); + } + if (HasFooString) { + output.WriteRawTag(18); + output.WriteString(FooString); + } + if (fooCase_ == FooOneofCase.FooMessage) { + output.WriteRawTag(26); + output.WriteMessage(FooMessage); + } + if (HasFooGroup) { + output.WriteRawTag(35); + output.WriteGroup(FooGroup); + output.WriteRawTag(36); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasFooInt) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(FooInt); + } + if (HasFooString) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(FooString); + } + if (fooCase_ == FooOneofCase.FooMessage) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(FooMessage); + } + if (HasFooGroup) { + size += 2 + pb::CodedOutputStream.ComputeGroupSize(FooGroup); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestOneof other) { + if (other == null) { + return; + } + switch (other.FooCase) { + case FooOneofCase.FooInt: + FooInt = other.FooInt; + break; + case FooOneofCase.FooString: + FooString = other.FooString; + break; + case FooOneofCase.FooMessage: + if (FooMessage == null) { + FooMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + FooMessage.MergeFrom(other.FooMessage); + break; + case FooOneofCase.FooGroup: + if (FooGroup == null) { + FooGroup = new global::Google.Protobuf.TestProtos.Proto2.TestOneof.Types.FooGroup(); + } + FooGroup.MergeFrom(other.FooGroup); + break; + } + + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + FooInt = input.ReadInt32(); + break; + } + case 18: { + FooString = input.ReadString(); + break; + } + case 26: { + global::Google.Protobuf.TestProtos.Proto2.TestAllTypes subBuilder = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + if (fooCase_ == FooOneofCase.FooMessage) { + subBuilder.MergeFrom(FooMessage); + } + input.ReadMessage(subBuilder); + FooMessage = subBuilder; + break; + } + case 35: { + global::Google.Protobuf.TestProtos.Proto2.TestOneof.Types.FooGroup subBuilder = new global::Google.Protobuf.TestProtos.Proto2.TestOneof.Types.FooGroup(); + if (HasFooGroup) { + subBuilder.MergeFrom(FooGroup); + } + input.ReadGroup(subBuilder); + FooGroup = subBuilder; + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + FooInt = input.ReadInt32(); + break; + } + case 18: { + FooString = input.ReadString(); + break; + } + case 26: { + global::Google.Protobuf.TestProtos.Proto2.TestAllTypes subBuilder = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + if (fooCase_ == FooOneofCase.FooMessage) { + subBuilder.MergeFrom(FooMessage); + } + input.ReadMessage(subBuilder); + FooMessage = subBuilder; + break; + } + case 35: { + global::Google.Protobuf.TestProtos.Proto2.TestOneof.Types.FooGroup subBuilder = new global::Google.Protobuf.TestProtos.Proto2.TestOneof.Types.FooGroup(); + if (HasFooGroup) { + subBuilder.MergeFrom(FooGroup); + } + input.ReadGroup(subBuilder); + FooGroup = subBuilder; + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the TestOneof message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public sealed partial class FooGroup : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new FooGroup()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestOneof.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooGroup() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooGroup(FooGroup other) : this() { + _hasBits0 = other._hasBits0; + a_ = other.a_; + b_ = other.b_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooGroup Clone() { + return new FooGroup(this); + } + + /// Field number for the "a" field. + public const int AFieldNumber = 5; + private readonly static int ADefaultValue = 0; + + private int a_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int A { + get { if ((_hasBits0 & 1) != 0) { return a_; } else { return ADefaultValue; } } + set { + _hasBits0 |= 1; + a_ = value; + } + } + /// Gets whether the "a" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasA { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "a" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearA() { + _hasBits0 &= ~1; + } + + /// Field number for the "b" field. + public const int BFieldNumber = 6; + private readonly static string BDefaultValue = ""; + + private string b_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string B { + get { return b_ ?? BDefaultValue; } + set { + b_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "b" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasB { + get { return b_ != null; } + } + /// Clears the value of the "b" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearB() { + b_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as FooGroup); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(FooGroup other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (A != other.A) return false; + if (B != other.B) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasA) hash ^= A.GetHashCode(); + if (HasB) hash ^= B.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasA) { + output.WriteRawTag(40); + output.WriteInt32(A); + } + if (HasB) { + output.WriteRawTag(50); + output.WriteString(B); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasA) { + output.WriteRawTag(40); + output.WriteInt32(A); + } + if (HasB) { + output.WriteRawTag(50); + output.WriteString(B); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasA) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(A); + } + if (HasB) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(B); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(FooGroup other) { + if (other == null) { + return; + } + if (other.HasA) { + A = other.A; + } + if (other.HasB) { + B = other.B; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 36: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 40: { + A = input.ReadInt32(); + break; + } + case 50: { + B = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 36: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 40: { + A = input.ReadInt32(); + break; + } + case 50: { + B = input.ReadString(); + break; + } + } + } + } + #endif + + } + + } + #endregion + + } + + public sealed partial class TestOneofBackwardsCompatible : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestOneofBackwardsCompatible()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[44]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestOneofBackwardsCompatible() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestOneofBackwardsCompatible(TestOneofBackwardsCompatible other) : this() { + _hasBits0 = other._hasBits0; + fooInt_ = other.fooInt_; + fooString_ = other.fooString_; + fooMessage_ = other.fooMessage_ != null ? other.fooMessage_.Clone() : null; + fooGroup_ = other.HasFooGroup ? other.fooGroup_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestOneofBackwardsCompatible Clone() { + return new TestOneofBackwardsCompatible(this); + } + + /// Field number for the "foo_int" field. + public const int FooIntFieldNumber = 1; + private readonly static int FooIntDefaultValue = 0; + + private int fooInt_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int FooInt { + get { if ((_hasBits0 & 1) != 0) { return fooInt_; } else { return FooIntDefaultValue; } } + set { + _hasBits0 |= 1; + fooInt_ = value; + } + } + /// Gets whether the "foo_int" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFooInt { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "foo_int" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFooInt() { + _hasBits0 &= ~1; + } + + /// Field number for the "foo_string" field. + public const int FooStringFieldNumber = 2; + private readonly static string FooStringDefaultValue = ""; + + private string fooString_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string FooString { + get { return fooString_ ?? FooStringDefaultValue; } + set { + fooString_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "foo_string" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFooString { + get { return fooString_ != null; } + } + /// Clears the value of the "foo_string" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFooString() { + fooString_ = null; + } + + /// Field number for the "foo_message" field. + public const int FooMessageFieldNumber = 3; + private global::Google.Protobuf.TestProtos.Proto2.TestAllTypes fooMessage_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestAllTypes FooMessage { + get { return fooMessage_; } + set { + fooMessage_ = value; + } + } + + /// Field number for the "foogroup" field. + public const int FooGroupFieldNumber = 4; + private global::Google.Protobuf.TestProtos.Proto2.TestOneofBackwardsCompatible.Types.FooGroup fooGroup_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestOneofBackwardsCompatible.Types.FooGroup FooGroup { + get { return fooGroup_; } + set { + fooGroup_ = value; + } + } + /// Gets whether the foogroup field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFooGroup { + get { return fooGroup_ != null; } + } + /// Clears the value of the foogroup field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFooGroup() { + fooGroup_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestOneofBackwardsCompatible); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestOneofBackwardsCompatible other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (FooInt != other.FooInt) return false; + if (FooString != other.FooString) return false; + if (!object.Equals(FooMessage, other.FooMessage)) return false; + if (!object.Equals(FooGroup, other.FooGroup)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasFooInt) hash ^= FooInt.GetHashCode(); + if (HasFooString) hash ^= FooString.GetHashCode(); + if (fooMessage_ != null) hash ^= FooMessage.GetHashCode(); + if (HasFooGroup) hash ^= FooGroup.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasFooInt) { + output.WriteRawTag(8); + output.WriteInt32(FooInt); + } + if (HasFooString) { + output.WriteRawTag(18); + output.WriteString(FooString); + } + if (fooMessage_ != null) { + output.WriteRawTag(26); + output.WriteMessage(FooMessage); + } + if (HasFooGroup) { + output.WriteRawTag(35); + output.WriteGroup(FooGroup); + output.WriteRawTag(36); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasFooInt) { + output.WriteRawTag(8); + output.WriteInt32(FooInt); + } + if (HasFooString) { + output.WriteRawTag(18); + output.WriteString(FooString); + } + if (fooMessage_ != null) { + output.WriteRawTag(26); + output.WriteMessage(FooMessage); + } + if (HasFooGroup) { + output.WriteRawTag(35); + output.WriteGroup(FooGroup); + output.WriteRawTag(36); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasFooInt) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(FooInt); + } + if (HasFooString) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(FooString); + } + if (fooMessage_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(FooMessage); + } + if (HasFooGroup) { + size += 2 + pb::CodedOutputStream.ComputeGroupSize(FooGroup); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestOneofBackwardsCompatible other) { + if (other == null) { + return; + } + if (other.HasFooInt) { + FooInt = other.FooInt; + } + if (other.HasFooString) { + FooString = other.FooString; + } + if (other.fooMessage_ != null) { + if (fooMessage_ == null) { + FooMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + FooMessage.MergeFrom(other.FooMessage); + } + if (other.HasFooGroup) { + if (!HasFooGroup) { + FooGroup = new global::Google.Protobuf.TestProtos.Proto2.TestOneofBackwardsCompatible.Types.FooGroup(); + } + FooGroup.MergeFrom(other.FooGroup); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + FooInt = input.ReadInt32(); + break; + } + case 18: { + FooString = input.ReadString(); + break; + } + case 26: { + if (fooMessage_ == null) { + FooMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + input.ReadMessage(FooMessage); + break; + } + case 35: { + if (!HasFooGroup) { + FooGroup = new global::Google.Protobuf.TestProtos.Proto2.TestOneofBackwardsCompatible.Types.FooGroup(); + } + input.ReadGroup(FooGroup); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + FooInt = input.ReadInt32(); + break; + } + case 18: { + FooString = input.ReadString(); + break; + } + case 26: { + if (fooMessage_ == null) { + FooMessage = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + input.ReadMessage(FooMessage); + break; + } + case 35: { + if (!HasFooGroup) { + FooGroup = new global::Google.Protobuf.TestProtos.Proto2.TestOneofBackwardsCompatible.Types.FooGroup(); + } + input.ReadGroup(FooGroup); + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the TestOneofBackwardsCompatible message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public sealed partial class FooGroup : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new FooGroup()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestOneofBackwardsCompatible.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooGroup() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooGroup(FooGroup other) : this() { + _hasBits0 = other._hasBits0; + a_ = other.a_; + b_ = other.b_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooGroup Clone() { + return new FooGroup(this); + } + + /// Field number for the "a" field. + public const int AFieldNumber = 5; + private readonly static int ADefaultValue = 0; + + private int a_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int A { + get { if ((_hasBits0 & 1) != 0) { return a_; } else { return ADefaultValue; } } + set { + _hasBits0 |= 1; + a_ = value; + } + } + /// Gets whether the "a" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasA { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "a" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearA() { + _hasBits0 &= ~1; + } + + /// Field number for the "b" field. + public const int BFieldNumber = 6; + private readonly static string BDefaultValue = ""; + + private string b_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string B { + get { return b_ ?? BDefaultValue; } + set { + b_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "b" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasB { + get { return b_ != null; } + } + /// Clears the value of the "b" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearB() { + b_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as FooGroup); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(FooGroup other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (A != other.A) return false; + if (B != other.B) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasA) hash ^= A.GetHashCode(); + if (HasB) hash ^= B.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasA) { + output.WriteRawTag(40); + output.WriteInt32(A); + } + if (HasB) { + output.WriteRawTag(50); + output.WriteString(B); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasA) { + output.WriteRawTag(40); + output.WriteInt32(A); + } + if (HasB) { + output.WriteRawTag(50); + output.WriteString(B); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasA) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(A); + } + if (HasB) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(B); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(FooGroup other) { + if (other == null) { + return; + } + if (other.HasA) { + A = other.A; + } + if (other.HasB) { + B = other.B; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 36: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 40: { + A = input.ReadInt32(); + break; + } + case 50: { + B = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 36: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 40: { + A = input.ReadInt32(); + break; + } + case 50: { + B = input.ReadString(); + break; + } + } + } + } + #endif + + } + + } + #endregion + + } + + public sealed partial class TestOneof2 : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestOneof2()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[45]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestOneof2() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestOneof2(TestOneof2 other) : this() { + _hasBits0 = other._hasBits0; + bazInt_ = other.bazInt_; + bazString_ = other.bazString_; + switch (other.FooCase) { + case FooOneofCase.FooInt: + FooInt = other.FooInt; + break; + case FooOneofCase.FooString: + FooString = other.FooString; + break; + case FooOneofCase.FooCord: + FooCord = other.FooCord; + break; + case FooOneofCase.FooStringPiece: + FooStringPiece = other.FooStringPiece; + break; + case FooOneofCase.FooBytes: + FooBytes = other.FooBytes; + break; + case FooOneofCase.FooEnum: + FooEnum = other.FooEnum; + break; + case FooOneofCase.FooMessage: + FooMessage = other.FooMessage.Clone(); + break; + case FooOneofCase.FooGroup: + FooGroup = other.FooGroup.Clone(); + break; + case FooOneofCase.FooLazyMessage: + FooLazyMessage = other.FooLazyMessage.Clone(); + break; + } + + switch (other.BarCase) { + case BarOneofCase.BarInt: + BarInt = other.BarInt; + break; + case BarOneofCase.BarString: + BarString = other.BarString; + break; + case BarOneofCase.BarCord: + BarCord = other.BarCord; + break; + case BarOneofCase.BarStringPiece: + BarStringPiece = other.BarStringPiece; + break; + case BarOneofCase.BarBytes: + BarBytes = other.BarBytes; + break; + case BarOneofCase.BarEnum: + BarEnum = other.BarEnum; + break; + } + + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestOneof2 Clone() { + return new TestOneof2(this); + } + + /// Field number for the "foo_int" field. + public const int FooIntFieldNumber = 1; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int FooInt { + get { return HasFooInt ? (int) foo_ : 0; } + set { + foo_ = value; + fooCase_ = FooOneofCase.FooInt; + } + } + /// Gets whether the "foo_int" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFooInt { + get { return fooCase_ == FooOneofCase.FooInt; } + } + /// Clears the value of the oneof if it's currently set to "foo_int" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFooInt() { + if (HasFooInt) { + ClearFoo(); + } + } + + /// Field number for the "foo_string" field. + public const int FooStringFieldNumber = 2; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string FooString { + get { return HasFooString ? (string) foo_ : ""; } + set { + foo_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + fooCase_ = FooOneofCase.FooString; + } + } + /// Gets whether the "foo_string" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFooString { + get { return fooCase_ == FooOneofCase.FooString; } + } + /// Clears the value of the oneof if it's currently set to "foo_string" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFooString() { + if (HasFooString) { + ClearFoo(); + } + } + + /// Field number for the "foo_cord" field. + public const int FooCordFieldNumber = 3; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string FooCord { + get { return HasFooCord ? (string) foo_ : ""; } + set { + foo_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + fooCase_ = FooOneofCase.FooCord; + } + } + /// Gets whether the "foo_cord" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFooCord { + get { return fooCase_ == FooOneofCase.FooCord; } + } + /// Clears the value of the oneof if it's currently set to "foo_cord" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFooCord() { + if (HasFooCord) { + ClearFoo(); + } + } + + /// Field number for the "foo_string_piece" field. + public const int FooStringPieceFieldNumber = 4; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string FooStringPiece { + get { return HasFooStringPiece ? (string) foo_ : ""; } + set { + foo_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + fooCase_ = FooOneofCase.FooStringPiece; + } + } + /// Gets whether the "foo_string_piece" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFooStringPiece { + get { return fooCase_ == FooOneofCase.FooStringPiece; } + } + /// Clears the value of the oneof if it's currently set to "foo_string_piece" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFooStringPiece() { + if (HasFooStringPiece) { + ClearFoo(); + } + } + + /// Field number for the "foo_bytes" field. + public const int FooBytesFieldNumber = 5; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pb::ByteString FooBytes { + get { return HasFooBytes ? (pb::ByteString) foo_ : pb::ByteString.Empty; } + set { + foo_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + fooCase_ = FooOneofCase.FooBytes; + } + } + /// Gets whether the "foo_bytes" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFooBytes { + get { return fooCase_ == FooOneofCase.FooBytes; } + } + /// Clears the value of the oneof if it's currently set to "foo_bytes" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFooBytes() { + if (HasFooBytes) { + ClearFoo(); + } + } + + /// Field number for the "foo_enum" field. + public const int FooEnumFieldNumber = 6; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedEnum FooEnum { + get { return HasFooEnum ? (global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedEnum) foo_ : global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedEnum.Foo; } + set { + foo_ = value; + fooCase_ = FooOneofCase.FooEnum; + } + } + /// Gets whether the "foo_enum" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFooEnum { + get { return fooCase_ == FooOneofCase.FooEnum; } + } + /// Clears the value of the oneof if it's currently set to "foo_enum" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFooEnum() { + if (HasFooEnum) { + ClearFoo(); + } + } + + /// Field number for the "foo_message" field. + public const int FooMessageFieldNumber = 7; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage FooMessage { + get { return fooCase_ == FooOneofCase.FooMessage ? (global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage) foo_ : null; } + set { + foo_ = value; + fooCase_ = value == null ? FooOneofCase.None : FooOneofCase.FooMessage; + } + } + + /// Field number for the "foogroup" field. + public const int FooGroupFieldNumber = 8; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.FooGroup FooGroup { + get { return HasFooGroup ? (global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.FooGroup) foo_ : null; } + set { + foo_ = value; + fooCase_ = value == null ? FooOneofCase.None : FooOneofCase.FooGroup; + } + } + /// Gets whether the "foogroup" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFooGroup { + get { return fooCase_ == FooOneofCase.FooGroup; } + } + /// Clears the value of the oneof if it's currently set to "foogroup" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFooGroup() { + if (HasFooGroup) { + ClearFoo(); + } + } + + /// Field number for the "foo_lazy_message" field. + public const int FooLazyMessageFieldNumber = 11; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage FooLazyMessage { + get { return fooCase_ == FooOneofCase.FooLazyMessage ? (global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage) foo_ : null; } + set { + foo_ = value; + fooCase_ = value == null ? FooOneofCase.None : FooOneofCase.FooLazyMessage; + } + } + + /// Field number for the "bar_int" field. + public const int BarIntFieldNumber = 12; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int BarInt { + get { return HasBarInt ? (int) bar_ : 5; } + set { + bar_ = value; + barCase_ = BarOneofCase.BarInt; + } + } + /// Gets whether the "bar_int" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasBarInt { + get { return barCase_ == BarOneofCase.BarInt; } + } + /// Clears the value of the oneof if it's currently set to "bar_int" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearBarInt() { + if (HasBarInt) { + ClearBar(); + } + } + + /// Field number for the "bar_string" field. + public const int BarStringFieldNumber = 13; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string BarString { + get { return HasBarString ? (string) bar_ : global::System.Text.Encoding.UTF8.GetString(global::System.Convert.FromBase64String("U1RSSU5H"), 0, 6); } + set { + bar_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + barCase_ = BarOneofCase.BarString; + } + } + /// Gets whether the "bar_string" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasBarString { + get { return barCase_ == BarOneofCase.BarString; } + } + /// Clears the value of the oneof if it's currently set to "bar_string" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearBarString() { + if (HasBarString) { + ClearBar(); + } + } + + /// Field number for the "bar_cord" field. + public const int BarCordFieldNumber = 14; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string BarCord { + get { return HasBarCord ? (string) bar_ : global::System.Text.Encoding.UTF8.GetString(global::System.Convert.FromBase64String("Q09SRA=="), 0, 4); } + set { + bar_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + barCase_ = BarOneofCase.BarCord; + } + } + /// Gets whether the "bar_cord" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasBarCord { + get { return barCase_ == BarOneofCase.BarCord; } + } + /// Clears the value of the oneof if it's currently set to "bar_cord" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearBarCord() { + if (HasBarCord) { + ClearBar(); + } + } + + /// Field number for the "bar_string_piece" field. + public const int BarStringPieceFieldNumber = 15; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string BarStringPiece { + get { return HasBarStringPiece ? (string) bar_ : global::System.Text.Encoding.UTF8.GetString(global::System.Convert.FromBase64String("U1BJRUNF"), 0, 6); } + set { + bar_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + barCase_ = BarOneofCase.BarStringPiece; + } + } + /// Gets whether the "bar_string_piece" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasBarStringPiece { + get { return barCase_ == BarOneofCase.BarStringPiece; } + } + /// Clears the value of the oneof if it's currently set to "bar_string_piece" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearBarStringPiece() { + if (HasBarStringPiece) { + ClearBar(); + } + } + + /// Field number for the "bar_bytes" field. + public const int BarBytesFieldNumber = 16; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pb::ByteString BarBytes { + get { return HasBarBytes ? (pb::ByteString) bar_ : pb::ByteString.FromBase64("QllURVM="); } + set { + bar_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + barCase_ = BarOneofCase.BarBytes; + } + } + /// Gets whether the "bar_bytes" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasBarBytes { + get { return barCase_ == BarOneofCase.BarBytes; } + } + /// Clears the value of the oneof if it's currently set to "bar_bytes" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearBarBytes() { + if (HasBarBytes) { + ClearBar(); + } + } + + /// Field number for the "bar_enum" field. + public const int BarEnumFieldNumber = 17; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedEnum BarEnum { + get { return HasBarEnum ? (global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedEnum) bar_ : global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedEnum.Bar; } + set { + bar_ = value; + barCase_ = BarOneofCase.BarEnum; + } + } + /// Gets whether the "bar_enum" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasBarEnum { + get { return barCase_ == BarOneofCase.BarEnum; } + } + /// Clears the value of the oneof if it's currently set to "bar_enum" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearBarEnum() { + if (HasBarEnum) { + ClearBar(); + } + } + + /// Field number for the "baz_int" field. + public const int BazIntFieldNumber = 18; + private readonly static int BazIntDefaultValue = 0; + + private int bazInt_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int BazInt { + get { if ((_hasBits0 & 1) != 0) { return bazInt_; } else { return BazIntDefaultValue; } } + set { + _hasBits0 |= 1; + bazInt_ = value; + } + } + /// Gets whether the "baz_int" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasBazInt { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "baz_int" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearBazInt() { + _hasBits0 &= ~1; + } + + /// Field number for the "baz_string" field. + public const int BazStringFieldNumber = 19; + private readonly static string BazStringDefaultValue = global::System.Text.Encoding.UTF8.GetString(global::System.Convert.FromBase64String("QkFa"), 0, 3); + + private string bazString_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string BazString { + get { return bazString_ ?? BazStringDefaultValue; } + set { + bazString_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "baz_string" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasBazString { + get { return bazString_ != null; } + } + /// Clears the value of the "baz_string" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearBazString() { + bazString_ = null; + } + + private object foo_; + /// Enum of possible cases for the "foo" oneof. + public enum FooOneofCase { + None = 0, + FooInt = 1, + FooString = 2, + FooCord = 3, + FooStringPiece = 4, + FooBytes = 5, + FooEnum = 6, + FooMessage = 7, + FooGroup = 8, + FooLazyMessage = 11, + } + private FooOneofCase fooCase_ = FooOneofCase.None; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooOneofCase FooCase { + get { return fooCase_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFoo() { + fooCase_ = FooOneofCase.None; + foo_ = null; + } + + private object bar_; + /// Enum of possible cases for the "bar" oneof. + public enum BarOneofCase { + None = 0, + BarInt = 12, + BarString = 13, + BarCord = 14, + BarStringPiece = 15, + BarBytes = 16, + BarEnum = 17, + } + private BarOneofCase barCase_ = BarOneofCase.None; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public BarOneofCase BarCase { + get { return barCase_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearBar() { + barCase_ = BarOneofCase.None; + bar_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestOneof2); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestOneof2 other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (FooInt != other.FooInt) return false; + if (FooString != other.FooString) return false; + if (FooCord != other.FooCord) return false; + if (FooStringPiece != other.FooStringPiece) return false; + if (FooBytes != other.FooBytes) return false; + if (FooEnum != other.FooEnum) return false; + if (!object.Equals(FooMessage, other.FooMessage)) return false; + if (!object.Equals(FooGroup, other.FooGroup)) return false; + if (!object.Equals(FooLazyMessage, other.FooLazyMessage)) return false; + if (BarInt != other.BarInt) return false; + if (BarString != other.BarString) return false; + if (BarCord != other.BarCord) return false; + if (BarStringPiece != other.BarStringPiece) return false; + if (BarBytes != other.BarBytes) return false; + if (BarEnum != other.BarEnum) return false; + if (BazInt != other.BazInt) return false; + if (BazString != other.BazString) return false; + if (FooCase != other.FooCase) return false; + if (BarCase != other.BarCase) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasFooInt) hash ^= FooInt.GetHashCode(); + if (HasFooString) hash ^= FooString.GetHashCode(); + if (HasFooCord) hash ^= FooCord.GetHashCode(); + if (HasFooStringPiece) hash ^= FooStringPiece.GetHashCode(); + if (HasFooBytes) hash ^= FooBytes.GetHashCode(); + if (HasFooEnum) hash ^= FooEnum.GetHashCode(); + if (fooCase_ == FooOneofCase.FooMessage) hash ^= FooMessage.GetHashCode(); + if (HasFooGroup) hash ^= FooGroup.GetHashCode(); + if (fooCase_ == FooOneofCase.FooLazyMessage) hash ^= FooLazyMessage.GetHashCode(); + if (HasBarInt) hash ^= BarInt.GetHashCode(); + if (HasBarString) hash ^= BarString.GetHashCode(); + if (HasBarCord) hash ^= BarCord.GetHashCode(); + if (HasBarStringPiece) hash ^= BarStringPiece.GetHashCode(); + if (HasBarBytes) hash ^= BarBytes.GetHashCode(); + if (HasBarEnum) hash ^= BarEnum.GetHashCode(); + if (HasBazInt) hash ^= BazInt.GetHashCode(); + if (HasBazString) hash ^= BazString.GetHashCode(); + hash ^= (int) fooCase_; + hash ^= (int) barCase_; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasFooInt) { + output.WriteRawTag(8); + output.WriteInt32(FooInt); + } + if (HasFooString) { + output.WriteRawTag(18); + output.WriteString(FooString); + } + if (HasFooCord) { + output.WriteRawTag(26); + output.WriteString(FooCord); + } + if (HasFooStringPiece) { + output.WriteRawTag(34); + output.WriteString(FooStringPiece); + } + if (HasFooBytes) { + output.WriteRawTag(42); + output.WriteBytes(FooBytes); + } + if (HasFooEnum) { + output.WriteRawTag(48); + output.WriteEnum((int) FooEnum); + } + if (fooCase_ == FooOneofCase.FooMessage) { + output.WriteRawTag(58); + output.WriteMessage(FooMessage); + } + if (HasFooGroup) { + output.WriteRawTag(67); + output.WriteGroup(FooGroup); + output.WriteRawTag(68); + } + if (fooCase_ == FooOneofCase.FooLazyMessage) { + output.WriteRawTag(90); + output.WriteMessage(FooLazyMessage); + } + if (HasBarInt) { + output.WriteRawTag(96); + output.WriteInt32(BarInt); + } + if (HasBarString) { + output.WriteRawTag(106); + output.WriteString(BarString); + } + if (HasBarCord) { + output.WriteRawTag(114); + output.WriteString(BarCord); + } + if (HasBarStringPiece) { + output.WriteRawTag(122); + output.WriteString(BarStringPiece); + } + if (HasBarBytes) { + output.WriteRawTag(130, 1); + output.WriteBytes(BarBytes); + } + if (HasBarEnum) { + output.WriteRawTag(136, 1); + output.WriteEnum((int) BarEnum); + } + if (HasBazInt) { + output.WriteRawTag(144, 1); + output.WriteInt32(BazInt); + } + if (HasBazString) { + output.WriteRawTag(154, 1); + output.WriteString(BazString); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasFooInt) { + output.WriteRawTag(8); + output.WriteInt32(FooInt); + } + if (HasFooString) { + output.WriteRawTag(18); + output.WriteString(FooString); + } + if (HasFooCord) { + output.WriteRawTag(26); + output.WriteString(FooCord); + } + if (HasFooStringPiece) { + output.WriteRawTag(34); + output.WriteString(FooStringPiece); + } + if (HasFooBytes) { + output.WriteRawTag(42); + output.WriteBytes(FooBytes); + } + if (HasFooEnum) { + output.WriteRawTag(48); + output.WriteEnum((int) FooEnum); + } + if (fooCase_ == FooOneofCase.FooMessage) { + output.WriteRawTag(58); + output.WriteMessage(FooMessage); + } + if (HasFooGroup) { + output.WriteRawTag(67); + output.WriteGroup(FooGroup); + output.WriteRawTag(68); + } + if (fooCase_ == FooOneofCase.FooLazyMessage) { + output.WriteRawTag(90); + output.WriteMessage(FooLazyMessage); + } + if (HasBarInt) { + output.WriteRawTag(96); + output.WriteInt32(BarInt); + } + if (HasBarString) { + output.WriteRawTag(106); + output.WriteString(BarString); + } + if (HasBarCord) { + output.WriteRawTag(114); + output.WriteString(BarCord); + } + if (HasBarStringPiece) { + output.WriteRawTag(122); + output.WriteString(BarStringPiece); + } + if (HasBarBytes) { + output.WriteRawTag(130, 1); + output.WriteBytes(BarBytes); + } + if (HasBarEnum) { + output.WriteRawTag(136, 1); + output.WriteEnum((int) BarEnum); + } + if (HasBazInt) { + output.WriteRawTag(144, 1); + output.WriteInt32(BazInt); + } + if (HasBazString) { + output.WriteRawTag(154, 1); + output.WriteString(BazString); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasFooInt) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(FooInt); + } + if (HasFooString) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(FooString); + } + if (HasFooCord) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(FooCord); + } + if (HasFooStringPiece) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(FooStringPiece); + } + if (HasFooBytes) { + size += 1 + pb::CodedOutputStream.ComputeBytesSize(FooBytes); + } + if (HasFooEnum) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) FooEnum); + } + if (fooCase_ == FooOneofCase.FooMessage) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(FooMessage); + } + if (HasFooGroup) { + size += 2 + pb::CodedOutputStream.ComputeGroupSize(FooGroup); + } + if (fooCase_ == FooOneofCase.FooLazyMessage) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(FooLazyMessage); + } + if (HasBarInt) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(BarInt); + } + if (HasBarString) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(BarString); + } + if (HasBarCord) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(BarCord); + } + if (HasBarStringPiece) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(BarStringPiece); + } + if (HasBarBytes) { + size += 2 + pb::CodedOutputStream.ComputeBytesSize(BarBytes); + } + if (HasBarEnum) { + size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) BarEnum); + } + if (HasBazInt) { + size += 2 + pb::CodedOutputStream.ComputeInt32Size(BazInt); + } + if (HasBazString) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(BazString); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestOneof2 other) { + if (other == null) { + return; + } + if (other.HasBazInt) { + BazInt = other.BazInt; + } + if (other.HasBazString) { + BazString = other.BazString; + } + switch (other.FooCase) { + case FooOneofCase.FooInt: + FooInt = other.FooInt; + break; + case FooOneofCase.FooString: + FooString = other.FooString; + break; + case FooOneofCase.FooCord: + FooCord = other.FooCord; + break; + case FooOneofCase.FooStringPiece: + FooStringPiece = other.FooStringPiece; + break; + case FooOneofCase.FooBytes: + FooBytes = other.FooBytes; + break; + case FooOneofCase.FooEnum: + FooEnum = other.FooEnum; + break; + case FooOneofCase.FooMessage: + if (FooMessage == null) { + FooMessage = new global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage(); + } + FooMessage.MergeFrom(other.FooMessage); + break; + case FooOneofCase.FooGroup: + if (FooGroup == null) { + FooGroup = new global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.FooGroup(); + } + FooGroup.MergeFrom(other.FooGroup); + break; + case FooOneofCase.FooLazyMessage: + if (FooLazyMessage == null) { + FooLazyMessage = new global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage(); + } + FooLazyMessage.MergeFrom(other.FooLazyMessage); + break; + } + + switch (other.BarCase) { + case BarOneofCase.BarInt: + BarInt = other.BarInt; + break; + case BarOneofCase.BarString: + BarString = other.BarString; + break; + case BarOneofCase.BarCord: + BarCord = other.BarCord; + break; + case BarOneofCase.BarStringPiece: + BarStringPiece = other.BarStringPiece; + break; + case BarOneofCase.BarBytes: + BarBytes = other.BarBytes; + break; + case BarOneofCase.BarEnum: + BarEnum = other.BarEnum; + break; + } + + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + FooInt = input.ReadInt32(); + break; + } + case 18: { + FooString = input.ReadString(); + break; + } + case 26: { + FooCord = input.ReadString(); + break; + } + case 34: { + FooStringPiece = input.ReadString(); + break; + } + case 42: { + FooBytes = input.ReadBytes(); + break; + } + case 48: { + foo_ = input.ReadEnum(); + fooCase_ = FooOneofCase.FooEnum; + break; + } + case 58: { + global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage subBuilder = new global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage(); + if (fooCase_ == FooOneofCase.FooMessage) { + subBuilder.MergeFrom(FooMessage); + } + input.ReadMessage(subBuilder); + FooMessage = subBuilder; + break; + } + case 67: { + global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.FooGroup subBuilder = new global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.FooGroup(); + if (HasFooGroup) { + subBuilder.MergeFrom(FooGroup); + } + input.ReadGroup(subBuilder); + FooGroup = subBuilder; + break; + } + case 90: { + global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage subBuilder = new global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage(); + if (fooCase_ == FooOneofCase.FooLazyMessage) { + subBuilder.MergeFrom(FooLazyMessage); + } + input.ReadMessage(subBuilder); + FooLazyMessage = subBuilder; + break; + } + case 96: { + BarInt = input.ReadInt32(); + break; + } + case 106: { + BarString = input.ReadString(); + break; + } + case 114: { + BarCord = input.ReadString(); + break; + } + case 122: { + BarStringPiece = input.ReadString(); + break; + } + case 130: { + BarBytes = input.ReadBytes(); + break; + } + case 136: { + bar_ = input.ReadEnum(); + barCase_ = BarOneofCase.BarEnum; + break; + } + case 144: { + BazInt = input.ReadInt32(); + break; + } + case 154: { + BazString = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + FooInt = input.ReadInt32(); + break; + } + case 18: { + FooString = input.ReadString(); + break; + } + case 26: { + FooCord = input.ReadString(); + break; + } + case 34: { + FooStringPiece = input.ReadString(); + break; + } + case 42: { + FooBytes = input.ReadBytes(); + break; + } + case 48: { + foo_ = input.ReadEnum(); + fooCase_ = FooOneofCase.FooEnum; + break; + } + case 58: { + global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage subBuilder = new global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage(); + if (fooCase_ == FooOneofCase.FooMessage) { + subBuilder.MergeFrom(FooMessage); + } + input.ReadMessage(subBuilder); + FooMessage = subBuilder; + break; + } + case 67: { + global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.FooGroup subBuilder = new global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.FooGroup(); + if (HasFooGroup) { + subBuilder.MergeFrom(FooGroup); + } + input.ReadGroup(subBuilder); + FooGroup = subBuilder; + break; + } + case 90: { + global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage subBuilder = new global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Types.NestedMessage(); + if (fooCase_ == FooOneofCase.FooLazyMessage) { + subBuilder.MergeFrom(FooLazyMessage); + } + input.ReadMessage(subBuilder); + FooLazyMessage = subBuilder; + break; + } + case 96: { + BarInt = input.ReadInt32(); + break; + } + case 106: { + BarString = input.ReadString(); + break; + } + case 114: { + BarCord = input.ReadString(); + break; + } + case 122: { + BarStringPiece = input.ReadString(); + break; + } + case 130: { + BarBytes = input.ReadBytes(); + break; + } + case 136: { + bar_ = input.ReadEnum(); + barCase_ = BarOneofCase.BarEnum; + break; + } + case 144: { + BazInt = input.ReadInt32(); + break; + } + case 154: { + BazString = input.ReadString(); + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the TestOneof2 message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public enum NestedEnum { + [pbr::OriginalName("FOO")] Foo = 1, + [pbr::OriginalName("BAR")] Bar = 2, + [pbr::OriginalName("BAZ")] Baz = 3, + } + + public sealed partial class FooGroup : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new FooGroup()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooGroup() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooGroup(FooGroup other) : this() { + _hasBits0 = other._hasBits0; + a_ = other.a_; + b_ = other.b_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooGroup Clone() { + return new FooGroup(this); + } + + /// Field number for the "a" field. + public const int AFieldNumber = 9; + private readonly static int ADefaultValue = 0; + + private int a_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int A { + get { if ((_hasBits0 & 1) != 0) { return a_; } else { return ADefaultValue; } } + set { + _hasBits0 |= 1; + a_ = value; + } + } + /// Gets whether the "a" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasA { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "a" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearA() { + _hasBits0 &= ~1; + } + + /// Field number for the "b" field. + public const int BFieldNumber = 10; + private readonly static string BDefaultValue = ""; + + private string b_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string B { + get { return b_ ?? BDefaultValue; } + set { + b_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "b" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasB { + get { return b_ != null; } + } + /// Clears the value of the "b" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearB() { + b_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as FooGroup); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(FooGroup other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (A != other.A) return false; + if (B != other.B) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasA) hash ^= A.GetHashCode(); + if (HasB) hash ^= B.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasA) { + output.WriteRawTag(72); + output.WriteInt32(A); + } + if (HasB) { + output.WriteRawTag(82); + output.WriteString(B); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasA) { + output.WriteRawTag(72); + output.WriteInt32(A); + } + if (HasB) { + output.WriteRawTag(82); + output.WriteString(B); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasA) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(A); + } + if (HasB) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(B); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(FooGroup other) { + if (other == null) { + return; + } + if (other.HasA) { + A = other.A; + } + if (other.HasB) { + B = other.B; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 68: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 72: { + A = input.ReadInt32(); + break; + } + case 82: { + B = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 68: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 72: { + A = input.ReadInt32(); + break; + } + case 82: { + B = input.ReadString(); + break; + } + } + } + } + #endif + + } + + public sealed partial class NestedMessage : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new NestedMessage()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestOneof2.Descriptor.NestedTypes[1]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedMessage(NestedMessage other) : this() { + _hasBits0 = other._hasBits0; + quxInt_ = other.quxInt_; + corgeInt_ = other.corgeInt_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedMessage Clone() { + return new NestedMessage(this); + } + + /// Field number for the "qux_int" field. + public const int QuxIntFieldNumber = 1; + private readonly static long QuxIntDefaultValue = 0L; + + private long quxInt_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public long QuxInt { + get { if ((_hasBits0 & 1) != 0) { return quxInt_; } else { return QuxIntDefaultValue; } } + set { + _hasBits0 |= 1; + quxInt_ = value; + } + } + /// Gets whether the "qux_int" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasQuxInt { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "qux_int" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearQuxInt() { + _hasBits0 &= ~1; + } + + /// Field number for the "corge_int" field. + public const int CorgeIntFieldNumber = 2; + private static readonly pb::FieldCodec _repeated_corgeInt_codec + = pb::FieldCodec.ForInt32(16); + private readonly pbc::RepeatedField corgeInt_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField CorgeInt { + get { return corgeInt_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as NestedMessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(NestedMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (QuxInt != other.QuxInt) return false; + if(!corgeInt_.Equals(other.corgeInt_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasQuxInt) hash ^= QuxInt.GetHashCode(); + hash ^= corgeInt_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasQuxInt) { + output.WriteRawTag(8); + output.WriteInt64(QuxInt); + } + corgeInt_.WriteTo(output, _repeated_corgeInt_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasQuxInt) { + output.WriteRawTag(8); + output.WriteInt64(QuxInt); + } + corgeInt_.WriteTo(ref output, _repeated_corgeInt_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasQuxInt) { + size += 1 + pb::CodedOutputStream.ComputeInt64Size(QuxInt); + } + size += corgeInt_.CalculateSize(_repeated_corgeInt_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(NestedMessage other) { + if (other == null) { + return; + } + if (other.HasQuxInt) { + QuxInt = other.QuxInt; + } + corgeInt_.Add(other.corgeInt_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + QuxInt = input.ReadInt64(); + break; + } + case 18: + case 16: { + corgeInt_.AddEntriesFrom(input, _repeated_corgeInt_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + QuxInt = input.ReadInt64(); + break; + } + case 18: + case 16: { + corgeInt_.AddEntriesFrom(ref input, _repeated_corgeInt_codec); + break; + } + } + } + } + #endif + + } + + } + #endregion + + } + + public sealed partial class TestRequiredOneof : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestRequiredOneof()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[46]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestRequiredOneof() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestRequiredOneof(TestRequiredOneof other) : this() { + switch (other.FooCase) { + case FooOneofCase.FooInt: + FooInt = other.FooInt; + break; + case FooOneofCase.FooString: + FooString = other.FooString; + break; + case FooOneofCase.FooMessage: + FooMessage = other.FooMessage.Clone(); + break; + } + + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestRequiredOneof Clone() { + return new TestRequiredOneof(this); + } + + /// Field number for the "foo_int" field. + public const int FooIntFieldNumber = 1; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int FooInt { + get { return HasFooInt ? (int) foo_ : 0; } + set { + foo_ = value; + fooCase_ = FooOneofCase.FooInt; + } + } + /// Gets whether the "foo_int" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFooInt { + get { return fooCase_ == FooOneofCase.FooInt; } + } + /// Clears the value of the oneof if it's currently set to "foo_int" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFooInt() { + if (HasFooInt) { + ClearFoo(); + } + } + + /// Field number for the "foo_string" field. + public const int FooStringFieldNumber = 2; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string FooString { + get { return HasFooString ? (string) foo_ : ""; } + set { + foo_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + fooCase_ = FooOneofCase.FooString; + } + } + /// Gets whether the "foo_string" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFooString { + get { return fooCase_ == FooOneofCase.FooString; } + } + /// Clears the value of the oneof if it's currently set to "foo_string" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFooString() { + if (HasFooString) { + ClearFoo(); + } + } + + /// Field number for the "foo_message" field. + public const int FooMessageFieldNumber = 3; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestRequiredOneof.Types.NestedMessage FooMessage { + get { return fooCase_ == FooOneofCase.FooMessage ? (global::Google.Protobuf.TestProtos.Proto2.TestRequiredOneof.Types.NestedMessage) foo_ : null; } + set { + foo_ = value; + fooCase_ = value == null ? FooOneofCase.None : FooOneofCase.FooMessage; + } + } + + private object foo_; + /// Enum of possible cases for the "foo" oneof. + public enum FooOneofCase { + None = 0, + FooInt = 1, + FooString = 2, + FooMessage = 3, + } + private FooOneofCase fooCase_ = FooOneofCase.None; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooOneofCase FooCase { + get { return fooCase_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFoo() { + fooCase_ = FooOneofCase.None; + foo_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestRequiredOneof); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestRequiredOneof other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (FooInt != other.FooInt) return false; + if (FooString != other.FooString) return false; + if (!object.Equals(FooMessage, other.FooMessage)) return false; + if (FooCase != other.FooCase) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasFooInt) hash ^= FooInt.GetHashCode(); + if (HasFooString) hash ^= FooString.GetHashCode(); + if (fooCase_ == FooOneofCase.FooMessage) hash ^= FooMessage.GetHashCode(); + hash ^= (int) fooCase_; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasFooInt) { + output.WriteRawTag(8); + output.WriteInt32(FooInt); + } + if (HasFooString) { + output.WriteRawTag(18); + output.WriteString(FooString); + } + if (fooCase_ == FooOneofCase.FooMessage) { + output.WriteRawTag(26); + output.WriteMessage(FooMessage); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasFooInt) { + output.WriteRawTag(8); + output.WriteInt32(FooInt); + } + if (HasFooString) { + output.WriteRawTag(18); + output.WriteString(FooString); + } + if (fooCase_ == FooOneofCase.FooMessage) { + output.WriteRawTag(26); + output.WriteMessage(FooMessage); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasFooInt) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(FooInt); + } + if (HasFooString) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(FooString); + } + if (fooCase_ == FooOneofCase.FooMessage) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(FooMessage); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestRequiredOneof other) { + if (other == null) { + return; + } + switch (other.FooCase) { + case FooOneofCase.FooInt: + FooInt = other.FooInt; + break; + case FooOneofCase.FooString: + FooString = other.FooString; + break; + case FooOneofCase.FooMessage: + if (FooMessage == null) { + FooMessage = new global::Google.Protobuf.TestProtos.Proto2.TestRequiredOneof.Types.NestedMessage(); + } + FooMessage.MergeFrom(other.FooMessage); + break; + } + + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + FooInt = input.ReadInt32(); + break; + } + case 18: { + FooString = input.ReadString(); + break; + } + case 26: { + global::Google.Protobuf.TestProtos.Proto2.TestRequiredOneof.Types.NestedMessage subBuilder = new global::Google.Protobuf.TestProtos.Proto2.TestRequiredOneof.Types.NestedMessage(); + if (fooCase_ == FooOneofCase.FooMessage) { + subBuilder.MergeFrom(FooMessage); + } + input.ReadMessage(subBuilder); + FooMessage = subBuilder; + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + FooInt = input.ReadInt32(); + break; + } + case 18: { + FooString = input.ReadString(); + break; + } + case 26: { + global::Google.Protobuf.TestProtos.Proto2.TestRequiredOneof.Types.NestedMessage subBuilder = new global::Google.Protobuf.TestProtos.Proto2.TestRequiredOneof.Types.NestedMessage(); + if (fooCase_ == FooOneofCase.FooMessage) { + subBuilder.MergeFrom(FooMessage); + } + input.ReadMessage(subBuilder); + FooMessage = subBuilder; + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the TestRequiredOneof message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public sealed partial class NestedMessage : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new NestedMessage()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestRequiredOneof.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedMessage(NestedMessage other) : this() { + _hasBits0 = other._hasBits0; + requiredDouble_ = other.requiredDouble_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedMessage Clone() { + return new NestedMessage(this); + } + + /// Field number for the "required_double" field. + public const int RequiredDoubleFieldNumber = 1; + private readonly static double RequiredDoubleDefaultValue = 0D; + + private double requiredDouble_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public double RequiredDouble { + get { if ((_hasBits0 & 1) != 0) { return requiredDouble_; } else { return RequiredDoubleDefaultValue; } } + set { + _hasBits0 |= 1; + requiredDouble_ = value; + } + } + /// Gets whether the "required_double" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasRequiredDouble { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "required_double" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearRequiredDouble() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as NestedMessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(NestedMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.Equals(RequiredDouble, other.RequiredDouble)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasRequiredDouble) hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(RequiredDouble); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasRequiredDouble) { + output.WriteRawTag(9); + output.WriteDouble(RequiredDouble); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasRequiredDouble) { + output.WriteRawTag(9); + output.WriteDouble(RequiredDouble); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasRequiredDouble) { + size += 1 + 8; + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(NestedMessage other) { + if (other == null) { + return; + } + if (other.HasRequiredDouble) { + RequiredDouble = other.RequiredDouble; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 9: { + RequiredDouble = input.ReadDouble(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 9: { + RequiredDouble = input.ReadDouble(); + break; + } + } + } + } + #endif + + } + + } + #endregion + + } + + public sealed partial class TestRequiredMap : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestRequiredMap()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[47]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestRequiredMap() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestRequiredMap(TestRequiredMap other) : this() { + foo_ = other.foo_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestRequiredMap Clone() { + return new TestRequiredMap(this); + } + + /// Field number for the "foo" field. + public const int FooFieldNumber = 1; + private static readonly pbc::MapField.Codec _map_foo_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForInt32(8, 0), pb::FieldCodec.ForMessage(18, global::Google.Protobuf.TestProtos.Proto2.TestRequiredMap.Types.NestedMessage.Parser), 10); + private readonly pbc::MapField foo_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField Foo { + get { return foo_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestRequiredMap); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestRequiredMap other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!Foo.Equals(other.Foo)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + hash ^= Foo.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + foo_.WriteTo(output, _map_foo_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + foo_.WriteTo(ref output, _map_foo_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + size += foo_.CalculateSize(_map_foo_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestRequiredMap other) { + if (other == null) { + return; + } + foo_.Add(other.foo_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + foo_.AddEntriesFrom(input, _map_foo_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + foo_.AddEntriesFrom(ref input, _map_foo_codec); + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the TestRequiredMap message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public sealed partial class NestedMessage : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new NestedMessage()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestRequiredMap.Descriptor.NestedTypes[1]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedMessage(NestedMessage other) : this() { + _hasBits0 = other._hasBits0; + requiredInt32_ = other.requiredInt32_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedMessage Clone() { + return new NestedMessage(this); + } + + /// Field number for the "required_int32" field. + public const int RequiredInt32FieldNumber = 1; + private readonly static int RequiredInt32DefaultValue = 0; + + private int requiredInt32_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int RequiredInt32 { + get { if ((_hasBits0 & 1) != 0) { return requiredInt32_; } else { return RequiredInt32DefaultValue; } } + set { + _hasBits0 |= 1; + requiredInt32_ = value; + } + } + /// Gets whether the "required_int32" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasRequiredInt32 { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "required_int32" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearRequiredInt32() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as NestedMessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(NestedMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (RequiredInt32 != other.RequiredInt32) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasRequiredInt32) hash ^= RequiredInt32.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasRequiredInt32) { + output.WriteRawTag(8); + output.WriteInt32(RequiredInt32); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasRequiredInt32) { + output.WriteRawTag(8); + output.WriteInt32(RequiredInt32); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasRequiredInt32) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(RequiredInt32); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(NestedMessage other) { + if (other == null) { + return; + } + if (other.HasRequiredInt32) { + RequiredInt32 = other.RequiredInt32; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + RequiredInt32 = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + RequiredInt32 = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + } + #endregion + + } + + public sealed partial class TestPackedTypes : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestPackedTypes()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[48]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestPackedTypes() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestPackedTypes(TestPackedTypes other) : this() { + packedInt32_ = other.packedInt32_.Clone(); + packedInt64_ = other.packedInt64_.Clone(); + packedUint32_ = other.packedUint32_.Clone(); + packedUint64_ = other.packedUint64_.Clone(); + packedSint32_ = other.packedSint32_.Clone(); + packedSint64_ = other.packedSint64_.Clone(); + packedFixed32_ = other.packedFixed32_.Clone(); + packedFixed64_ = other.packedFixed64_.Clone(); + packedSfixed32_ = other.packedSfixed32_.Clone(); + packedSfixed64_ = other.packedSfixed64_.Clone(); + packedFloat_ = other.packedFloat_.Clone(); + packedDouble_ = other.packedDouble_.Clone(); + packedBool_ = other.packedBool_.Clone(); + packedEnum_ = other.packedEnum_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestPackedTypes Clone() { + return new TestPackedTypes(this); + } + + /// Field number for the "packed_int32" field. + public const int PackedInt32FieldNumber = 90; + private static readonly pb::FieldCodec _repeated_packedInt32_codec + = pb::FieldCodec.ForInt32(722); + private readonly pbc::RepeatedField packedInt32_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField PackedInt32 { + get { return packedInt32_; } + } + + /// Field number for the "packed_int64" field. + public const int PackedInt64FieldNumber = 91; + private static readonly pb::FieldCodec _repeated_packedInt64_codec + = pb::FieldCodec.ForInt64(730); + private readonly pbc::RepeatedField packedInt64_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField PackedInt64 { + get { return packedInt64_; } + } + + /// Field number for the "packed_uint32" field. + public const int PackedUint32FieldNumber = 92; + private static readonly pb::FieldCodec _repeated_packedUint32_codec + = pb::FieldCodec.ForUInt32(738); + private readonly pbc::RepeatedField packedUint32_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField PackedUint32 { + get { return packedUint32_; } + } + + /// Field number for the "packed_uint64" field. + public const int PackedUint64FieldNumber = 93; + private static readonly pb::FieldCodec _repeated_packedUint64_codec + = pb::FieldCodec.ForUInt64(746); + private readonly pbc::RepeatedField packedUint64_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField PackedUint64 { + get { return packedUint64_; } + } + + /// Field number for the "packed_sint32" field. + public const int PackedSint32FieldNumber = 94; + private static readonly pb::FieldCodec _repeated_packedSint32_codec + = pb::FieldCodec.ForSInt32(754); + private readonly pbc::RepeatedField packedSint32_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField PackedSint32 { + get { return packedSint32_; } + } + + /// Field number for the "packed_sint64" field. + public const int PackedSint64FieldNumber = 95; + private static readonly pb::FieldCodec _repeated_packedSint64_codec + = pb::FieldCodec.ForSInt64(762); + private readonly pbc::RepeatedField packedSint64_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField PackedSint64 { + get { return packedSint64_; } + } + + /// Field number for the "packed_fixed32" field. + public const int PackedFixed32FieldNumber = 96; + private static readonly pb::FieldCodec _repeated_packedFixed32_codec + = pb::FieldCodec.ForFixed32(770); + private readonly pbc::RepeatedField packedFixed32_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField PackedFixed32 { + get { return packedFixed32_; } + } + + /// Field number for the "packed_fixed64" field. + public const int PackedFixed64FieldNumber = 97; + private static readonly pb::FieldCodec _repeated_packedFixed64_codec + = pb::FieldCodec.ForFixed64(778); + private readonly pbc::RepeatedField packedFixed64_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField PackedFixed64 { + get { return packedFixed64_; } + } + + /// Field number for the "packed_sfixed32" field. + public const int PackedSfixed32FieldNumber = 98; + private static readonly pb::FieldCodec _repeated_packedSfixed32_codec + = pb::FieldCodec.ForSFixed32(786); + private readonly pbc::RepeatedField packedSfixed32_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField PackedSfixed32 { + get { return packedSfixed32_; } + } + + /// Field number for the "packed_sfixed64" field. + public const int PackedSfixed64FieldNumber = 99; + private static readonly pb::FieldCodec _repeated_packedSfixed64_codec + = pb::FieldCodec.ForSFixed64(794); + private readonly pbc::RepeatedField packedSfixed64_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField PackedSfixed64 { + get { return packedSfixed64_; } + } + + /// Field number for the "packed_float" field. + public const int PackedFloatFieldNumber = 100; + private static readonly pb::FieldCodec _repeated_packedFloat_codec + = pb::FieldCodec.ForFloat(802); + private readonly pbc::RepeatedField packedFloat_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField PackedFloat { + get { return packedFloat_; } + } + + /// Field number for the "packed_double" field. + public const int PackedDoubleFieldNumber = 101; + private static readonly pb::FieldCodec _repeated_packedDouble_codec + = pb::FieldCodec.ForDouble(810); + private readonly pbc::RepeatedField packedDouble_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField PackedDouble { + get { return packedDouble_; } + } + + /// Field number for the "packed_bool" field. + public const int PackedBoolFieldNumber = 102; + private static readonly pb::FieldCodec _repeated_packedBool_codec + = pb::FieldCodec.ForBool(818); + private readonly pbc::RepeatedField packedBool_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField PackedBool { + get { return packedBool_; } + } + + /// Field number for the "packed_enum" field. + public const int PackedEnumFieldNumber = 103; + private static readonly pb::FieldCodec _repeated_packedEnum_codec + = pb::FieldCodec.ForEnum(826, x => (int) x, x => (global::Google.Protobuf.TestProtos.Proto2.ForeignEnum) x); + private readonly pbc::RepeatedField packedEnum_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField PackedEnum { + get { return packedEnum_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestPackedTypes); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestPackedTypes other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!packedInt32_.Equals(other.packedInt32_)) return false; + if(!packedInt64_.Equals(other.packedInt64_)) return false; + if(!packedUint32_.Equals(other.packedUint32_)) return false; + if(!packedUint64_.Equals(other.packedUint64_)) return false; + if(!packedSint32_.Equals(other.packedSint32_)) return false; + if(!packedSint64_.Equals(other.packedSint64_)) return false; + if(!packedFixed32_.Equals(other.packedFixed32_)) return false; + if(!packedFixed64_.Equals(other.packedFixed64_)) return false; + if(!packedSfixed32_.Equals(other.packedSfixed32_)) return false; + if(!packedSfixed64_.Equals(other.packedSfixed64_)) return false; + if(!packedFloat_.Equals(other.packedFloat_)) return false; + if(!packedDouble_.Equals(other.packedDouble_)) return false; + if(!packedBool_.Equals(other.packedBool_)) return false; + if(!packedEnum_.Equals(other.packedEnum_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + hash ^= packedInt32_.GetHashCode(); + hash ^= packedInt64_.GetHashCode(); + hash ^= packedUint32_.GetHashCode(); + hash ^= packedUint64_.GetHashCode(); + hash ^= packedSint32_.GetHashCode(); + hash ^= packedSint64_.GetHashCode(); + hash ^= packedFixed32_.GetHashCode(); + hash ^= packedFixed64_.GetHashCode(); + hash ^= packedSfixed32_.GetHashCode(); + hash ^= packedSfixed64_.GetHashCode(); + hash ^= packedFloat_.GetHashCode(); + hash ^= packedDouble_.GetHashCode(); + hash ^= packedBool_.GetHashCode(); + hash ^= packedEnum_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + packedInt32_.WriteTo(output, _repeated_packedInt32_codec); + packedInt64_.WriteTo(output, _repeated_packedInt64_codec); + packedUint32_.WriteTo(output, _repeated_packedUint32_codec); + packedUint64_.WriteTo(output, _repeated_packedUint64_codec); + packedSint32_.WriteTo(output, _repeated_packedSint32_codec); + packedSint64_.WriteTo(output, _repeated_packedSint64_codec); + packedFixed32_.WriteTo(output, _repeated_packedFixed32_codec); + packedFixed64_.WriteTo(output, _repeated_packedFixed64_codec); + packedSfixed32_.WriteTo(output, _repeated_packedSfixed32_codec); + packedSfixed64_.WriteTo(output, _repeated_packedSfixed64_codec); + packedFloat_.WriteTo(output, _repeated_packedFloat_codec); + packedDouble_.WriteTo(output, _repeated_packedDouble_codec); + packedBool_.WriteTo(output, _repeated_packedBool_codec); + packedEnum_.WriteTo(output, _repeated_packedEnum_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + packedInt32_.WriteTo(ref output, _repeated_packedInt32_codec); + packedInt64_.WriteTo(ref output, _repeated_packedInt64_codec); + packedUint32_.WriteTo(ref output, _repeated_packedUint32_codec); + packedUint64_.WriteTo(ref output, _repeated_packedUint64_codec); + packedSint32_.WriteTo(ref output, _repeated_packedSint32_codec); + packedSint64_.WriteTo(ref output, _repeated_packedSint64_codec); + packedFixed32_.WriteTo(ref output, _repeated_packedFixed32_codec); + packedFixed64_.WriteTo(ref output, _repeated_packedFixed64_codec); + packedSfixed32_.WriteTo(ref output, _repeated_packedSfixed32_codec); + packedSfixed64_.WriteTo(ref output, _repeated_packedSfixed64_codec); + packedFloat_.WriteTo(ref output, _repeated_packedFloat_codec); + packedDouble_.WriteTo(ref output, _repeated_packedDouble_codec); + packedBool_.WriteTo(ref output, _repeated_packedBool_codec); + packedEnum_.WriteTo(ref output, _repeated_packedEnum_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + size += packedInt32_.CalculateSize(_repeated_packedInt32_codec); + size += packedInt64_.CalculateSize(_repeated_packedInt64_codec); + size += packedUint32_.CalculateSize(_repeated_packedUint32_codec); + size += packedUint64_.CalculateSize(_repeated_packedUint64_codec); + size += packedSint32_.CalculateSize(_repeated_packedSint32_codec); + size += packedSint64_.CalculateSize(_repeated_packedSint64_codec); + size += packedFixed32_.CalculateSize(_repeated_packedFixed32_codec); + size += packedFixed64_.CalculateSize(_repeated_packedFixed64_codec); + size += packedSfixed32_.CalculateSize(_repeated_packedSfixed32_codec); + size += packedSfixed64_.CalculateSize(_repeated_packedSfixed64_codec); + size += packedFloat_.CalculateSize(_repeated_packedFloat_codec); + size += packedDouble_.CalculateSize(_repeated_packedDouble_codec); + size += packedBool_.CalculateSize(_repeated_packedBool_codec); + size += packedEnum_.CalculateSize(_repeated_packedEnum_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestPackedTypes other) { + if (other == null) { + return; + } + packedInt32_.Add(other.packedInt32_); + packedInt64_.Add(other.packedInt64_); + packedUint32_.Add(other.packedUint32_); + packedUint64_.Add(other.packedUint64_); + packedSint32_.Add(other.packedSint32_); + packedSint64_.Add(other.packedSint64_); + packedFixed32_.Add(other.packedFixed32_); + packedFixed64_.Add(other.packedFixed64_); + packedSfixed32_.Add(other.packedSfixed32_); + packedSfixed64_.Add(other.packedSfixed64_); + packedFloat_.Add(other.packedFloat_); + packedDouble_.Add(other.packedDouble_); + packedBool_.Add(other.packedBool_); + packedEnum_.Add(other.packedEnum_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 722: + case 720: { + packedInt32_.AddEntriesFrom(input, _repeated_packedInt32_codec); + break; + } + case 730: + case 728: { + packedInt64_.AddEntriesFrom(input, _repeated_packedInt64_codec); + break; + } + case 738: + case 736: { + packedUint32_.AddEntriesFrom(input, _repeated_packedUint32_codec); + break; + } + case 746: + case 744: { + packedUint64_.AddEntriesFrom(input, _repeated_packedUint64_codec); + break; + } + case 754: + case 752: { + packedSint32_.AddEntriesFrom(input, _repeated_packedSint32_codec); + break; + } + case 762: + case 760: { + packedSint64_.AddEntriesFrom(input, _repeated_packedSint64_codec); + break; + } + case 770: + case 773: { + packedFixed32_.AddEntriesFrom(input, _repeated_packedFixed32_codec); + break; + } + case 778: + case 777: { + packedFixed64_.AddEntriesFrom(input, _repeated_packedFixed64_codec); + break; + } + case 786: + case 789: { + packedSfixed32_.AddEntriesFrom(input, _repeated_packedSfixed32_codec); + break; + } + case 794: + case 793: { + packedSfixed64_.AddEntriesFrom(input, _repeated_packedSfixed64_codec); + break; + } + case 802: + case 805: { + packedFloat_.AddEntriesFrom(input, _repeated_packedFloat_codec); + break; + } + case 810: + case 809: { + packedDouble_.AddEntriesFrom(input, _repeated_packedDouble_codec); + break; + } + case 818: + case 816: { + packedBool_.AddEntriesFrom(input, _repeated_packedBool_codec); + break; + } + case 826: + case 824: { + packedEnum_.AddEntriesFrom(input, _repeated_packedEnum_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 722: + case 720: { + packedInt32_.AddEntriesFrom(ref input, _repeated_packedInt32_codec); + break; + } + case 730: + case 728: { + packedInt64_.AddEntriesFrom(ref input, _repeated_packedInt64_codec); + break; + } + case 738: + case 736: { + packedUint32_.AddEntriesFrom(ref input, _repeated_packedUint32_codec); + break; + } + case 746: + case 744: { + packedUint64_.AddEntriesFrom(ref input, _repeated_packedUint64_codec); + break; + } + case 754: + case 752: { + packedSint32_.AddEntriesFrom(ref input, _repeated_packedSint32_codec); + break; + } + case 762: + case 760: { + packedSint64_.AddEntriesFrom(ref input, _repeated_packedSint64_codec); + break; + } + case 770: + case 773: { + packedFixed32_.AddEntriesFrom(ref input, _repeated_packedFixed32_codec); + break; + } + case 778: + case 777: { + packedFixed64_.AddEntriesFrom(ref input, _repeated_packedFixed64_codec); + break; + } + case 786: + case 789: { + packedSfixed32_.AddEntriesFrom(ref input, _repeated_packedSfixed32_codec); + break; + } + case 794: + case 793: { + packedSfixed64_.AddEntriesFrom(ref input, _repeated_packedSfixed64_codec); + break; + } + case 802: + case 805: { + packedFloat_.AddEntriesFrom(ref input, _repeated_packedFloat_codec); + break; + } + case 810: + case 809: { + packedDouble_.AddEntriesFrom(ref input, _repeated_packedDouble_codec); + break; + } + case 818: + case 816: { + packedBool_.AddEntriesFrom(ref input, _repeated_packedBool_codec); + break; + } + case 826: + case 824: { + packedEnum_.AddEntriesFrom(ref input, _repeated_packedEnum_codec); + break; + } + } + } + } + #endif + + } + + /// + /// A message with the same fields as TestPackedTypes, but without packing. Used + /// to test packed <-> unpacked wire compatibility. + /// + public sealed partial class TestUnpackedTypes : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestUnpackedTypes()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[49]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestUnpackedTypes() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestUnpackedTypes(TestUnpackedTypes other) : this() { + unpackedInt32_ = other.unpackedInt32_.Clone(); + unpackedInt64_ = other.unpackedInt64_.Clone(); + unpackedUint32_ = other.unpackedUint32_.Clone(); + unpackedUint64_ = other.unpackedUint64_.Clone(); + unpackedSint32_ = other.unpackedSint32_.Clone(); + unpackedSint64_ = other.unpackedSint64_.Clone(); + unpackedFixed32_ = other.unpackedFixed32_.Clone(); + unpackedFixed64_ = other.unpackedFixed64_.Clone(); + unpackedSfixed32_ = other.unpackedSfixed32_.Clone(); + unpackedSfixed64_ = other.unpackedSfixed64_.Clone(); + unpackedFloat_ = other.unpackedFloat_.Clone(); + unpackedDouble_ = other.unpackedDouble_.Clone(); + unpackedBool_ = other.unpackedBool_.Clone(); + unpackedEnum_ = other.unpackedEnum_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestUnpackedTypes Clone() { + return new TestUnpackedTypes(this); + } + + /// Field number for the "unpacked_int32" field. + public const int UnpackedInt32FieldNumber = 90; + private static readonly pb::FieldCodec _repeated_unpackedInt32_codec + = pb::FieldCodec.ForInt32(720); + private readonly pbc::RepeatedField unpackedInt32_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField UnpackedInt32 { + get { return unpackedInt32_; } + } + + /// Field number for the "unpacked_int64" field. + public const int UnpackedInt64FieldNumber = 91; + private static readonly pb::FieldCodec _repeated_unpackedInt64_codec + = pb::FieldCodec.ForInt64(728); + private readonly pbc::RepeatedField unpackedInt64_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField UnpackedInt64 { + get { return unpackedInt64_; } + } + + /// Field number for the "unpacked_uint32" field. + public const int UnpackedUint32FieldNumber = 92; + private static readonly pb::FieldCodec _repeated_unpackedUint32_codec + = pb::FieldCodec.ForUInt32(736); + private readonly pbc::RepeatedField unpackedUint32_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField UnpackedUint32 { + get { return unpackedUint32_; } + } + + /// Field number for the "unpacked_uint64" field. + public const int UnpackedUint64FieldNumber = 93; + private static readonly pb::FieldCodec _repeated_unpackedUint64_codec + = pb::FieldCodec.ForUInt64(744); + private readonly pbc::RepeatedField unpackedUint64_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField UnpackedUint64 { + get { return unpackedUint64_; } + } + + /// Field number for the "unpacked_sint32" field. + public const int UnpackedSint32FieldNumber = 94; + private static readonly pb::FieldCodec _repeated_unpackedSint32_codec + = pb::FieldCodec.ForSInt32(752); + private readonly pbc::RepeatedField unpackedSint32_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField UnpackedSint32 { + get { return unpackedSint32_; } + } + + /// Field number for the "unpacked_sint64" field. + public const int UnpackedSint64FieldNumber = 95; + private static readonly pb::FieldCodec _repeated_unpackedSint64_codec + = pb::FieldCodec.ForSInt64(760); + private readonly pbc::RepeatedField unpackedSint64_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField UnpackedSint64 { + get { return unpackedSint64_; } + } + + /// Field number for the "unpacked_fixed32" field. + public const int UnpackedFixed32FieldNumber = 96; + private static readonly pb::FieldCodec _repeated_unpackedFixed32_codec + = pb::FieldCodec.ForFixed32(773); + private readonly pbc::RepeatedField unpackedFixed32_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField UnpackedFixed32 { + get { return unpackedFixed32_; } + } + + /// Field number for the "unpacked_fixed64" field. + public const int UnpackedFixed64FieldNumber = 97; + private static readonly pb::FieldCodec _repeated_unpackedFixed64_codec + = pb::FieldCodec.ForFixed64(777); + private readonly pbc::RepeatedField unpackedFixed64_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField UnpackedFixed64 { + get { return unpackedFixed64_; } + } + + /// Field number for the "unpacked_sfixed32" field. + public const int UnpackedSfixed32FieldNumber = 98; + private static readonly pb::FieldCodec _repeated_unpackedSfixed32_codec + = pb::FieldCodec.ForSFixed32(789); + private readonly pbc::RepeatedField unpackedSfixed32_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField UnpackedSfixed32 { + get { return unpackedSfixed32_; } + } + + /// Field number for the "unpacked_sfixed64" field. + public const int UnpackedSfixed64FieldNumber = 99; + private static readonly pb::FieldCodec _repeated_unpackedSfixed64_codec + = pb::FieldCodec.ForSFixed64(793); + private readonly pbc::RepeatedField unpackedSfixed64_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField UnpackedSfixed64 { + get { return unpackedSfixed64_; } + } + + /// Field number for the "unpacked_float" field. + public const int UnpackedFloatFieldNumber = 100; + private static readonly pb::FieldCodec _repeated_unpackedFloat_codec + = pb::FieldCodec.ForFloat(805); + private readonly pbc::RepeatedField unpackedFloat_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField UnpackedFloat { + get { return unpackedFloat_; } + } + + /// Field number for the "unpacked_double" field. + public const int UnpackedDoubleFieldNumber = 101; + private static readonly pb::FieldCodec _repeated_unpackedDouble_codec + = pb::FieldCodec.ForDouble(809); + private readonly pbc::RepeatedField unpackedDouble_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField UnpackedDouble { + get { return unpackedDouble_; } + } + + /// Field number for the "unpacked_bool" field. + public const int UnpackedBoolFieldNumber = 102; + private static readonly pb::FieldCodec _repeated_unpackedBool_codec + = pb::FieldCodec.ForBool(816); + private readonly pbc::RepeatedField unpackedBool_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField UnpackedBool { + get { return unpackedBool_; } + } + + /// Field number for the "unpacked_enum" field. + public const int UnpackedEnumFieldNumber = 103; + private static readonly pb::FieldCodec _repeated_unpackedEnum_codec + = pb::FieldCodec.ForEnum(824, x => (int) x, x => (global::Google.Protobuf.TestProtos.Proto2.ForeignEnum) x); + private readonly pbc::RepeatedField unpackedEnum_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField UnpackedEnum { + get { return unpackedEnum_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestUnpackedTypes); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestUnpackedTypes other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!unpackedInt32_.Equals(other.unpackedInt32_)) return false; + if(!unpackedInt64_.Equals(other.unpackedInt64_)) return false; + if(!unpackedUint32_.Equals(other.unpackedUint32_)) return false; + if(!unpackedUint64_.Equals(other.unpackedUint64_)) return false; + if(!unpackedSint32_.Equals(other.unpackedSint32_)) return false; + if(!unpackedSint64_.Equals(other.unpackedSint64_)) return false; + if(!unpackedFixed32_.Equals(other.unpackedFixed32_)) return false; + if(!unpackedFixed64_.Equals(other.unpackedFixed64_)) return false; + if(!unpackedSfixed32_.Equals(other.unpackedSfixed32_)) return false; + if(!unpackedSfixed64_.Equals(other.unpackedSfixed64_)) return false; + if(!unpackedFloat_.Equals(other.unpackedFloat_)) return false; + if(!unpackedDouble_.Equals(other.unpackedDouble_)) return false; + if(!unpackedBool_.Equals(other.unpackedBool_)) return false; + if(!unpackedEnum_.Equals(other.unpackedEnum_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + hash ^= unpackedInt32_.GetHashCode(); + hash ^= unpackedInt64_.GetHashCode(); + hash ^= unpackedUint32_.GetHashCode(); + hash ^= unpackedUint64_.GetHashCode(); + hash ^= unpackedSint32_.GetHashCode(); + hash ^= unpackedSint64_.GetHashCode(); + hash ^= unpackedFixed32_.GetHashCode(); + hash ^= unpackedFixed64_.GetHashCode(); + hash ^= unpackedSfixed32_.GetHashCode(); + hash ^= unpackedSfixed64_.GetHashCode(); + hash ^= unpackedFloat_.GetHashCode(); + hash ^= unpackedDouble_.GetHashCode(); + hash ^= unpackedBool_.GetHashCode(); + hash ^= unpackedEnum_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + unpackedInt32_.WriteTo(output, _repeated_unpackedInt32_codec); + unpackedInt64_.WriteTo(output, _repeated_unpackedInt64_codec); + unpackedUint32_.WriteTo(output, _repeated_unpackedUint32_codec); + unpackedUint64_.WriteTo(output, _repeated_unpackedUint64_codec); + unpackedSint32_.WriteTo(output, _repeated_unpackedSint32_codec); + unpackedSint64_.WriteTo(output, _repeated_unpackedSint64_codec); + unpackedFixed32_.WriteTo(output, _repeated_unpackedFixed32_codec); + unpackedFixed64_.WriteTo(output, _repeated_unpackedFixed64_codec); + unpackedSfixed32_.WriteTo(output, _repeated_unpackedSfixed32_codec); + unpackedSfixed64_.WriteTo(output, _repeated_unpackedSfixed64_codec); + unpackedFloat_.WriteTo(output, _repeated_unpackedFloat_codec); + unpackedDouble_.WriteTo(output, _repeated_unpackedDouble_codec); + unpackedBool_.WriteTo(output, _repeated_unpackedBool_codec); + unpackedEnum_.WriteTo(output, _repeated_unpackedEnum_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + unpackedInt32_.WriteTo(ref output, _repeated_unpackedInt32_codec); + unpackedInt64_.WriteTo(ref output, _repeated_unpackedInt64_codec); + unpackedUint32_.WriteTo(ref output, _repeated_unpackedUint32_codec); + unpackedUint64_.WriteTo(ref output, _repeated_unpackedUint64_codec); + unpackedSint32_.WriteTo(ref output, _repeated_unpackedSint32_codec); + unpackedSint64_.WriteTo(ref output, _repeated_unpackedSint64_codec); + unpackedFixed32_.WriteTo(ref output, _repeated_unpackedFixed32_codec); + unpackedFixed64_.WriteTo(ref output, _repeated_unpackedFixed64_codec); + unpackedSfixed32_.WriteTo(ref output, _repeated_unpackedSfixed32_codec); + unpackedSfixed64_.WriteTo(ref output, _repeated_unpackedSfixed64_codec); + unpackedFloat_.WriteTo(ref output, _repeated_unpackedFloat_codec); + unpackedDouble_.WriteTo(ref output, _repeated_unpackedDouble_codec); + unpackedBool_.WriteTo(ref output, _repeated_unpackedBool_codec); + unpackedEnum_.WriteTo(ref output, _repeated_unpackedEnum_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + size += unpackedInt32_.CalculateSize(_repeated_unpackedInt32_codec); + size += unpackedInt64_.CalculateSize(_repeated_unpackedInt64_codec); + size += unpackedUint32_.CalculateSize(_repeated_unpackedUint32_codec); + size += unpackedUint64_.CalculateSize(_repeated_unpackedUint64_codec); + size += unpackedSint32_.CalculateSize(_repeated_unpackedSint32_codec); + size += unpackedSint64_.CalculateSize(_repeated_unpackedSint64_codec); + size += unpackedFixed32_.CalculateSize(_repeated_unpackedFixed32_codec); + size += unpackedFixed64_.CalculateSize(_repeated_unpackedFixed64_codec); + size += unpackedSfixed32_.CalculateSize(_repeated_unpackedSfixed32_codec); + size += unpackedSfixed64_.CalculateSize(_repeated_unpackedSfixed64_codec); + size += unpackedFloat_.CalculateSize(_repeated_unpackedFloat_codec); + size += unpackedDouble_.CalculateSize(_repeated_unpackedDouble_codec); + size += unpackedBool_.CalculateSize(_repeated_unpackedBool_codec); + size += unpackedEnum_.CalculateSize(_repeated_unpackedEnum_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestUnpackedTypes other) { + if (other == null) { + return; + } + unpackedInt32_.Add(other.unpackedInt32_); + unpackedInt64_.Add(other.unpackedInt64_); + unpackedUint32_.Add(other.unpackedUint32_); + unpackedUint64_.Add(other.unpackedUint64_); + unpackedSint32_.Add(other.unpackedSint32_); + unpackedSint64_.Add(other.unpackedSint64_); + unpackedFixed32_.Add(other.unpackedFixed32_); + unpackedFixed64_.Add(other.unpackedFixed64_); + unpackedSfixed32_.Add(other.unpackedSfixed32_); + unpackedSfixed64_.Add(other.unpackedSfixed64_); + unpackedFloat_.Add(other.unpackedFloat_); + unpackedDouble_.Add(other.unpackedDouble_); + unpackedBool_.Add(other.unpackedBool_); + unpackedEnum_.Add(other.unpackedEnum_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 722: + case 720: { + unpackedInt32_.AddEntriesFrom(input, _repeated_unpackedInt32_codec); + break; + } + case 730: + case 728: { + unpackedInt64_.AddEntriesFrom(input, _repeated_unpackedInt64_codec); + break; + } + case 738: + case 736: { + unpackedUint32_.AddEntriesFrom(input, _repeated_unpackedUint32_codec); + break; + } + case 746: + case 744: { + unpackedUint64_.AddEntriesFrom(input, _repeated_unpackedUint64_codec); + break; + } + case 754: + case 752: { + unpackedSint32_.AddEntriesFrom(input, _repeated_unpackedSint32_codec); + break; + } + case 762: + case 760: { + unpackedSint64_.AddEntriesFrom(input, _repeated_unpackedSint64_codec); + break; + } + case 770: + case 773: { + unpackedFixed32_.AddEntriesFrom(input, _repeated_unpackedFixed32_codec); + break; + } + case 778: + case 777: { + unpackedFixed64_.AddEntriesFrom(input, _repeated_unpackedFixed64_codec); + break; + } + case 786: + case 789: { + unpackedSfixed32_.AddEntriesFrom(input, _repeated_unpackedSfixed32_codec); + break; + } + case 794: + case 793: { + unpackedSfixed64_.AddEntriesFrom(input, _repeated_unpackedSfixed64_codec); + break; + } + case 802: + case 805: { + unpackedFloat_.AddEntriesFrom(input, _repeated_unpackedFloat_codec); + break; + } + case 810: + case 809: { + unpackedDouble_.AddEntriesFrom(input, _repeated_unpackedDouble_codec); + break; + } + case 818: + case 816: { + unpackedBool_.AddEntriesFrom(input, _repeated_unpackedBool_codec); + break; + } + case 826: + case 824: { + unpackedEnum_.AddEntriesFrom(input, _repeated_unpackedEnum_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 722: + case 720: { + unpackedInt32_.AddEntriesFrom(ref input, _repeated_unpackedInt32_codec); + break; + } + case 730: + case 728: { + unpackedInt64_.AddEntriesFrom(ref input, _repeated_unpackedInt64_codec); + break; + } + case 738: + case 736: { + unpackedUint32_.AddEntriesFrom(ref input, _repeated_unpackedUint32_codec); + break; + } + case 746: + case 744: { + unpackedUint64_.AddEntriesFrom(ref input, _repeated_unpackedUint64_codec); + break; + } + case 754: + case 752: { + unpackedSint32_.AddEntriesFrom(ref input, _repeated_unpackedSint32_codec); + break; + } + case 762: + case 760: { + unpackedSint64_.AddEntriesFrom(ref input, _repeated_unpackedSint64_codec); + break; + } + case 770: + case 773: { + unpackedFixed32_.AddEntriesFrom(ref input, _repeated_unpackedFixed32_codec); + break; + } + case 778: + case 777: { + unpackedFixed64_.AddEntriesFrom(ref input, _repeated_unpackedFixed64_codec); + break; + } + case 786: + case 789: { + unpackedSfixed32_.AddEntriesFrom(ref input, _repeated_unpackedSfixed32_codec); + break; + } + case 794: + case 793: { + unpackedSfixed64_.AddEntriesFrom(ref input, _repeated_unpackedSfixed64_codec); + break; + } + case 802: + case 805: { + unpackedFloat_.AddEntriesFrom(ref input, _repeated_unpackedFloat_codec); + break; + } + case 810: + case 809: { + unpackedDouble_.AddEntriesFrom(ref input, _repeated_unpackedDouble_codec); + break; + } + case 818: + case 816: { + unpackedBool_.AddEntriesFrom(ref input, _repeated_unpackedBool_codec); + break; + } + case 826: + case 824: { + unpackedEnum_.AddEntriesFrom(ref input, _repeated_unpackedEnum_codec); + break; + } + } + } + } + #endif + + } + + public sealed partial class TestPackedExtensions : pb::IExtendableMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestPackedExtensions()); + private pb::UnknownFieldSet _unknownFields; + private pb::ExtensionSet _extensions; + private pb::ExtensionSet _Extensions { get { return _extensions; } } + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[50]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestPackedExtensions() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestPackedExtensions(TestPackedExtensions other) : this() { + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + _extensions = pb::ExtensionSet.Clone(other._extensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestPackedExtensions Clone() { + return new TestPackedExtensions(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestPackedExtensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestPackedExtensions other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!Equals(_extensions, other._extensions)) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (_extensions != null) { + hash ^= _extensions.GetHashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (_extensions != null) { + _extensions.WriteTo(output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (_extensions != null) { + _extensions.WriteTo(ref output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (_extensions != null) { + size += _extensions.CalculateSize(); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestPackedExtensions other) { + if (other == null) { + return; + } + pb::ExtensionSet.MergeFrom(ref _extensions, other._extensions); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + } + break; + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + } + break; + } + } + } + #endif + + public TValue GetExtension(pb::Extension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetOrInitializeExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.GetOrInitialize(ref _extensions, extension); + } + public void SetExtension(pb::Extension extension, TValue value) { + pb::ExtensionSet.Set(ref _extensions, extension, value); + } + public bool HasExtension(pb::Extension extension) { + return pb::ExtensionSet.Has(ref _extensions, extension); + } + public void ClearExtension(pb::Extension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + public void ClearExtension(pb::RepeatedExtension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + + } + + public sealed partial class TestUnpackedExtensions : pb::IExtendableMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestUnpackedExtensions()); + private pb::UnknownFieldSet _unknownFields; + private pb::ExtensionSet _extensions; + private pb::ExtensionSet _Extensions { get { return _extensions; } } + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[51]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestUnpackedExtensions() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestUnpackedExtensions(TestUnpackedExtensions other) : this() { + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + _extensions = pb::ExtensionSet.Clone(other._extensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestUnpackedExtensions Clone() { + return new TestUnpackedExtensions(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestUnpackedExtensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestUnpackedExtensions other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!Equals(_extensions, other._extensions)) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (_extensions != null) { + hash ^= _extensions.GetHashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (_extensions != null) { + _extensions.WriteTo(output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (_extensions != null) { + _extensions.WriteTo(ref output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (_extensions != null) { + size += _extensions.CalculateSize(); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestUnpackedExtensions other) { + if (other == null) { + return; + } + pb::ExtensionSet.MergeFrom(ref _extensions, other._extensions); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + } + break; + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + } + break; + } + } + } + #endif + + public TValue GetExtension(pb::Extension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetOrInitializeExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.GetOrInitialize(ref _extensions, extension); + } + public void SetExtension(pb::Extension extension, TValue value) { + pb::ExtensionSet.Set(ref _extensions, extension, value); + } + public bool HasExtension(pb::Extension extension) { + return pb::ExtensionSet.Has(ref _extensions, extension); + } + public void ClearExtension(pb::Extension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + public void ClearExtension(pb::RepeatedExtension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + + } + + /// + /// Used by ExtensionSetTest/DynamicExtensions. The test actually builds + /// a set of extensions to TestAllExtensions dynamically, based on the fields + /// of this message type. + /// + public sealed partial class TestDynamicExtensions : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestDynamicExtensions()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[52]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestDynamicExtensions() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestDynamicExtensions(TestDynamicExtensions other) : this() { + _hasBits0 = other._hasBits0; + scalarExtension_ = other.scalarExtension_; + enumExtension_ = other.enumExtension_; + dynamicEnumExtension_ = other.dynamicEnumExtension_; + messageExtension_ = other.messageExtension_ != null ? other.messageExtension_.Clone() : null; + dynamicMessageExtension_ = other.dynamicMessageExtension_ != null ? other.dynamicMessageExtension_.Clone() : null; + repeatedExtension_ = other.repeatedExtension_.Clone(); + packedExtension_ = other.packedExtension_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestDynamicExtensions Clone() { + return new TestDynamicExtensions(this); + } + + /// Field number for the "scalar_extension" field. + public const int ScalarExtensionFieldNumber = 2000; + private readonly static uint ScalarExtensionDefaultValue = 0; + + private uint scalarExtension_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public uint ScalarExtension { + get { if ((_hasBits0 & 1) != 0) { return scalarExtension_; } else { return ScalarExtensionDefaultValue; } } + set { + _hasBits0 |= 1; + scalarExtension_ = value; + } + } + /// Gets whether the "scalar_extension" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasScalarExtension { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "scalar_extension" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearScalarExtension() { + _hasBits0 &= ~1; + } + + /// Field number for the "enum_extension" field. + public const int EnumExtensionFieldNumber = 2001; + private readonly static global::Google.Protobuf.TestProtos.Proto2.ForeignEnum EnumExtensionDefaultValue = global::Google.Protobuf.TestProtos.Proto2.ForeignEnum.ForeignFoo; + + private global::Google.Protobuf.TestProtos.Proto2.ForeignEnum enumExtension_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.ForeignEnum EnumExtension { + get { if ((_hasBits0 & 2) != 0) { return enumExtension_; } else { return EnumExtensionDefaultValue; } } + set { + _hasBits0 |= 2; + enumExtension_ = value; + } + } + /// Gets whether the "enum_extension" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasEnumExtension { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "enum_extension" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearEnumExtension() { + _hasBits0 &= ~2; + } + + /// Field number for the "dynamic_enum_extension" field. + public const int DynamicEnumExtensionFieldNumber = 2002; + private readonly static global::Google.Protobuf.TestProtos.Proto2.TestDynamicExtensions.Types.DynamicEnumType DynamicEnumExtensionDefaultValue = global::Google.Protobuf.TestProtos.Proto2.TestDynamicExtensions.Types.DynamicEnumType.DynamicFoo; + + private global::Google.Protobuf.TestProtos.Proto2.TestDynamicExtensions.Types.DynamicEnumType dynamicEnumExtension_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestDynamicExtensions.Types.DynamicEnumType DynamicEnumExtension { + get { if ((_hasBits0 & 4) != 0) { return dynamicEnumExtension_; } else { return DynamicEnumExtensionDefaultValue; } } + set { + _hasBits0 |= 4; + dynamicEnumExtension_ = value; + } + } + /// Gets whether the "dynamic_enum_extension" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDynamicEnumExtension { + get { return (_hasBits0 & 4) != 0; } + } + /// Clears the value of the "dynamic_enum_extension" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDynamicEnumExtension() { + _hasBits0 &= ~4; + } + + /// Field number for the "message_extension" field. + public const int MessageExtensionFieldNumber = 2003; + private global::Google.Protobuf.TestProtos.Proto2.ForeignMessage messageExtension_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.ForeignMessage MessageExtension { + get { return messageExtension_; } + set { + messageExtension_ = value; + } + } + + /// Field number for the "dynamic_message_extension" field. + public const int DynamicMessageExtensionFieldNumber = 2004; + private global::Google.Protobuf.TestProtos.Proto2.TestDynamicExtensions.Types.DynamicMessageType dynamicMessageExtension_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestDynamicExtensions.Types.DynamicMessageType DynamicMessageExtension { + get { return dynamicMessageExtension_; } + set { + dynamicMessageExtension_ = value; + } + } + + /// Field number for the "repeated_extension" field. + public const int RepeatedExtensionFieldNumber = 2005; + private static readonly pb::FieldCodec _repeated_repeatedExtension_codec + = pb::FieldCodec.ForString(16042); + private readonly pbc::RepeatedField repeatedExtension_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedExtension { + get { return repeatedExtension_; } + } + + /// Field number for the "packed_extension" field. + public const int PackedExtensionFieldNumber = 2006; + private static readonly pb::FieldCodec _repeated_packedExtension_codec + = pb::FieldCodec.ForSInt32(16050); + private readonly pbc::RepeatedField packedExtension_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField PackedExtension { + get { return packedExtension_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestDynamicExtensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestDynamicExtensions other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (ScalarExtension != other.ScalarExtension) return false; + if (EnumExtension != other.EnumExtension) return false; + if (DynamicEnumExtension != other.DynamicEnumExtension) return false; + if (!object.Equals(MessageExtension, other.MessageExtension)) return false; + if (!object.Equals(DynamicMessageExtension, other.DynamicMessageExtension)) return false; + if(!repeatedExtension_.Equals(other.repeatedExtension_)) return false; + if(!packedExtension_.Equals(other.packedExtension_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasScalarExtension) hash ^= ScalarExtension.GetHashCode(); + if (HasEnumExtension) hash ^= EnumExtension.GetHashCode(); + if (HasDynamicEnumExtension) hash ^= DynamicEnumExtension.GetHashCode(); + if (messageExtension_ != null) hash ^= MessageExtension.GetHashCode(); + if (dynamicMessageExtension_ != null) hash ^= DynamicMessageExtension.GetHashCode(); + hash ^= repeatedExtension_.GetHashCode(); + hash ^= packedExtension_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasScalarExtension) { + output.WriteRawTag(133, 125); + output.WriteFixed32(ScalarExtension); + } + if (HasEnumExtension) { + output.WriteRawTag(136, 125); + output.WriteEnum((int) EnumExtension); + } + if (HasDynamicEnumExtension) { + output.WriteRawTag(144, 125); + output.WriteEnum((int) DynamicEnumExtension); + } + if (messageExtension_ != null) { + output.WriteRawTag(154, 125); + output.WriteMessage(MessageExtension); + } + if (dynamicMessageExtension_ != null) { + output.WriteRawTag(162, 125); + output.WriteMessage(DynamicMessageExtension); + } + repeatedExtension_.WriteTo(output, _repeated_repeatedExtension_codec); + packedExtension_.WriteTo(output, _repeated_packedExtension_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasScalarExtension) { + output.WriteRawTag(133, 125); + output.WriteFixed32(ScalarExtension); + } + if (HasEnumExtension) { + output.WriteRawTag(136, 125); + output.WriteEnum((int) EnumExtension); + } + if (HasDynamicEnumExtension) { + output.WriteRawTag(144, 125); + output.WriteEnum((int) DynamicEnumExtension); + } + if (messageExtension_ != null) { + output.WriteRawTag(154, 125); + output.WriteMessage(MessageExtension); + } + if (dynamicMessageExtension_ != null) { + output.WriteRawTag(162, 125); + output.WriteMessage(DynamicMessageExtension); + } + repeatedExtension_.WriteTo(ref output, _repeated_repeatedExtension_codec); + packedExtension_.WriteTo(ref output, _repeated_packedExtension_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasScalarExtension) { + size += 2 + 4; + } + if (HasEnumExtension) { + size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) EnumExtension); + } + if (HasDynamicEnumExtension) { + size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) DynamicEnumExtension); + } + if (messageExtension_ != null) { + size += 2 + pb::CodedOutputStream.ComputeMessageSize(MessageExtension); + } + if (dynamicMessageExtension_ != null) { + size += 2 + pb::CodedOutputStream.ComputeMessageSize(DynamicMessageExtension); + } + size += repeatedExtension_.CalculateSize(_repeated_repeatedExtension_codec); + size += packedExtension_.CalculateSize(_repeated_packedExtension_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestDynamicExtensions other) { + if (other == null) { + return; + } + if (other.HasScalarExtension) { + ScalarExtension = other.ScalarExtension; + } + if (other.HasEnumExtension) { + EnumExtension = other.EnumExtension; + } + if (other.HasDynamicEnumExtension) { + DynamicEnumExtension = other.DynamicEnumExtension; + } + if (other.messageExtension_ != null) { + if (messageExtension_ == null) { + MessageExtension = new global::Google.Protobuf.TestProtos.Proto2.ForeignMessage(); + } + MessageExtension.MergeFrom(other.MessageExtension); + } + if (other.dynamicMessageExtension_ != null) { + if (dynamicMessageExtension_ == null) { + DynamicMessageExtension = new global::Google.Protobuf.TestProtos.Proto2.TestDynamicExtensions.Types.DynamicMessageType(); + } + DynamicMessageExtension.MergeFrom(other.DynamicMessageExtension); + } + repeatedExtension_.Add(other.repeatedExtension_); + packedExtension_.Add(other.packedExtension_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 16005: { + ScalarExtension = input.ReadFixed32(); + break; + } + case 16008: { + EnumExtension = (global::Google.Protobuf.TestProtos.Proto2.ForeignEnum) input.ReadEnum(); + break; + } + case 16016: { + DynamicEnumExtension = (global::Google.Protobuf.TestProtos.Proto2.TestDynamicExtensions.Types.DynamicEnumType) input.ReadEnum(); + break; + } + case 16026: { + if (messageExtension_ == null) { + MessageExtension = new global::Google.Protobuf.TestProtos.Proto2.ForeignMessage(); + } + input.ReadMessage(MessageExtension); + break; + } + case 16034: { + if (dynamicMessageExtension_ == null) { + DynamicMessageExtension = new global::Google.Protobuf.TestProtos.Proto2.TestDynamicExtensions.Types.DynamicMessageType(); + } + input.ReadMessage(DynamicMessageExtension); + break; + } + case 16042: { + repeatedExtension_.AddEntriesFrom(input, _repeated_repeatedExtension_codec); + break; + } + case 16050: + case 16048: { + packedExtension_.AddEntriesFrom(input, _repeated_packedExtension_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 16005: { + ScalarExtension = input.ReadFixed32(); + break; + } + case 16008: { + EnumExtension = (global::Google.Protobuf.TestProtos.Proto2.ForeignEnum) input.ReadEnum(); + break; + } + case 16016: { + DynamicEnumExtension = (global::Google.Protobuf.TestProtos.Proto2.TestDynamicExtensions.Types.DynamicEnumType) input.ReadEnum(); + break; + } + case 16026: { + if (messageExtension_ == null) { + MessageExtension = new global::Google.Protobuf.TestProtos.Proto2.ForeignMessage(); + } + input.ReadMessage(MessageExtension); + break; + } + case 16034: { + if (dynamicMessageExtension_ == null) { + DynamicMessageExtension = new global::Google.Protobuf.TestProtos.Proto2.TestDynamicExtensions.Types.DynamicMessageType(); + } + input.ReadMessage(DynamicMessageExtension); + break; + } + case 16042: { + repeatedExtension_.AddEntriesFrom(ref input, _repeated_repeatedExtension_codec); + break; + } + case 16050: + case 16048: { + packedExtension_.AddEntriesFrom(ref input, _repeated_packedExtension_codec); + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the TestDynamicExtensions message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public enum DynamicEnumType { + [pbr::OriginalName("DYNAMIC_FOO")] DynamicFoo = 2200, + [pbr::OriginalName("DYNAMIC_BAR")] DynamicBar = 2201, + [pbr::OriginalName("DYNAMIC_BAZ")] DynamicBaz = 2202, + } + + public sealed partial class DynamicMessageType : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new DynamicMessageType()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestDynamicExtensions.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public DynamicMessageType() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public DynamicMessageType(DynamicMessageType other) : this() { + _hasBits0 = other._hasBits0; + dynamicField_ = other.dynamicField_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public DynamicMessageType Clone() { + return new DynamicMessageType(this); + } + + /// Field number for the "dynamic_field" field. + public const int DynamicFieldFieldNumber = 2100; + private readonly static int DynamicFieldDefaultValue = 0; + + private int dynamicField_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int DynamicField { + get { if ((_hasBits0 & 1) != 0) { return dynamicField_; } else { return DynamicFieldDefaultValue; } } + set { + _hasBits0 |= 1; + dynamicField_ = value; + } + } + /// Gets whether the "dynamic_field" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDynamicField { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "dynamic_field" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDynamicField() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as DynamicMessageType); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(DynamicMessageType other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (DynamicField != other.DynamicField) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasDynamicField) hash ^= DynamicField.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasDynamicField) { + output.WriteRawTag(160, 131, 1); + output.WriteInt32(DynamicField); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasDynamicField) { + output.WriteRawTag(160, 131, 1); + output.WriteInt32(DynamicField); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasDynamicField) { + size += 3 + pb::CodedOutputStream.ComputeInt32Size(DynamicField); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(DynamicMessageType other) { + if (other == null) { + return; + } + if (other.HasDynamicField) { + DynamicField = other.DynamicField; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 16800: { + DynamicField = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 16800: { + DynamicField = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + } + #endregion + + } + + public sealed partial class TestRepeatedScalarDifferentTagSizes : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestRepeatedScalarDifferentTagSizes()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[53]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestRepeatedScalarDifferentTagSizes() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestRepeatedScalarDifferentTagSizes(TestRepeatedScalarDifferentTagSizes other) : this() { + repeatedFixed32_ = other.repeatedFixed32_.Clone(); + repeatedInt32_ = other.repeatedInt32_.Clone(); + repeatedFixed64_ = other.repeatedFixed64_.Clone(); + repeatedInt64_ = other.repeatedInt64_.Clone(); + repeatedFloat_ = other.repeatedFloat_.Clone(); + repeatedUint64_ = other.repeatedUint64_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestRepeatedScalarDifferentTagSizes Clone() { + return new TestRepeatedScalarDifferentTagSizes(this); + } + + /// Field number for the "repeated_fixed32" field. + public const int RepeatedFixed32FieldNumber = 12; + private static readonly pb::FieldCodec _repeated_repeatedFixed32_codec + = pb::FieldCodec.ForFixed32(101); + private readonly pbc::RepeatedField repeatedFixed32_ = new pbc::RepeatedField(); + /// + /// Parsing repeated fixed size values used to fail. This message needs to be + /// used in order to get a tag of the right size; all of the repeated fields + /// in TestAllTypes didn't trigger the check. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedFixed32 { + get { return repeatedFixed32_; } + } + + /// Field number for the "repeated_int32" field. + public const int RepeatedInt32FieldNumber = 13; + private static readonly pb::FieldCodec _repeated_repeatedInt32_codec + = pb::FieldCodec.ForInt32(104); + private readonly pbc::RepeatedField repeatedInt32_ = new pbc::RepeatedField(); + /// + /// Check for a varint type, just for good measure. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedInt32 { + get { return repeatedInt32_; } + } + + /// Field number for the "repeated_fixed64" field. + public const int RepeatedFixed64FieldNumber = 2046; + private static readonly pb::FieldCodec _repeated_repeatedFixed64_codec + = pb::FieldCodec.ForFixed64(16369); + private readonly pbc::RepeatedField repeatedFixed64_ = new pbc::RepeatedField(); + /// + /// These have two-byte tags. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedFixed64 { + get { return repeatedFixed64_; } + } + + /// Field number for the "repeated_int64" field. + public const int RepeatedInt64FieldNumber = 2047; + private static readonly pb::FieldCodec _repeated_repeatedInt64_codec + = pb::FieldCodec.ForInt64(16376); + private readonly pbc::RepeatedField repeatedInt64_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedInt64 { + get { return repeatedInt64_; } + } + + /// Field number for the "repeated_float" field. + public const int RepeatedFloatFieldNumber = 262142; + private static readonly pb::FieldCodec _repeated_repeatedFloat_codec + = pb::FieldCodec.ForFloat(2097141); + private readonly pbc::RepeatedField repeatedFloat_ = new pbc::RepeatedField(); + /// + /// Three byte tags. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedFloat { + get { return repeatedFloat_; } + } + + /// Field number for the "repeated_uint64" field. + public const int RepeatedUint64FieldNumber = 262143; + private static readonly pb::FieldCodec _repeated_repeatedUint64_codec + = pb::FieldCodec.ForUInt64(2097144); + private readonly pbc::RepeatedField repeatedUint64_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedUint64 { + get { return repeatedUint64_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestRepeatedScalarDifferentTagSizes); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestRepeatedScalarDifferentTagSizes other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!repeatedFixed32_.Equals(other.repeatedFixed32_)) return false; + if(!repeatedInt32_.Equals(other.repeatedInt32_)) return false; + if(!repeatedFixed64_.Equals(other.repeatedFixed64_)) return false; + if(!repeatedInt64_.Equals(other.repeatedInt64_)) return false; + if(!repeatedFloat_.Equals(other.repeatedFloat_)) return false; + if(!repeatedUint64_.Equals(other.repeatedUint64_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + hash ^= repeatedFixed32_.GetHashCode(); + hash ^= repeatedInt32_.GetHashCode(); + hash ^= repeatedFixed64_.GetHashCode(); + hash ^= repeatedInt64_.GetHashCode(); + hash ^= repeatedFloat_.GetHashCode(); + hash ^= repeatedUint64_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + repeatedFixed32_.WriteTo(output, _repeated_repeatedFixed32_codec); + repeatedInt32_.WriteTo(output, _repeated_repeatedInt32_codec); + repeatedFixed64_.WriteTo(output, _repeated_repeatedFixed64_codec); + repeatedInt64_.WriteTo(output, _repeated_repeatedInt64_codec); + repeatedFloat_.WriteTo(output, _repeated_repeatedFloat_codec); + repeatedUint64_.WriteTo(output, _repeated_repeatedUint64_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + repeatedFixed32_.WriteTo(ref output, _repeated_repeatedFixed32_codec); + repeatedInt32_.WriteTo(ref output, _repeated_repeatedInt32_codec); + repeatedFixed64_.WriteTo(ref output, _repeated_repeatedFixed64_codec); + repeatedInt64_.WriteTo(ref output, _repeated_repeatedInt64_codec); + repeatedFloat_.WriteTo(ref output, _repeated_repeatedFloat_codec); + repeatedUint64_.WriteTo(ref output, _repeated_repeatedUint64_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + size += repeatedFixed32_.CalculateSize(_repeated_repeatedFixed32_codec); + size += repeatedInt32_.CalculateSize(_repeated_repeatedInt32_codec); + size += repeatedFixed64_.CalculateSize(_repeated_repeatedFixed64_codec); + size += repeatedInt64_.CalculateSize(_repeated_repeatedInt64_codec); + size += repeatedFloat_.CalculateSize(_repeated_repeatedFloat_codec); + size += repeatedUint64_.CalculateSize(_repeated_repeatedUint64_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestRepeatedScalarDifferentTagSizes other) { + if (other == null) { + return; + } + repeatedFixed32_.Add(other.repeatedFixed32_); + repeatedInt32_.Add(other.repeatedInt32_); + repeatedFixed64_.Add(other.repeatedFixed64_); + repeatedInt64_.Add(other.repeatedInt64_); + repeatedFloat_.Add(other.repeatedFloat_); + repeatedUint64_.Add(other.repeatedUint64_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 98: + case 101: { + repeatedFixed32_.AddEntriesFrom(input, _repeated_repeatedFixed32_codec); + break; + } + case 106: + case 104: { + repeatedInt32_.AddEntriesFrom(input, _repeated_repeatedInt32_codec); + break; + } + case 16370: + case 16369: { + repeatedFixed64_.AddEntriesFrom(input, _repeated_repeatedFixed64_codec); + break; + } + case 16378: + case 16376: { + repeatedInt64_.AddEntriesFrom(input, _repeated_repeatedInt64_codec); + break; + } + case 2097138: + case 2097141: { + repeatedFloat_.AddEntriesFrom(input, _repeated_repeatedFloat_codec); + break; + } + case 2097146: + case 2097144: { + repeatedUint64_.AddEntriesFrom(input, _repeated_repeatedUint64_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 98: + case 101: { + repeatedFixed32_.AddEntriesFrom(ref input, _repeated_repeatedFixed32_codec); + break; + } + case 106: + case 104: { + repeatedInt32_.AddEntriesFrom(ref input, _repeated_repeatedInt32_codec); + break; + } + case 16370: + case 16369: { + repeatedFixed64_.AddEntriesFrom(ref input, _repeated_repeatedFixed64_codec); + break; + } + case 16378: + case 16376: { + repeatedInt64_.AddEntriesFrom(ref input, _repeated_repeatedInt64_codec); + break; + } + case 2097138: + case 2097141: { + repeatedFloat_.AddEntriesFrom(ref input, _repeated_repeatedFloat_codec); + break; + } + case 2097146: + case 2097144: { + repeatedUint64_.AddEntriesFrom(ref input, _repeated_repeatedUint64_codec); + break; + } + } + } + } + #endif + + } + + /// + /// Test that if an optional or required message/group field appears multiple + /// times in the input, they need to be merged. + /// + public sealed partial class TestParsingMerge : pb::IExtendableMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestParsingMerge()); + private pb::UnknownFieldSet _unknownFields; + private pb::ExtensionSet _extensions; + private pb::ExtensionSet _Extensions { get { return _extensions; } } + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[54]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestParsingMerge() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestParsingMerge(TestParsingMerge other) : this() { + requiredAllTypes_ = other.requiredAllTypes_ != null ? other.requiredAllTypes_.Clone() : null; + optionalAllTypes_ = other.optionalAllTypes_ != null ? other.optionalAllTypes_.Clone() : null; + repeatedAllTypes_ = other.repeatedAllTypes_.Clone(); + optionalGroup_ = other.HasOptionalGroup ? other.optionalGroup_.Clone() : null; + repeatedGroup_ = other.repeatedGroup_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + _extensions = pb::ExtensionSet.Clone(other._extensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestParsingMerge Clone() { + return new TestParsingMerge(this); + } + + /// Field number for the "required_all_types" field. + public const int RequiredAllTypesFieldNumber = 1; + private global::Google.Protobuf.TestProtos.Proto2.TestAllTypes requiredAllTypes_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestAllTypes RequiredAllTypes { + get { return requiredAllTypes_; } + set { + requiredAllTypes_ = value; + } + } + + /// Field number for the "optional_all_types" field. + public const int OptionalAllTypesFieldNumber = 2; + private global::Google.Protobuf.TestProtos.Proto2.TestAllTypes optionalAllTypes_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestAllTypes OptionalAllTypes { + get { return optionalAllTypes_; } + set { + optionalAllTypes_ = value; + } + } + + /// Field number for the "repeated_all_types" field. + public const int RepeatedAllTypesFieldNumber = 3; + private static readonly pb::FieldCodec _repeated_repeatedAllTypes_codec + = pb::FieldCodec.ForMessage(26, global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Parser); + private readonly pbc::RepeatedField repeatedAllTypes_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedAllTypes { + get { return repeatedAllTypes_; } + } + + /// Field number for the "optionalgroup" field. + public const int OptionalGroupFieldNumber = 10; + private global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Types.OptionalGroup optionalGroup_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Types.OptionalGroup OptionalGroup { + get { return optionalGroup_; } + set { + optionalGroup_ = value; + } + } + /// Gets whether the optionalgroup field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalGroup { + get { return optionalGroup_ != null; } + } + /// Clears the value of the optionalgroup field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalGroup() { + optionalGroup_ = null; + } + + /// Field number for the "repeatedgroup" field. + public const int RepeatedGroupFieldNumber = 20; + private static readonly pb::FieldCodec _repeated_repeatedGroup_codec + = pb::FieldCodec.ForGroup(163, 164, global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Types.RepeatedGroup.Parser); + private readonly pbc::RepeatedField repeatedGroup_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedGroup { + get { return repeatedGroup_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestParsingMerge); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestParsingMerge other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(RequiredAllTypes, other.RequiredAllTypes)) return false; + if (!object.Equals(OptionalAllTypes, other.OptionalAllTypes)) return false; + if(!repeatedAllTypes_.Equals(other.repeatedAllTypes_)) return false; + if (!object.Equals(OptionalGroup, other.OptionalGroup)) return false; + if(!repeatedGroup_.Equals(other.repeatedGroup_)) return false; + if (!Equals(_extensions, other._extensions)) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (requiredAllTypes_ != null) hash ^= RequiredAllTypes.GetHashCode(); + if (optionalAllTypes_ != null) hash ^= OptionalAllTypes.GetHashCode(); + hash ^= repeatedAllTypes_.GetHashCode(); + if (HasOptionalGroup) hash ^= OptionalGroup.GetHashCode(); + hash ^= repeatedGroup_.GetHashCode(); + if (_extensions != null) { + hash ^= _extensions.GetHashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (requiredAllTypes_ != null) { + output.WriteRawTag(10); + output.WriteMessage(RequiredAllTypes); + } + if (optionalAllTypes_ != null) { + output.WriteRawTag(18); + output.WriteMessage(OptionalAllTypes); + } + repeatedAllTypes_.WriteTo(output, _repeated_repeatedAllTypes_codec); + if (HasOptionalGroup) { + output.WriteRawTag(83); + output.WriteGroup(OptionalGroup); + output.WriteRawTag(84); + } + repeatedGroup_.WriteTo(output, _repeated_repeatedGroup_codec); + if (_extensions != null) { + _extensions.WriteTo(output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (requiredAllTypes_ != null) { + output.WriteRawTag(10); + output.WriteMessage(RequiredAllTypes); + } + if (optionalAllTypes_ != null) { + output.WriteRawTag(18); + output.WriteMessage(OptionalAllTypes); + } + repeatedAllTypes_.WriteTo(ref output, _repeated_repeatedAllTypes_codec); + if (HasOptionalGroup) { + output.WriteRawTag(83); + output.WriteGroup(OptionalGroup); + output.WriteRawTag(84); + } + repeatedGroup_.WriteTo(ref output, _repeated_repeatedGroup_codec); + if (_extensions != null) { + _extensions.WriteTo(ref output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (requiredAllTypes_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(RequiredAllTypes); + } + if (optionalAllTypes_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(OptionalAllTypes); + } + size += repeatedAllTypes_.CalculateSize(_repeated_repeatedAllTypes_codec); + if (HasOptionalGroup) { + size += 2 + pb::CodedOutputStream.ComputeGroupSize(OptionalGroup); + } + size += repeatedGroup_.CalculateSize(_repeated_repeatedGroup_codec); + if (_extensions != null) { + size += _extensions.CalculateSize(); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestParsingMerge other) { + if (other == null) { + return; + } + if (other.requiredAllTypes_ != null) { + if (requiredAllTypes_ == null) { + RequiredAllTypes = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + RequiredAllTypes.MergeFrom(other.RequiredAllTypes); + } + if (other.optionalAllTypes_ != null) { + if (optionalAllTypes_ == null) { + OptionalAllTypes = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + OptionalAllTypes.MergeFrom(other.OptionalAllTypes); + } + repeatedAllTypes_.Add(other.repeatedAllTypes_); + if (other.HasOptionalGroup) { + if (!HasOptionalGroup) { + OptionalGroup = new global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Types.OptionalGroup(); + } + OptionalGroup.MergeFrom(other.OptionalGroup); + } + repeatedGroup_.Add(other.repeatedGroup_); + pb::ExtensionSet.MergeFrom(ref _extensions, other._extensions); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + } + break; + case 10: { + if (requiredAllTypes_ == null) { + RequiredAllTypes = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + input.ReadMessage(RequiredAllTypes); + break; + } + case 18: { + if (optionalAllTypes_ == null) { + OptionalAllTypes = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + input.ReadMessage(OptionalAllTypes); + break; + } + case 26: { + repeatedAllTypes_.AddEntriesFrom(input, _repeated_repeatedAllTypes_codec); + break; + } + case 83: { + if (!HasOptionalGroup) { + OptionalGroup = new global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Types.OptionalGroup(); + } + input.ReadGroup(OptionalGroup); + break; + } + case 163: { + repeatedGroup_.AddEntriesFrom(input, _repeated_repeatedGroup_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + } + break; + case 10: { + if (requiredAllTypes_ == null) { + RequiredAllTypes = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + input.ReadMessage(RequiredAllTypes); + break; + } + case 18: { + if (optionalAllTypes_ == null) { + OptionalAllTypes = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + input.ReadMessage(OptionalAllTypes); + break; + } + case 26: { + repeatedAllTypes_.AddEntriesFrom(ref input, _repeated_repeatedAllTypes_codec); + break; + } + case 83: { + if (!HasOptionalGroup) { + OptionalGroup = new global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Types.OptionalGroup(); + } + input.ReadGroup(OptionalGroup); + break; + } + case 163: { + repeatedGroup_.AddEntriesFrom(ref input, _repeated_repeatedGroup_codec); + break; + } + } + } + } + #endif + + public TValue GetExtension(pb::Extension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetOrInitializeExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.GetOrInitialize(ref _extensions, extension); + } + public void SetExtension(pb::Extension extension, TValue value) { + pb::ExtensionSet.Set(ref _extensions, extension, value); + } + public bool HasExtension(pb::Extension extension) { + return pb::ExtensionSet.Has(ref _extensions, extension); + } + public void ClearExtension(pb::Extension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + public void ClearExtension(pb::RepeatedExtension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + + #region Nested types + /// Container for nested types declared in the TestParsingMerge message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + /// + /// RepeatedFieldsGenerator defines matching field types as TestParsingMerge, + /// except that all fields are repeated. In the tests, we will serialize the + /// RepeatedFieldsGenerator to bytes, and parse the bytes to TestParsingMerge. + /// Repeated fields in RepeatedFieldsGenerator are expected to be merged into + /// the corresponding required/optional fields in TestParsingMerge. + /// + public sealed partial class RepeatedFieldsGenerator : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new RepeatedFieldsGenerator()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public RepeatedFieldsGenerator() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public RepeatedFieldsGenerator(RepeatedFieldsGenerator other) : this() { + field1_ = other.field1_.Clone(); + field2_ = other.field2_.Clone(); + field3_ = other.field3_.Clone(); + group1_ = other.group1_.Clone(); + group2_ = other.group2_.Clone(); + ext1_ = other.ext1_.Clone(); + ext2_ = other.ext2_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public RepeatedFieldsGenerator Clone() { + return new RepeatedFieldsGenerator(this); + } + + /// Field number for the "field1" field. + public const int Field1FieldNumber = 1; + private static readonly pb::FieldCodec _repeated_field1_codec + = pb::FieldCodec.ForMessage(10, global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Parser); + private readonly pbc::RepeatedField field1_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Field1 { + get { return field1_; } + } + + /// Field number for the "field2" field. + public const int Field2FieldNumber = 2; + private static readonly pb::FieldCodec _repeated_field2_codec + = pb::FieldCodec.ForMessage(18, global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Parser); + private readonly pbc::RepeatedField field2_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Field2 { + get { return field2_; } + } + + /// Field number for the "field3" field. + public const int Field3FieldNumber = 3; + private static readonly pb::FieldCodec _repeated_field3_codec + = pb::FieldCodec.ForMessage(26, global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Parser); + private readonly pbc::RepeatedField field3_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Field3 { + get { return field3_; } + } + + /// Field number for the "group1" field. + public const int Group1FieldNumber = 10; + private static readonly pb::FieldCodec _repeated_group1_codec + = pb::FieldCodec.ForGroup(83, 84, global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Types.RepeatedFieldsGenerator.Types.Group1.Parser); + private readonly pbc::RepeatedField group1_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Group1 { + get { return group1_; } + } + + /// Field number for the "group2" field. + public const int Group2FieldNumber = 20; + private static readonly pb::FieldCodec _repeated_group2_codec + = pb::FieldCodec.ForGroup(163, 164, global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Types.RepeatedFieldsGenerator.Types.Group2.Parser); + private readonly pbc::RepeatedField group2_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Group2 { + get { return group2_; } + } + + /// Field number for the "ext1" field. + public const int Ext1FieldNumber = 1000; + private static readonly pb::FieldCodec _repeated_ext1_codec + = pb::FieldCodec.ForMessage(8002, global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Parser); + private readonly pbc::RepeatedField ext1_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Ext1 { + get { return ext1_; } + } + + /// Field number for the "ext2" field. + public const int Ext2FieldNumber = 1001; + private static readonly pb::FieldCodec _repeated_ext2_codec + = pb::FieldCodec.ForMessage(8010, global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Parser); + private readonly pbc::RepeatedField ext2_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Ext2 { + get { return ext2_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as RepeatedFieldsGenerator); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(RepeatedFieldsGenerator other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!field1_.Equals(other.field1_)) return false; + if(!field2_.Equals(other.field2_)) return false; + if(!field3_.Equals(other.field3_)) return false; + if(!group1_.Equals(other.group1_)) return false; + if(!group2_.Equals(other.group2_)) return false; + if(!ext1_.Equals(other.ext1_)) return false; + if(!ext2_.Equals(other.ext2_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + hash ^= field1_.GetHashCode(); + hash ^= field2_.GetHashCode(); + hash ^= field3_.GetHashCode(); + hash ^= group1_.GetHashCode(); + hash ^= group2_.GetHashCode(); + hash ^= ext1_.GetHashCode(); + hash ^= ext2_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + field1_.WriteTo(output, _repeated_field1_codec); + field2_.WriteTo(output, _repeated_field2_codec); + field3_.WriteTo(output, _repeated_field3_codec); + group1_.WriteTo(output, _repeated_group1_codec); + group2_.WriteTo(output, _repeated_group2_codec); + ext1_.WriteTo(output, _repeated_ext1_codec); + ext2_.WriteTo(output, _repeated_ext2_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + field1_.WriteTo(ref output, _repeated_field1_codec); + field2_.WriteTo(ref output, _repeated_field2_codec); + field3_.WriteTo(ref output, _repeated_field3_codec); + group1_.WriteTo(ref output, _repeated_group1_codec); + group2_.WriteTo(ref output, _repeated_group2_codec); + ext1_.WriteTo(ref output, _repeated_ext1_codec); + ext2_.WriteTo(ref output, _repeated_ext2_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + size += field1_.CalculateSize(_repeated_field1_codec); + size += field2_.CalculateSize(_repeated_field2_codec); + size += field3_.CalculateSize(_repeated_field3_codec); + size += group1_.CalculateSize(_repeated_group1_codec); + size += group2_.CalculateSize(_repeated_group2_codec); + size += ext1_.CalculateSize(_repeated_ext1_codec); + size += ext2_.CalculateSize(_repeated_ext2_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(RepeatedFieldsGenerator other) { + if (other == null) { + return; + } + field1_.Add(other.field1_); + field2_.Add(other.field2_); + field3_.Add(other.field3_); + group1_.Add(other.group1_); + group2_.Add(other.group2_); + ext1_.Add(other.ext1_); + ext2_.Add(other.ext2_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + field1_.AddEntriesFrom(input, _repeated_field1_codec); + break; + } + case 18: { + field2_.AddEntriesFrom(input, _repeated_field2_codec); + break; + } + case 26: { + field3_.AddEntriesFrom(input, _repeated_field3_codec); + break; + } + case 83: { + group1_.AddEntriesFrom(input, _repeated_group1_codec); + break; + } + case 163: { + group2_.AddEntriesFrom(input, _repeated_group2_codec); + break; + } + case 8002: { + ext1_.AddEntriesFrom(input, _repeated_ext1_codec); + break; + } + case 8010: { + ext2_.AddEntriesFrom(input, _repeated_ext2_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + field1_.AddEntriesFrom(ref input, _repeated_field1_codec); + break; + } + case 18: { + field2_.AddEntriesFrom(ref input, _repeated_field2_codec); + break; + } + case 26: { + field3_.AddEntriesFrom(ref input, _repeated_field3_codec); + break; + } + case 83: { + group1_.AddEntriesFrom(ref input, _repeated_group1_codec); + break; + } + case 163: { + group2_.AddEntriesFrom(ref input, _repeated_group2_codec); + break; + } + case 8002: { + ext1_.AddEntriesFrom(ref input, _repeated_ext1_codec); + break; + } + case 8010: { + ext2_.AddEntriesFrom(ref input, _repeated_ext2_codec); + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the RepeatedFieldsGenerator message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public sealed partial class Group1 : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Group1()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Types.RepeatedFieldsGenerator.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Group1() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Group1(Group1 other) : this() { + field1_ = other.field1_ != null ? other.field1_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Group1 Clone() { + return new Group1(this); + } + + /// Field number for the "field1" field. + public const int Field1FieldNumber = 11; + private global::Google.Protobuf.TestProtos.Proto2.TestAllTypes field1_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestAllTypes Field1 { + get { return field1_; } + set { + field1_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as Group1); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(Group1 other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(Field1, other.Field1)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (field1_ != null) hash ^= Field1.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (field1_ != null) { + output.WriteRawTag(90); + output.WriteMessage(Field1); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (field1_ != null) { + output.WriteRawTag(90); + output.WriteMessage(Field1); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (field1_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Field1); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(Group1 other) { + if (other == null) { + return; + } + if (other.field1_ != null) { + if (field1_ == null) { + Field1 = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + Field1.MergeFrom(other.Field1); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 84: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 90: { + if (field1_ == null) { + Field1 = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + input.ReadMessage(Field1); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 84: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 90: { + if (field1_ == null) { + Field1 = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + input.ReadMessage(Field1); + break; + } + } + } + } + #endif + + } + + public sealed partial class Group2 : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Group2()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Types.RepeatedFieldsGenerator.Descriptor.NestedTypes[1]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Group2() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Group2(Group2 other) : this() { + field1_ = other.field1_ != null ? other.field1_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Group2 Clone() { + return new Group2(this); + } + + /// Field number for the "field1" field. + public const int Field1FieldNumber = 21; + private global::Google.Protobuf.TestProtos.Proto2.TestAllTypes field1_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestAllTypes Field1 { + get { return field1_; } + set { + field1_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as Group2); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(Group2 other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(Field1, other.Field1)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (field1_ != null) hash ^= Field1.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (field1_ != null) { + output.WriteRawTag(170, 1); + output.WriteMessage(Field1); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (field1_ != null) { + output.WriteRawTag(170, 1); + output.WriteMessage(Field1); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (field1_ != null) { + size += 2 + pb::CodedOutputStream.ComputeMessageSize(Field1); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(Group2 other) { + if (other == null) { + return; + } + if (other.field1_ != null) { + if (field1_ == null) { + Field1 = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + Field1.MergeFrom(other.Field1); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 164: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 170: { + if (field1_ == null) { + Field1 = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + input.ReadMessage(Field1); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 164: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 170: { + if (field1_ == null) { + Field1 = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + input.ReadMessage(Field1); + break; + } + } + } + } + #endif + + } + + } + #endregion + + } + + public sealed partial class OptionalGroup : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new OptionalGroup()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Descriptor.NestedTypes[1]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OptionalGroup() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OptionalGroup(OptionalGroup other) : this() { + optionalGroupAllTypes_ = other.optionalGroupAllTypes_ != null ? other.optionalGroupAllTypes_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OptionalGroup Clone() { + return new OptionalGroup(this); + } + + /// Field number for the "optional_group_all_types" field. + public const int OptionalGroupAllTypesFieldNumber = 11; + private global::Google.Protobuf.TestProtos.Proto2.TestAllTypes optionalGroupAllTypes_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestAllTypes OptionalGroupAllTypes { + get { return optionalGroupAllTypes_; } + set { + optionalGroupAllTypes_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as OptionalGroup); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(OptionalGroup other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(OptionalGroupAllTypes, other.OptionalGroupAllTypes)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (optionalGroupAllTypes_ != null) hash ^= OptionalGroupAllTypes.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (optionalGroupAllTypes_ != null) { + output.WriteRawTag(90); + output.WriteMessage(OptionalGroupAllTypes); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (optionalGroupAllTypes_ != null) { + output.WriteRawTag(90); + output.WriteMessage(OptionalGroupAllTypes); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (optionalGroupAllTypes_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(OptionalGroupAllTypes); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(OptionalGroup other) { + if (other == null) { + return; + } + if (other.optionalGroupAllTypes_ != null) { + if (optionalGroupAllTypes_ == null) { + OptionalGroupAllTypes = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + OptionalGroupAllTypes.MergeFrom(other.OptionalGroupAllTypes); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 84: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 90: { + if (optionalGroupAllTypes_ == null) { + OptionalGroupAllTypes = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + input.ReadMessage(OptionalGroupAllTypes); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 84: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 90: { + if (optionalGroupAllTypes_ == null) { + OptionalGroupAllTypes = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + input.ReadMessage(OptionalGroupAllTypes); + break; + } + } + } + } + #endif + + } + + public sealed partial class RepeatedGroup : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new RepeatedGroup()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestParsingMerge.Descriptor.NestedTypes[2]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public RepeatedGroup() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public RepeatedGroup(RepeatedGroup other) : this() { + repeatedGroupAllTypes_ = other.repeatedGroupAllTypes_ != null ? other.repeatedGroupAllTypes_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public RepeatedGroup Clone() { + return new RepeatedGroup(this); + } + + /// Field number for the "repeated_group_all_types" field. + public const int RepeatedGroupAllTypesFieldNumber = 21; + private global::Google.Protobuf.TestProtos.Proto2.TestAllTypes repeatedGroupAllTypes_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestAllTypes RepeatedGroupAllTypes { + get { return repeatedGroupAllTypes_; } + set { + repeatedGroupAllTypes_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as RepeatedGroup); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(RepeatedGroup other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(RepeatedGroupAllTypes, other.RepeatedGroupAllTypes)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (repeatedGroupAllTypes_ != null) hash ^= RepeatedGroupAllTypes.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (repeatedGroupAllTypes_ != null) { + output.WriteRawTag(170, 1); + output.WriteMessage(RepeatedGroupAllTypes); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (repeatedGroupAllTypes_ != null) { + output.WriteRawTag(170, 1); + output.WriteMessage(RepeatedGroupAllTypes); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (repeatedGroupAllTypes_ != null) { + size += 2 + pb::CodedOutputStream.ComputeMessageSize(RepeatedGroupAllTypes); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(RepeatedGroup other) { + if (other == null) { + return; + } + if (other.repeatedGroupAllTypes_ != null) { + if (repeatedGroupAllTypes_ == null) { + RepeatedGroupAllTypes = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + RepeatedGroupAllTypes.MergeFrom(other.RepeatedGroupAllTypes); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 164: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 170: { + if (repeatedGroupAllTypes_ == null) { + RepeatedGroupAllTypes = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + input.ReadMessage(RepeatedGroupAllTypes); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 164: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 170: { + if (repeatedGroupAllTypes_ == null) { + RepeatedGroupAllTypes = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + input.ReadMessage(RepeatedGroupAllTypes); + break; + } + } + } + } + #endif + + } + + } + #endregion + + #region Extensions + /// Container for extensions for other messages declared in the TestParsingMerge message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Extensions { + public static readonly pb::Extension OptionalExt = + new pb::Extension(1000, pb::FieldCodec.ForMessage(8002, global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Parser)); + public static readonly pb::RepeatedExtension RepeatedExt = + new pb::RepeatedExtension(1001, pb::FieldCodec.ForMessage(8010, global::Google.Protobuf.TestProtos.Proto2.TestAllTypes.Parser)); + } + #endregion + + } + + public sealed partial class TestCommentInjectionMessage : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestCommentInjectionMessage()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[55]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestCommentInjectionMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestCommentInjectionMessage(TestCommentInjectionMessage other) : this() { + a_ = other.a_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestCommentInjectionMessage Clone() { + return new TestCommentInjectionMessage(this); + } + + /// Field number for the "a" field. + public const int AFieldNumber = 1; + private readonly static string ADefaultValue = global::System.Text.Encoding.UTF8.GetString(global::System.Convert.FromBase64String("Ki8gPC0gTmVpdGhlciBzaG91bGQgdGhpcy4="), 0, 26); + + private string a_; + /// + /// */ <- This should not close the generated doc comment + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string A { + get { return a_ ?? ADefaultValue; } + set { + a_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "a" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasA { + get { return a_ != null; } + } + /// Clears the value of the "a" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearA() { + a_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestCommentInjectionMessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestCommentInjectionMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (A != other.A) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasA) hash ^= A.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasA) { + output.WriteRawTag(10); + output.WriteString(A); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasA) { + output.WriteRawTag(10); + output.WriteString(A); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasA) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(A); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestCommentInjectionMessage other) { + if (other == null) { + return; + } + if (other.HasA) { + A = other.A; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + A = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + A = input.ReadString(); + break; + } + } + } + } + #endif + + } + + /// + /// Test that RPC services work. + /// + public sealed partial class FooRequest : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new FooRequest()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[56]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooRequest() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooRequest(FooRequest other) : this() { + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooRequest Clone() { + return new FooRequest(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as FooRequest); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(FooRequest other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(FooRequest other) { + if (other == null) { + return; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + } + } + } + #endif + + } + + public sealed partial class FooResponse : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new FooResponse()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[57]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooResponse() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooResponse(FooResponse other) : this() { + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooResponse Clone() { + return new FooResponse(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as FooResponse); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(FooResponse other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(FooResponse other) { + if (other == null) { + return; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + } + } + } + #endif + + } + + public sealed partial class FooClientMessage : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new FooClientMessage()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[58]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooClientMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooClientMessage(FooClientMessage other) : this() { + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooClientMessage Clone() { + return new FooClientMessage(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as FooClientMessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(FooClientMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(FooClientMessage other) { + if (other == null) { + return; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + } + } + } + #endif + + } + + public sealed partial class FooServerMessage : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new FooServerMessage()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[59]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooServerMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooServerMessage(FooServerMessage other) : this() { + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooServerMessage Clone() { + return new FooServerMessage(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as FooServerMessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(FooServerMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(FooServerMessage other) { + if (other == null) { + return; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + } + } + } + #endif + + } + + public sealed partial class BarRequest : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new BarRequest()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[60]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public BarRequest() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public BarRequest(BarRequest other) : this() { + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public BarRequest Clone() { + return new BarRequest(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as BarRequest); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(BarRequest other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(BarRequest other) { + if (other == null) { + return; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + } + } + } + #endif + + } + + public sealed partial class BarResponse : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new BarResponse()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[61]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public BarResponse() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public BarResponse(BarResponse other) : this() { + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public BarResponse Clone() { + return new BarResponse(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as BarResponse); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(BarResponse other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(BarResponse other) { + if (other == null) { + return; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + } + } + } + #endif + + } + + public sealed partial class TestJsonName : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestJsonName()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[62]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestJsonName() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestJsonName(TestJsonName other) : this() { + _hasBits0 = other._hasBits0; + fieldName1_ = other.fieldName1_; + fieldName2_ = other.fieldName2_; + fieldName3_ = other.fieldName3_; + FieldName4_ = other.FieldName4_; + fIELDNAME5_ = other.fIELDNAME5_; + fieldName6_ = other.fieldName6_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestJsonName Clone() { + return new TestJsonName(this); + } + + /// Field number for the "field_name1" field. + public const int FieldName1FieldNumber = 1; + private readonly static int FieldName1DefaultValue = 0; + + private int fieldName1_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int FieldName1 { + get { if ((_hasBits0 & 1) != 0) { return fieldName1_; } else { return FieldName1DefaultValue; } } + set { + _hasBits0 |= 1; + fieldName1_ = value; + } + } + /// Gets whether the "field_name1" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFieldName1 { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "field_name1" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFieldName1() { + _hasBits0 &= ~1; + } + + /// Field number for the "fieldName2" field. + public const int FieldName2FieldNumber = 2; + private readonly static int FieldName2DefaultValue = 0; + + private int fieldName2_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int FieldName2 { + get { if ((_hasBits0 & 2) != 0) { return fieldName2_; } else { return FieldName2DefaultValue; } } + set { + _hasBits0 |= 2; + fieldName2_ = value; + } + } + /// Gets whether the "fieldName2" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFieldName2 { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "fieldName2" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFieldName2() { + _hasBits0 &= ~2; + } + + /// Field number for the "FieldName3" field. + public const int FieldName3FieldNumber = 3; + private readonly static int FieldName3DefaultValue = 0; + + private int fieldName3_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int FieldName3 { + get { if ((_hasBits0 & 4) != 0) { return fieldName3_; } else { return FieldName3DefaultValue; } } + set { + _hasBits0 |= 4; + fieldName3_ = value; + } + } + /// Gets whether the "FieldName3" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFieldName3 { + get { return (_hasBits0 & 4) != 0; } + } + /// Clears the value of the "FieldName3" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFieldName3() { + _hasBits0 &= ~4; + } + + /// Field number for the "_field_name4" field. + public const int FieldName4FieldNumber = 4; + private readonly static int FieldName4DefaultValue = 0; + + private int FieldName4_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int FieldName4 { + get { if ((_hasBits0 & 8) != 0) { return FieldName4_; } else { return FieldName4DefaultValue; } } + set { + _hasBits0 |= 8; + FieldName4_ = value; + } + } + /// Gets whether the "_field_name4" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFieldName4 { + get { return (_hasBits0 & 8) != 0; } + } + /// Clears the value of the "_field_name4" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFieldName4() { + _hasBits0 &= ~8; + } + + /// Field number for the "FIELD_NAME5" field. + public const int FIELDNAME5FieldNumber = 5; + private readonly static int FIELDNAME5DefaultValue = 0; + + private int fIELDNAME5_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int FIELDNAME5 { + get { if ((_hasBits0 & 16) != 0) { return fIELDNAME5_; } else { return FIELDNAME5DefaultValue; } } + set { + _hasBits0 |= 16; + fIELDNAME5_ = value; + } + } + /// Gets whether the "FIELD_NAME5" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFIELDNAME5 { + get { return (_hasBits0 & 16) != 0; } + } + /// Clears the value of the "FIELD_NAME5" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFIELDNAME5() { + _hasBits0 &= ~16; + } + + /// Field number for the "field_name6" field. + public const int FieldName6FieldNumber = 6; + private readonly static int FieldName6DefaultValue = 0; + + private int fieldName6_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int FieldName6 { + get { if ((_hasBits0 & 32) != 0) { return fieldName6_; } else { return FieldName6DefaultValue; } } + set { + _hasBits0 |= 32; + fieldName6_ = value; + } + } + /// Gets whether the "field_name6" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFieldName6 { + get { return (_hasBits0 & 32) != 0; } + } + /// Clears the value of the "field_name6" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFieldName6() { + _hasBits0 &= ~32; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestJsonName); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestJsonName other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (FieldName1 != other.FieldName1) return false; + if (FieldName2 != other.FieldName2) return false; + if (FieldName3 != other.FieldName3) return false; + if (FieldName4 != other.FieldName4) return false; + if (FIELDNAME5 != other.FIELDNAME5) return false; + if (FieldName6 != other.FieldName6) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasFieldName1) hash ^= FieldName1.GetHashCode(); + if (HasFieldName2) hash ^= FieldName2.GetHashCode(); + if (HasFieldName3) hash ^= FieldName3.GetHashCode(); + if (HasFieldName4) hash ^= FieldName4.GetHashCode(); + if (HasFIELDNAME5) hash ^= FIELDNAME5.GetHashCode(); + if (HasFieldName6) hash ^= FieldName6.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasFieldName1) { + output.WriteRawTag(8); + output.WriteInt32(FieldName1); + } + if (HasFieldName2) { + output.WriteRawTag(16); + output.WriteInt32(FieldName2); + } + if (HasFieldName3) { + output.WriteRawTag(24); + output.WriteInt32(FieldName3); + } + if (HasFieldName4) { + output.WriteRawTag(32); + output.WriteInt32(FieldName4); + } + if (HasFIELDNAME5) { + output.WriteRawTag(40); + output.WriteInt32(FIELDNAME5); + } + if (HasFieldName6) { + output.WriteRawTag(48); + output.WriteInt32(FieldName6); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasFieldName1) { + output.WriteRawTag(8); + output.WriteInt32(FieldName1); + } + if (HasFieldName2) { + output.WriteRawTag(16); + output.WriteInt32(FieldName2); + } + if (HasFieldName3) { + output.WriteRawTag(24); + output.WriteInt32(FieldName3); + } + if (HasFieldName4) { + output.WriteRawTag(32); + output.WriteInt32(FieldName4); + } + if (HasFIELDNAME5) { + output.WriteRawTag(40); + output.WriteInt32(FIELDNAME5); + } + if (HasFieldName6) { + output.WriteRawTag(48); + output.WriteInt32(FieldName6); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasFieldName1) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(FieldName1); + } + if (HasFieldName2) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(FieldName2); + } + if (HasFieldName3) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(FieldName3); + } + if (HasFieldName4) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(FieldName4); + } + if (HasFIELDNAME5) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(FIELDNAME5); + } + if (HasFieldName6) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(FieldName6); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestJsonName other) { + if (other == null) { + return; + } + if (other.HasFieldName1) { + FieldName1 = other.FieldName1; + } + if (other.HasFieldName2) { + FieldName2 = other.FieldName2; + } + if (other.HasFieldName3) { + FieldName3 = other.FieldName3; + } + if (other.HasFieldName4) { + FieldName4 = other.FieldName4; + } + if (other.HasFIELDNAME5) { + FIELDNAME5 = other.FIELDNAME5; + } + if (other.HasFieldName6) { + FieldName6 = other.FieldName6; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + FieldName1 = input.ReadInt32(); + break; + } + case 16: { + FieldName2 = input.ReadInt32(); + break; + } + case 24: { + FieldName3 = input.ReadInt32(); + break; + } + case 32: { + FieldName4 = input.ReadInt32(); + break; + } + case 40: { + FIELDNAME5 = input.ReadInt32(); + break; + } + case 48: { + FieldName6 = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + FieldName1 = input.ReadInt32(); + break; + } + case 16: { + FieldName2 = input.ReadInt32(); + break; + } + case 24: { + FieldName3 = input.ReadInt32(); + break; + } + case 32: { + FieldName4 = input.ReadInt32(); + break; + } + case 40: { + FIELDNAME5 = input.ReadInt32(); + break; + } + case 48: { + FieldName6 = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + public sealed partial class TestHugeFieldNumbers : pb::IExtendableMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestHugeFieldNumbers()); + private pb::UnknownFieldSet _unknownFields; + private pb::ExtensionSet _extensions; + private pb::ExtensionSet _Extensions { get { return _extensions; } } + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[63]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestHugeFieldNumbers() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestHugeFieldNumbers(TestHugeFieldNumbers other) : this() { + _hasBits0 = other._hasBits0; + optionalInt32_ = other.optionalInt32_; + fixed32_ = other.fixed32_; + repeatedInt32_ = other.repeatedInt32_.Clone(); + packedInt32_ = other.packedInt32_.Clone(); + optionalEnum_ = other.optionalEnum_; + optionalString_ = other.optionalString_; + optionalBytes_ = other.optionalBytes_; + optionalMessage_ = other.optionalMessage_ != null ? other.optionalMessage_.Clone() : null; + optionalGroup_ = other.HasOptionalGroup ? other.optionalGroup_.Clone() : null; + stringStringMap_ = other.stringStringMap_.Clone(); + switch (other.OneofFieldCase) { + case OneofFieldOneofCase.OneofUint32: + OneofUint32 = other.OneofUint32; + break; + case OneofFieldOneofCase.OneofTestAllTypes: + OneofTestAllTypes = other.OneofTestAllTypes.Clone(); + break; + case OneofFieldOneofCase.OneofString: + OneofString = other.OneofString; + break; + case OneofFieldOneofCase.OneofBytes: + OneofBytes = other.OneofBytes; + break; + } + + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + _extensions = pb::ExtensionSet.Clone(other._extensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestHugeFieldNumbers Clone() { + return new TestHugeFieldNumbers(this); + } + + /// Field number for the "optional_int32" field. + public const int OptionalInt32FieldNumber = 536870000; + private readonly static int OptionalInt32DefaultValue = 0; + + private int optionalInt32_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int OptionalInt32 { + get { if ((_hasBits0 & 1) != 0) { return optionalInt32_; } else { return OptionalInt32DefaultValue; } } + set { + _hasBits0 |= 1; + optionalInt32_ = value; + } + } + /// Gets whether the "optional_int32" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalInt32 { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "optional_int32" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalInt32() { + _hasBits0 &= ~1; + } + + /// Field number for the "fixed_32" field. + public const int Fixed32FieldNumber = 536870001; + private readonly static int Fixed32DefaultValue = 0; + + private int fixed32_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Fixed32 { + get { if ((_hasBits0 & 2) != 0) { return fixed32_; } else { return Fixed32DefaultValue; } } + set { + _hasBits0 |= 2; + fixed32_ = value; + } + } + /// Gets whether the "fixed_32" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFixed32 { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "fixed_32" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFixed32() { + _hasBits0 &= ~2; + } + + /// Field number for the "repeated_int32" field. + public const int RepeatedInt32FieldNumber = 536870002; + private static readonly pb::FieldCodec _repeated_repeatedInt32_codec + = pb::FieldCodec.ForInt32(4294960016); + private readonly pbc::RepeatedField repeatedInt32_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField RepeatedInt32 { + get { return repeatedInt32_; } + } + + /// Field number for the "packed_int32" field. + public const int PackedInt32FieldNumber = 536870003; + private static readonly pb::FieldCodec _repeated_packedInt32_codec + = pb::FieldCodec.ForInt32(4294960026); + private readonly pbc::RepeatedField packedInt32_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField PackedInt32 { + get { return packedInt32_; } + } + + /// Field number for the "optional_enum" field. + public const int OptionalEnumFieldNumber = 536870004; + private readonly static global::Google.Protobuf.TestProtos.Proto2.ForeignEnum OptionalEnumDefaultValue = global::Google.Protobuf.TestProtos.Proto2.ForeignEnum.ForeignFoo; + + private global::Google.Protobuf.TestProtos.Proto2.ForeignEnum optionalEnum_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.ForeignEnum OptionalEnum { + get { if ((_hasBits0 & 4) != 0) { return optionalEnum_; } else { return OptionalEnumDefaultValue; } } + set { + _hasBits0 |= 4; + optionalEnum_ = value; + } + } + /// Gets whether the "optional_enum" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalEnum { + get { return (_hasBits0 & 4) != 0; } + } + /// Clears the value of the "optional_enum" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalEnum() { + _hasBits0 &= ~4; + } + + /// Field number for the "optional_string" field. + public const int OptionalStringFieldNumber = 536870005; + private readonly static string OptionalStringDefaultValue = ""; + + private string optionalString_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string OptionalString { + get { return optionalString_ ?? OptionalStringDefaultValue; } + set { + optionalString_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "optional_string" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalString { + get { return optionalString_ != null; } + } + /// Clears the value of the "optional_string" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalString() { + optionalString_ = null; + } + + /// Field number for the "optional_bytes" field. + public const int OptionalBytesFieldNumber = 536870006; + private readonly static pb::ByteString OptionalBytesDefaultValue = pb::ByteString.Empty; + + private pb::ByteString optionalBytes_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pb::ByteString OptionalBytes { + get { return optionalBytes_ ?? OptionalBytesDefaultValue; } + set { + optionalBytes_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "optional_bytes" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalBytes { + get { return optionalBytes_ != null; } + } + /// Clears the value of the "optional_bytes" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalBytes() { + optionalBytes_ = null; + } + + /// Field number for the "optional_message" field. + public const int OptionalMessageFieldNumber = 536870007; + private global::Google.Protobuf.TestProtos.Proto2.ForeignMessage optionalMessage_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.ForeignMessage OptionalMessage { + get { return optionalMessage_; } + set { + optionalMessage_ = value; + } + } + + /// Field number for the "optionalgroup" field. + public const int OptionalGroupFieldNumber = 536870008; + private global::Google.Protobuf.TestProtos.Proto2.TestHugeFieldNumbers.Types.OptionalGroup optionalGroup_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestHugeFieldNumbers.Types.OptionalGroup OptionalGroup { + get { return optionalGroup_; } + set { + optionalGroup_ = value; + } + } + /// Gets whether the optionalgroup field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalGroup { + get { return optionalGroup_ != null; } + } + /// Clears the value of the optionalgroup field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalGroup() { + optionalGroup_ = null; + } + + /// Field number for the "string_string_map" field. + public const int StringStringMapFieldNumber = 536870010; + private static readonly pbc::MapField.Codec _map_stringStringMap_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForString(10, ""), pb::FieldCodec.ForString(18, ""), 4294960082); + private readonly pbc::MapField stringStringMap_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField StringStringMap { + get { return stringStringMap_; } + } + + /// Field number for the "oneof_uint32" field. + public const int OneofUint32FieldNumber = 536870011; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public uint OneofUint32 { + get { return HasOneofUint32 ? (uint) oneofField_ : 0; } + set { + oneofField_ = value; + oneofFieldCase_ = OneofFieldOneofCase.OneofUint32; + } + } + /// Gets whether the "oneof_uint32" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOneofUint32 { + get { return oneofFieldCase_ == OneofFieldOneofCase.OneofUint32; } + } + /// Clears the value of the oneof if it's currently set to "oneof_uint32" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOneofUint32() { + if (HasOneofUint32) { + ClearOneofField(); + } + } + + /// Field number for the "oneof_test_all_types" field. + public const int OneofTestAllTypesFieldNumber = 536870012; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.Proto2.TestAllTypes OneofTestAllTypes { + get { return oneofFieldCase_ == OneofFieldOneofCase.OneofTestAllTypes ? (global::Google.Protobuf.TestProtos.Proto2.TestAllTypes) oneofField_ : null; } + set { + oneofField_ = value; + oneofFieldCase_ = value == null ? OneofFieldOneofCase.None : OneofFieldOneofCase.OneofTestAllTypes; + } + } + + /// Field number for the "oneof_string" field. + public const int OneofStringFieldNumber = 536870013; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string OneofString { + get { return HasOneofString ? (string) oneofField_ : ""; } + set { + oneofField_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + oneofFieldCase_ = OneofFieldOneofCase.OneofString; + } + } + /// Gets whether the "oneof_string" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOneofString { + get { return oneofFieldCase_ == OneofFieldOneofCase.OneofString; } + } + /// Clears the value of the oneof if it's currently set to "oneof_string" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOneofString() { + if (HasOneofString) { + ClearOneofField(); + } + } + + /// Field number for the "oneof_bytes" field. + public const int OneofBytesFieldNumber = 536870014; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pb::ByteString OneofBytes { + get { return HasOneofBytes ? (pb::ByteString) oneofField_ : pb::ByteString.Empty; } + set { + oneofField_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + oneofFieldCase_ = OneofFieldOneofCase.OneofBytes; + } + } + /// Gets whether the "oneof_bytes" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOneofBytes { + get { return oneofFieldCase_ == OneofFieldOneofCase.OneofBytes; } + } + /// Clears the value of the oneof if it's currently set to "oneof_bytes" + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOneofBytes() { + if (HasOneofBytes) { + ClearOneofField(); + } + } + + private object oneofField_; + /// Enum of possible cases for the "oneof_field" oneof. + public enum OneofFieldOneofCase { + None = 0, + OneofUint32 = 536870011, + OneofTestAllTypes = 536870012, + OneofString = 536870013, + OneofBytes = 536870014, + } + private OneofFieldOneofCase oneofFieldCase_ = OneofFieldOneofCase.None; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneofFieldOneofCase OneofFieldCase { + get { return oneofFieldCase_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOneofField() { + oneofFieldCase_ = OneofFieldOneofCase.None; + oneofField_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestHugeFieldNumbers); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestHugeFieldNumbers other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (OptionalInt32 != other.OptionalInt32) return false; + if (Fixed32 != other.Fixed32) return false; + if(!repeatedInt32_.Equals(other.repeatedInt32_)) return false; + if(!packedInt32_.Equals(other.packedInt32_)) return false; + if (OptionalEnum != other.OptionalEnum) return false; + if (OptionalString != other.OptionalString) return false; + if (OptionalBytes != other.OptionalBytes) return false; + if (!object.Equals(OptionalMessage, other.OptionalMessage)) return false; + if (!object.Equals(OptionalGroup, other.OptionalGroup)) return false; + if (!StringStringMap.Equals(other.StringStringMap)) return false; + if (OneofUint32 != other.OneofUint32) return false; + if (!object.Equals(OneofTestAllTypes, other.OneofTestAllTypes)) return false; + if (OneofString != other.OneofString) return false; + if (OneofBytes != other.OneofBytes) return false; + if (OneofFieldCase != other.OneofFieldCase) return false; + if (!Equals(_extensions, other._extensions)) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasOptionalInt32) hash ^= OptionalInt32.GetHashCode(); + if (HasFixed32) hash ^= Fixed32.GetHashCode(); + hash ^= repeatedInt32_.GetHashCode(); + hash ^= packedInt32_.GetHashCode(); + if (HasOptionalEnum) hash ^= OptionalEnum.GetHashCode(); + if (HasOptionalString) hash ^= OptionalString.GetHashCode(); + if (HasOptionalBytes) hash ^= OptionalBytes.GetHashCode(); + if (optionalMessage_ != null) hash ^= OptionalMessage.GetHashCode(); + if (HasOptionalGroup) hash ^= OptionalGroup.GetHashCode(); + hash ^= StringStringMap.GetHashCode(); + if (HasOneofUint32) hash ^= OneofUint32.GetHashCode(); + if (oneofFieldCase_ == OneofFieldOneofCase.OneofTestAllTypes) hash ^= OneofTestAllTypes.GetHashCode(); + if (HasOneofString) hash ^= OneofString.GetHashCode(); + if (HasOneofBytes) hash ^= OneofBytes.GetHashCode(); + hash ^= (int) oneofFieldCase_; + if (_extensions != null) { + hash ^= _extensions.GetHashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasOptionalInt32) { + output.WriteRawTag(128, 199, 255, 255, 15); + output.WriteInt32(OptionalInt32); + } + if (HasFixed32) { + output.WriteRawTag(136, 199, 255, 255, 15); + output.WriteInt32(Fixed32); + } + repeatedInt32_.WriteTo(output, _repeated_repeatedInt32_codec); + packedInt32_.WriteTo(output, _repeated_packedInt32_codec); + if (HasOptionalEnum) { + output.WriteRawTag(160, 199, 255, 255, 15); + output.WriteEnum((int) OptionalEnum); + } + if (HasOptionalString) { + output.WriteRawTag(170, 199, 255, 255, 15); + output.WriteString(OptionalString); + } + if (HasOptionalBytes) { + output.WriteRawTag(178, 199, 255, 255, 15); + output.WriteBytes(OptionalBytes); + } + if (optionalMessage_ != null) { + output.WriteRawTag(186, 199, 255, 255, 15); + output.WriteMessage(OptionalMessage); + } + if (HasOptionalGroup) { + output.WriteRawTag(195, 199, 255, 255, 15); + output.WriteGroup(OptionalGroup); + output.WriteRawTag(196, 199, 255, 255, 15); + } + stringStringMap_.WriteTo(output, _map_stringStringMap_codec); + if (HasOneofUint32) { + output.WriteRawTag(216, 199, 255, 255, 15); + output.WriteUInt32(OneofUint32); + } + if (oneofFieldCase_ == OneofFieldOneofCase.OneofTestAllTypes) { + output.WriteRawTag(226, 199, 255, 255, 15); + output.WriteMessage(OneofTestAllTypes); + } + if (HasOneofString) { + output.WriteRawTag(234, 199, 255, 255, 15); + output.WriteString(OneofString); + } + if (HasOneofBytes) { + output.WriteRawTag(242, 199, 255, 255, 15); + output.WriteBytes(OneofBytes); + } + if (_extensions != null) { + _extensions.WriteTo(output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasOptionalInt32) { + output.WriteRawTag(128, 199, 255, 255, 15); + output.WriteInt32(OptionalInt32); + } + if (HasFixed32) { + output.WriteRawTag(136, 199, 255, 255, 15); + output.WriteInt32(Fixed32); + } + repeatedInt32_.WriteTo(ref output, _repeated_repeatedInt32_codec); + packedInt32_.WriteTo(ref output, _repeated_packedInt32_codec); + if (HasOptionalEnum) { + output.WriteRawTag(160, 199, 255, 255, 15); + output.WriteEnum((int) OptionalEnum); + } + if (HasOptionalString) { + output.WriteRawTag(170, 199, 255, 255, 15); + output.WriteString(OptionalString); + } + if (HasOptionalBytes) { + output.WriteRawTag(178, 199, 255, 255, 15); + output.WriteBytes(OptionalBytes); + } + if (optionalMessage_ != null) { + output.WriteRawTag(186, 199, 255, 255, 15); + output.WriteMessage(OptionalMessage); + } + if (HasOptionalGroup) { + output.WriteRawTag(195, 199, 255, 255, 15); + output.WriteGroup(OptionalGroup); + output.WriteRawTag(196, 199, 255, 255, 15); + } + stringStringMap_.WriteTo(ref output, _map_stringStringMap_codec); + if (HasOneofUint32) { + output.WriteRawTag(216, 199, 255, 255, 15); + output.WriteUInt32(OneofUint32); + } + if (oneofFieldCase_ == OneofFieldOneofCase.OneofTestAllTypes) { + output.WriteRawTag(226, 199, 255, 255, 15); + output.WriteMessage(OneofTestAllTypes); + } + if (HasOneofString) { + output.WriteRawTag(234, 199, 255, 255, 15); + output.WriteString(OneofString); + } + if (HasOneofBytes) { + output.WriteRawTag(242, 199, 255, 255, 15); + output.WriteBytes(OneofBytes); + } + if (_extensions != null) { + _extensions.WriteTo(ref output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasOptionalInt32) { + size += 5 + pb::CodedOutputStream.ComputeInt32Size(OptionalInt32); + } + if (HasFixed32) { + size += 5 + pb::CodedOutputStream.ComputeInt32Size(Fixed32); + } + size += repeatedInt32_.CalculateSize(_repeated_repeatedInt32_codec); + size += packedInt32_.CalculateSize(_repeated_packedInt32_codec); + if (HasOptionalEnum) { + size += 5 + pb::CodedOutputStream.ComputeEnumSize((int) OptionalEnum); + } + if (HasOptionalString) { + size += 5 + pb::CodedOutputStream.ComputeStringSize(OptionalString); + } + if (HasOptionalBytes) { + size += 5 + pb::CodedOutputStream.ComputeBytesSize(OptionalBytes); + } + if (optionalMessage_ != null) { + size += 5 + pb::CodedOutputStream.ComputeMessageSize(OptionalMessage); + } + if (HasOptionalGroup) { + size += 10 + pb::CodedOutputStream.ComputeGroupSize(OptionalGroup); + } + size += stringStringMap_.CalculateSize(_map_stringStringMap_codec); + if (HasOneofUint32) { + size += 5 + pb::CodedOutputStream.ComputeUInt32Size(OneofUint32); + } + if (oneofFieldCase_ == OneofFieldOneofCase.OneofTestAllTypes) { + size += 5 + pb::CodedOutputStream.ComputeMessageSize(OneofTestAllTypes); + } + if (HasOneofString) { + size += 5 + pb::CodedOutputStream.ComputeStringSize(OneofString); + } + if (HasOneofBytes) { + size += 5 + pb::CodedOutputStream.ComputeBytesSize(OneofBytes); + } + if (_extensions != null) { + size += _extensions.CalculateSize(); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestHugeFieldNumbers other) { + if (other == null) { + return; + } + if (other.HasOptionalInt32) { + OptionalInt32 = other.OptionalInt32; + } + if (other.HasFixed32) { + Fixed32 = other.Fixed32; + } + repeatedInt32_.Add(other.repeatedInt32_); + packedInt32_.Add(other.packedInt32_); + if (other.HasOptionalEnum) { + OptionalEnum = other.OptionalEnum; + } + if (other.HasOptionalString) { + OptionalString = other.OptionalString; + } + if (other.HasOptionalBytes) { + OptionalBytes = other.OptionalBytes; + } + if (other.optionalMessage_ != null) { + if (optionalMessage_ == null) { + OptionalMessage = new global::Google.Protobuf.TestProtos.Proto2.ForeignMessage(); + } + OptionalMessage.MergeFrom(other.OptionalMessage); + } + if (other.HasOptionalGroup) { + if (!HasOptionalGroup) { + OptionalGroup = new global::Google.Protobuf.TestProtos.Proto2.TestHugeFieldNumbers.Types.OptionalGroup(); + } + OptionalGroup.MergeFrom(other.OptionalGroup); + } + stringStringMap_.Add(other.stringStringMap_); + switch (other.OneofFieldCase) { + case OneofFieldOneofCase.OneofUint32: + OneofUint32 = other.OneofUint32; + break; + case OneofFieldOneofCase.OneofTestAllTypes: + if (OneofTestAllTypes == null) { + OneofTestAllTypes = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + } + OneofTestAllTypes.MergeFrom(other.OneofTestAllTypes); + break; + case OneofFieldOneofCase.OneofString: + OneofString = other.OneofString; + break; + case OneofFieldOneofCase.OneofBytes: + OneofBytes = other.OneofBytes; + break; + } + + pb::ExtensionSet.MergeFrom(ref _extensions, other._extensions); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + } + break; + case 4294960000: { + OptionalInt32 = input.ReadInt32(); + break; + } + case 4294960008: { + Fixed32 = input.ReadInt32(); + break; + } + case 4294960018: + case 4294960016: { + repeatedInt32_.AddEntriesFrom(input, _repeated_repeatedInt32_codec); + break; + } + case 4294960026: + case 4294960024: { + packedInt32_.AddEntriesFrom(input, _repeated_packedInt32_codec); + break; + } + case 4294960032: { + OptionalEnum = (global::Google.Protobuf.TestProtos.Proto2.ForeignEnum) input.ReadEnum(); + break; + } + case 4294960042: { + OptionalString = input.ReadString(); + break; + } + case 4294960050: { + OptionalBytes = input.ReadBytes(); + break; + } + case 4294960058: { + if (optionalMessage_ == null) { + OptionalMessage = new global::Google.Protobuf.TestProtos.Proto2.ForeignMessage(); + } + input.ReadMessage(OptionalMessage); + break; + } + case 4294960067: { + if (!HasOptionalGroup) { + OptionalGroup = new global::Google.Protobuf.TestProtos.Proto2.TestHugeFieldNumbers.Types.OptionalGroup(); + } + input.ReadGroup(OptionalGroup); + break; + } + case 4294960082: { + stringStringMap_.AddEntriesFrom(input, _map_stringStringMap_codec); + break; + } + case 4294960088: { + OneofUint32 = input.ReadUInt32(); + break; + } + case 4294960098: { + global::Google.Protobuf.TestProtos.Proto2.TestAllTypes subBuilder = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + if (oneofFieldCase_ == OneofFieldOneofCase.OneofTestAllTypes) { + subBuilder.MergeFrom(OneofTestAllTypes); + } + input.ReadMessage(subBuilder); + OneofTestAllTypes = subBuilder; + break; + } + case 4294960106: { + OneofString = input.ReadString(); + break; + } + case 4294960114: { + OneofBytes = input.ReadBytes(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + } + break; + case 4294960000: { + OptionalInt32 = input.ReadInt32(); + break; + } + case 4294960008: { + Fixed32 = input.ReadInt32(); + break; + } + case 4294960018: + case 4294960016: { + repeatedInt32_.AddEntriesFrom(ref input, _repeated_repeatedInt32_codec); + break; + } + case 4294960026: + case 4294960024: { + packedInt32_.AddEntriesFrom(ref input, _repeated_packedInt32_codec); + break; + } + case 4294960032: { + OptionalEnum = (global::Google.Protobuf.TestProtos.Proto2.ForeignEnum) input.ReadEnum(); + break; + } + case 4294960042: { + OptionalString = input.ReadString(); + break; + } + case 4294960050: { + OptionalBytes = input.ReadBytes(); + break; + } + case 4294960058: { + if (optionalMessage_ == null) { + OptionalMessage = new global::Google.Protobuf.TestProtos.Proto2.ForeignMessage(); + } + input.ReadMessage(OptionalMessage); + break; + } + case 4294960067: { + if (!HasOptionalGroup) { + OptionalGroup = new global::Google.Protobuf.TestProtos.Proto2.TestHugeFieldNumbers.Types.OptionalGroup(); + } + input.ReadGroup(OptionalGroup); + break; + } + case 4294960082: { + stringStringMap_.AddEntriesFrom(ref input, _map_stringStringMap_codec); + break; + } + case 4294960088: { + OneofUint32 = input.ReadUInt32(); + break; + } + case 4294960098: { + global::Google.Protobuf.TestProtos.Proto2.TestAllTypes subBuilder = new global::Google.Protobuf.TestProtos.Proto2.TestAllTypes(); + if (oneofFieldCase_ == OneofFieldOneofCase.OneofTestAllTypes) { + subBuilder.MergeFrom(OneofTestAllTypes); + } + input.ReadMessage(subBuilder); + OneofTestAllTypes = subBuilder; + break; + } + case 4294960106: { + OneofString = input.ReadString(); + break; + } + case 4294960114: { + OneofBytes = input.ReadBytes(); + break; + } + } + } + } + #endif + + public TValue GetExtension(pb::Extension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetOrInitializeExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.GetOrInitialize(ref _extensions, extension); + } + public void SetExtension(pb::Extension extension, TValue value) { + pb::ExtensionSet.Set(ref _extensions, extension, value); + } + public bool HasExtension(pb::Extension extension) { + return pb::ExtensionSet.Has(ref _extensions, extension); + } + public void ClearExtension(pb::Extension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + public void ClearExtension(pb::RepeatedExtension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + + #region Nested types + /// Container for nested types declared in the TestHugeFieldNumbers message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public sealed partial class OptionalGroup : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new OptionalGroup()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.TestHugeFieldNumbers.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OptionalGroup() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OptionalGroup(OptionalGroup other) : this() { + _hasBits0 = other._hasBits0; + groupA_ = other.groupA_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OptionalGroup Clone() { + return new OptionalGroup(this); + } + + /// Field number for the "group_a" field. + public const int GroupAFieldNumber = 536870009; + private readonly static int GroupADefaultValue = 0; + + private int groupA_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int GroupA { + get { if ((_hasBits0 & 1) != 0) { return groupA_; } else { return GroupADefaultValue; } } + set { + _hasBits0 |= 1; + groupA_ = value; + } + } + /// Gets whether the "group_a" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasGroupA { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "group_a" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearGroupA() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as OptionalGroup); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(OptionalGroup other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (GroupA != other.GroupA) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasGroupA) hash ^= GroupA.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasGroupA) { + output.WriteRawTag(200, 199, 255, 255, 15); + output.WriteInt32(GroupA); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasGroupA) { + output.WriteRawTag(200, 199, 255, 255, 15); + output.WriteInt32(GroupA); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasGroupA) { + size += 5 + pb::CodedOutputStream.ComputeInt32Size(GroupA); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(OptionalGroup other) { + if (other == null) { + return; + } + if (other.HasGroupA) { + GroupA = other.GroupA; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 4294960068: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 4294960072: { + GroupA = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + case 4294960068: + return; + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 4294960072: { + GroupA = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + } + #endregion + + } + + public sealed partial class TestExtensionInsideTable : pb::IExtendableMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestExtensionInsideTable()); + private pb::UnknownFieldSet _unknownFields; + private pb::ExtensionSet _extensions; + private pb::ExtensionSet _Extensions { get { return _extensions; } } + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.Proto2.UnittestReflection.Descriptor.MessageTypes[64]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestExtensionInsideTable() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestExtensionInsideTable(TestExtensionInsideTable other) : this() { + _hasBits0 = other._hasBits0; + field1_ = other.field1_; + field2_ = other.field2_; + field3_ = other.field3_; + field4_ = other.field4_; + field6_ = other.field6_; + field7_ = other.field7_; + field8_ = other.field8_; + field9_ = other.field9_; + field10_ = other.field10_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + _extensions = pb::ExtensionSet.Clone(other._extensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestExtensionInsideTable Clone() { + return new TestExtensionInsideTable(this); + } + + /// Field number for the "field1" field. + public const int Field1FieldNumber = 1; + private readonly static int Field1DefaultValue = 0; + + private int field1_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Field1 { + get { if ((_hasBits0 & 1) != 0) { return field1_; } else { return Field1DefaultValue; } } + set { + _hasBits0 |= 1; + field1_ = value; + } + } + /// Gets whether the "field1" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasField1 { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "field1" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearField1() { + _hasBits0 &= ~1; + } + + /// Field number for the "field2" field. + public const int Field2FieldNumber = 2; + private readonly static int Field2DefaultValue = 0; + + private int field2_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Field2 { + get { if ((_hasBits0 & 2) != 0) { return field2_; } else { return Field2DefaultValue; } } + set { + _hasBits0 |= 2; + field2_ = value; + } + } + /// Gets whether the "field2" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasField2 { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "field2" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearField2() { + _hasBits0 &= ~2; + } + + /// Field number for the "field3" field. + public const int Field3FieldNumber = 3; + private readonly static int Field3DefaultValue = 0; + + private int field3_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Field3 { + get { if ((_hasBits0 & 4) != 0) { return field3_; } else { return Field3DefaultValue; } } + set { + _hasBits0 |= 4; + field3_ = value; + } + } + /// Gets whether the "field3" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasField3 { + get { return (_hasBits0 & 4) != 0; } + } + /// Clears the value of the "field3" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearField3() { + _hasBits0 &= ~4; + } + + /// Field number for the "field4" field. + public const int Field4FieldNumber = 4; + private readonly static int Field4DefaultValue = 0; + + private int field4_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Field4 { + get { if ((_hasBits0 & 8) != 0) { return field4_; } else { return Field4DefaultValue; } } + set { + _hasBits0 |= 8; + field4_ = value; + } + } + /// Gets whether the "field4" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasField4 { + get { return (_hasBits0 & 8) != 0; } + } + /// Clears the value of the "field4" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearField4() { + _hasBits0 &= ~8; + } + + /// Field number for the "field6" field. + public const int Field6FieldNumber = 6; + private readonly static int Field6DefaultValue = 0; + + private int field6_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Field6 { + get { if ((_hasBits0 & 16) != 0) { return field6_; } else { return Field6DefaultValue; } } + set { + _hasBits0 |= 16; + field6_ = value; + } + } + /// Gets whether the "field6" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasField6 { + get { return (_hasBits0 & 16) != 0; } + } + /// Clears the value of the "field6" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearField6() { + _hasBits0 &= ~16; + } + + /// Field number for the "field7" field. + public const int Field7FieldNumber = 7; + private readonly static int Field7DefaultValue = 0; + + private int field7_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Field7 { + get { if ((_hasBits0 & 32) != 0) { return field7_; } else { return Field7DefaultValue; } } + set { + _hasBits0 |= 32; + field7_ = value; + } + } + /// Gets whether the "field7" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasField7 { + get { return (_hasBits0 & 32) != 0; } + } + /// Clears the value of the "field7" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearField7() { + _hasBits0 &= ~32; + } + + /// Field number for the "field8" field. + public const int Field8FieldNumber = 8; + private readonly static int Field8DefaultValue = 0; + + private int field8_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Field8 { + get { if ((_hasBits0 & 64) != 0) { return field8_; } else { return Field8DefaultValue; } } + set { + _hasBits0 |= 64; + field8_ = value; + } + } + /// Gets whether the "field8" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasField8 { + get { return (_hasBits0 & 64) != 0; } + } + /// Clears the value of the "field8" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearField8() { + _hasBits0 &= ~64; + } + + /// Field number for the "field9" field. + public const int Field9FieldNumber = 9; + private readonly static int Field9DefaultValue = 0; + + private int field9_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Field9 { + get { if ((_hasBits0 & 128) != 0) { return field9_; } else { return Field9DefaultValue; } } + set { + _hasBits0 |= 128; + field9_ = value; + } + } + /// Gets whether the "field9" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasField9 { + get { return (_hasBits0 & 128) != 0; } + } + /// Clears the value of the "field9" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearField9() { + _hasBits0 &= ~128; + } + + /// Field number for the "field10" field. + public const int Field10FieldNumber = 10; + private readonly static int Field10DefaultValue = 0; + + private int field10_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Field10 { + get { if ((_hasBits0 & 256) != 0) { return field10_; } else { return Field10DefaultValue; } } + set { + _hasBits0 |= 256; + field10_ = value; + } + } + /// Gets whether the "field10" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasField10 { + get { return (_hasBits0 & 256) != 0; } + } + /// Clears the value of the "field10" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearField10() { + _hasBits0 &= ~256; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestExtensionInsideTable); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestExtensionInsideTable other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Field1 != other.Field1) return false; + if (Field2 != other.Field2) return false; + if (Field3 != other.Field3) return false; + if (Field4 != other.Field4) return false; + if (Field6 != other.Field6) return false; + if (Field7 != other.Field7) return false; + if (Field8 != other.Field8) return false; + if (Field9 != other.Field9) return false; + if (Field10 != other.Field10) return false; + if (!Equals(_extensions, other._extensions)) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasField1) hash ^= Field1.GetHashCode(); + if (HasField2) hash ^= Field2.GetHashCode(); + if (HasField3) hash ^= Field3.GetHashCode(); + if (HasField4) hash ^= Field4.GetHashCode(); + if (HasField6) hash ^= Field6.GetHashCode(); + if (HasField7) hash ^= Field7.GetHashCode(); + if (HasField8) hash ^= Field8.GetHashCode(); + if (HasField9) hash ^= Field9.GetHashCode(); + if (HasField10) hash ^= Field10.GetHashCode(); + if (_extensions != null) { + hash ^= _extensions.GetHashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasField1) { + output.WriteRawTag(8); + output.WriteInt32(Field1); + } + if (HasField2) { + output.WriteRawTag(16); + output.WriteInt32(Field2); + } + if (HasField3) { + output.WriteRawTag(24); + output.WriteInt32(Field3); + } + if (HasField4) { + output.WriteRawTag(32); + output.WriteInt32(Field4); + } + if (HasField6) { + output.WriteRawTag(48); + output.WriteInt32(Field6); + } + if (HasField7) { + output.WriteRawTag(56); + output.WriteInt32(Field7); + } + if (HasField8) { + output.WriteRawTag(64); + output.WriteInt32(Field8); + } + if (HasField9) { + output.WriteRawTag(72); + output.WriteInt32(Field9); + } + if (HasField10) { + output.WriteRawTag(80); + output.WriteInt32(Field10); + } + if (_extensions != null) { + _extensions.WriteTo(output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasField1) { + output.WriteRawTag(8); + output.WriteInt32(Field1); + } + if (HasField2) { + output.WriteRawTag(16); + output.WriteInt32(Field2); + } + if (HasField3) { + output.WriteRawTag(24); + output.WriteInt32(Field3); + } + if (HasField4) { + output.WriteRawTag(32); + output.WriteInt32(Field4); + } + if (HasField6) { + output.WriteRawTag(48); + output.WriteInt32(Field6); + } + if (HasField7) { + output.WriteRawTag(56); + output.WriteInt32(Field7); + } + if (HasField8) { + output.WriteRawTag(64); + output.WriteInt32(Field8); + } + if (HasField9) { + output.WriteRawTag(72); + output.WriteInt32(Field9); + } + if (HasField10) { + output.WriteRawTag(80); + output.WriteInt32(Field10); + } + if (_extensions != null) { + _extensions.WriteTo(ref output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasField1) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Field1); + } + if (HasField2) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Field2); + } + if (HasField3) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Field3); + } + if (HasField4) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Field4); + } + if (HasField6) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Field6); + } + if (HasField7) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Field7); + } + if (HasField8) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Field8); + } + if (HasField9) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Field9); + } + if (HasField10) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Field10); + } + if (_extensions != null) { + size += _extensions.CalculateSize(); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestExtensionInsideTable other) { + if (other == null) { + return; + } + if (other.HasField1) { + Field1 = other.Field1; + } + if (other.HasField2) { + Field2 = other.Field2; + } + if (other.HasField3) { + Field3 = other.Field3; + } + if (other.HasField4) { + Field4 = other.Field4; + } + if (other.HasField6) { + Field6 = other.Field6; + } + if (other.HasField7) { + Field7 = other.Field7; + } + if (other.HasField8) { + Field8 = other.Field8; + } + if (other.HasField9) { + Field9 = other.Field9; + } + if (other.HasField10) { + Field10 = other.Field10; + } + pb::ExtensionSet.MergeFrom(ref _extensions, other._extensions); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + } + break; + case 8: { + Field1 = input.ReadInt32(); + break; + } + case 16: { + Field2 = input.ReadInt32(); + break; + } + case 24: { + Field3 = input.ReadInt32(); + break; + } + case 32: { + Field4 = input.ReadInt32(); + break; + } + case 48: { + Field6 = input.ReadInt32(); + break; + } + case 56: { + Field7 = input.ReadInt32(); + break; + } + case 64: { + Field8 = input.ReadInt32(); + break; + } + case 72: { + Field9 = input.ReadInt32(); + break; + } + case 80: { + Field10 = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + } + break; + case 8: { + Field1 = input.ReadInt32(); + break; + } + case 16: { + Field2 = input.ReadInt32(); + break; + } + case 24: { + Field3 = input.ReadInt32(); + break; + } + case 32: { + Field4 = input.ReadInt32(); + break; + } + case 48: { + Field6 = input.ReadInt32(); + break; + } + case 56: { + Field7 = input.ReadInt32(); + break; + } + case 64: { + Field8 = input.ReadInt32(); + break; + } + case 72: { + Field9 = input.ReadInt32(); + break; + } + case 80: { + Field10 = input.ReadInt32(); + break; + } + } + } + } + #endif + + public TValue GetExtension(pb::Extension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetOrInitializeExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.GetOrInitialize(ref _extensions, extension); + } + public void SetExtension(pb::Extension extension, TValue value) { + pb::ExtensionSet.Set(ref _extensions, extension, value); + } + public bool HasExtension(pb::Extension extension) { + return pb::ExtensionSet.Has(ref _extensions, extension); + } + public void ClearExtension(pb::Extension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + public void ClearExtension(pb::RepeatedExtension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssue6936A.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssue6936A.cs new file mode 100644 index 0000000..56fde4f --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssue6936A.cs @@ -0,0 +1,46 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: unittest_issue6936_a.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace UnitTest.Issues.TestProtos { + + /// Holder for reflection information generated from unittest_issue6936_a.proto + public static partial class UnittestIssue6936AReflection { + + #region Descriptor + /// File descriptor for unittest_issue6936_a.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static UnittestIssue6936AReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Chp1bml0dGVzdF9pc3N1ZTY5MzZfYS5wcm90bxIPdW5pdHRlc3RfaXNzdWVz", + "GiBnb29nbGUvcHJvdG9idWYvZGVzY3JpcHRvci5wcm90bzouCgNvcHQSHy5n", + "b29nbGUucHJvdG9idWYuTWVzc2FnZU9wdGlvbnMY0IYDIAEoCUIdqgIaVW5p", + "dFRlc3QuSXNzdWVzLlRlc3RQcm90b3NiBnByb3RvMw==")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor, }, + new pbr::GeneratedClrTypeInfo(null, new pb::Extension[] { UnittestIssue6936AExtensions.Opt }, null)); + } + #endregion + + } + /// Holder for extension identifiers generated from the top level of unittest_issue6936_a.proto + public static partial class UnittestIssue6936AExtensions { + public static readonly pb::Extension Opt = + new pb::Extension(50000, pb::FieldCodec.ForString(400002, "")); + } + +} + +#endregion Designer generated code diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/Buffers/ArrayBufferWriter.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/Buffers/ArrayBufferWriter.cs new file mode 100644 index 0000000..a36a951 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/Buffers/ArrayBufferWriter.cs @@ -0,0 +1,225 @@ +#region Copyright notice and license +// 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. +#endregion + +using System; +using System.Buffers; +using System.Diagnostics; + +namespace Google.Protobuf.Buffers +{ + /// + /// Represents a heap-based, array-backed output sink into which data can be written. + /// + /// ArrayBufferWriter is originally from corefx, and has been contributed to Protobuf + /// https://github.com/dotnet/runtime/blob/071da4c41aa808c949a773b92dca6f88de9d11f3/src/libraries/Common/src/System/Buffers/ArrayBufferWriter.cs + /// + internal sealed class TestArrayBufferWriter : IBufferWriter + { + private T[] _buffer; + private int _index; + + private const int DefaultInitialBufferSize = 256; + + /// + /// Creates an instance of an , in which data can be written to, + /// with the default initial capacity. + /// + public TestArrayBufferWriter() + { + _buffer = new T[0]; + _index = 0; + } + + /// + /// Useful for testing writing to buffer writer with a lot of small segments. + /// If set, it limits the max number of bytes by which the buffer grows by at once. + /// + public int? MaxGrowBy { get; set; } + + /// + /// Creates an instance of an , in which data can be written to, + /// with an initial capacity specified. + /// + /// The minimum capacity with which to initialize the underlying buffer. + /// + /// Thrown when is not positive (i.e. less than or equal to 0). + /// + public TestArrayBufferWriter(int initialCapacity) + { + if (initialCapacity <= 0) + throw new ArgumentException(nameof(initialCapacity)); + + _buffer = new T[initialCapacity]; + _index = 0; + } + + /// + /// Returns the data written to the underlying buffer so far, as a . + /// + public ReadOnlyMemory WrittenMemory => _buffer.AsMemory(0, _index); + + /// + /// Returns the data written to the underlying buffer so far, as a . + /// + public ReadOnlySpan WrittenSpan => _buffer.AsSpan(0, _index); + + /// + /// Returns the amount of data written to the underlying buffer so far. + /// + public int WrittenCount => _index; + + /// + /// Returns the total amount of space within the underlying buffer. + /// + public int Capacity => _buffer.Length; + + /// + /// Returns the amount of space available that can still be written into without forcing the underlying buffer to grow. + /// + public int FreeCapacity => _buffer.Length - _index; + + /// + /// Clears the data written to the underlying buffer. + /// + /// + /// You must clear the before trying to re-use it. + /// + public void Clear() + { + Debug.Assert(_buffer.Length >= _index); + _buffer.AsSpan(0, _index).Clear(); + _index = 0; + } + + /// + /// Notifies that amount of data was written to the output / + /// + /// + /// Thrown when is negative. + /// + /// + /// Thrown when attempting to advance past the end of the underlying buffer. + /// + /// + /// You must request a new buffer after calling Advance to continue writing more data and cannot write to a previously acquired buffer. + /// + public void Advance(int count) + { + if (count < 0) + throw new ArgumentException(nameof(count)); + + if (_index > _buffer.Length - count) + throw new InvalidOperationException("Advanced past capacity."); + + _index += count; + } + + /// + /// Returns a to write to that is at least the requested length (specified by ). + /// If no is provided (or it's equal to 0), some non-empty buffer is returned. + /// + /// + /// Thrown when is negative. + /// + /// + /// This will never return an empty . + /// + /// + /// There is no guarantee that successive calls will return the same buffer or the same-sized buffer. + /// + /// + /// You must request a new buffer after calling Advance to continue writing more data and cannot write to a previously acquired buffer. + /// + public Memory GetMemory(int sizeHint = 0) + { + CheckAndResizeBuffer(sizeHint); + Debug.Assert(_buffer.Length > _index); + return _buffer.AsMemory(_index); + } + + /// + /// Returns a to write to that is at least the requested length (specified by ). + /// If no is provided (or it's equal to 0), some non-empty buffer is returned. + /// + /// + /// Thrown when is negative. + /// + /// + /// This will never return an empty . + /// + /// + /// There is no guarantee that successive calls will return the same buffer or the same-sized buffer. + /// + /// + /// You must request a new buffer after calling Advance to continue writing more data and cannot write to a previously acquired buffer. + /// + public Span GetSpan(int sizeHint = 0) + { + CheckAndResizeBuffer(sizeHint); + Debug.Assert(_buffer.Length > _index); + return _buffer.AsSpan(_index); + } + + private void CheckAndResizeBuffer(int sizeHint) + { + if (sizeHint < 0) + throw new ArgumentException(nameof(sizeHint)); + + if (sizeHint == 0) + { + sizeHint = 1; + } + + if (sizeHint > FreeCapacity) + { + int growBy = Math.Max(sizeHint, _buffer.Length); + + if (_buffer.Length == 0) + { + growBy = Math.Max(growBy, DefaultInitialBufferSize); + } + + // enable tests that write to small buffer segments + if (MaxGrowBy.HasValue && growBy > MaxGrowBy.Value) + { + growBy = MaxGrowBy.Value; + } + + int newSize = checked(_buffer.Length + growBy); + + Array.Resize(ref _buffer, newSize); + } + + Debug.Assert(FreeCapacity > 0 && FreeCapacity >= sizeHint); + } + } +} \ No newline at end of file diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs new file mode 100644 index 0000000..d4c63dc --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs @@ -0,0 +1,661 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; +using System.IO; +using System.Collections.Generic; +using Google.Protobuf.TestProtos; +using NUnit.Framework; +using System.Collections; +using System.Linq; + +namespace Google.Protobuf.Collections +{ + /// + /// Tests for MapField which aren't reliant on the encoded format - + /// tests for serialization/deserialization are part of GeneratedMessageTest. + /// + public class MapFieldTest + { + [Test] + public void Clone_ClonesMessages() + { + var message = new ForeignMessage { C = 20 }; + var map = new MapField { { "x", message } }; + var clone = map.Clone(); + map["x"].C = 30; + Assert.AreEqual(20, clone["x"].C); + } + + [Test] + public void NullValuesProhibited() + { + TestNullValues(0); + TestNullValues(""); + TestNullValues(new TestAllTypes()); + } + + private void TestNullValues(T nonNullValue) + { + var map = new MapField(); + var nullValue = (T) (object) null; + Assert.Throws(() => map.Add(0, nullValue)); + Assert.Throws(() => map[0] = nullValue); + map.Add(1, nonNullValue); + map[1] = nonNullValue; + } + + [Test] + public void Add_ForbidsNullKeys() + { + var map = new MapField(); + Assert.Throws(() => map.Add(null, new ForeignMessage())); + } + + [Test] + public void Indexer_ForbidsNullKeys() + { + var map = new MapField(); + Assert.Throws(() => map[null] = new ForeignMessage()); + } + + [Test] + public void AddPreservesInsertionOrder() + { + var map = new MapField(); + map.Add("a", "v1"); + map.Add("b", "v2"); + map.Add("c", "v3"); + map.Remove("b"); + map.Add("d", "v4"); + CollectionAssert.AreEqual(new[] { "a", "c", "d" }, map.Keys); + CollectionAssert.AreEqual(new[] { "v1", "v3", "v4" }, map.Values); + } + + [Test] + public void EqualityIsOrderInsensitive() + { + var map1 = new MapField(); + map1.Add("a", "v1"); + map1.Add("b", "v2"); + + var map2 = new MapField(); + map2.Add("b", "v2"); + map2.Add("a", "v1"); + + EqualityTester.AssertEquality(map1, map2); + } + + [Test] + public void EqualityIsKeySensitive() + { + var map1 = new MapField(); + map1.Add("first key", "v1"); + map1.Add("second key", "v2"); + + var map2 = new MapField(); + map2.Add("third key", "v1"); + map2.Add("fourth key", "v2"); + + EqualityTester.AssertInequality(map1, map2); + } + + [Test] + public void Equality_Simple() + { + var map = new MapField(); + EqualityTester.AssertEquality(map, map); + EqualityTester.AssertInequality(map, null); + Assert.IsFalse(map.Equals(new object())); + } + + [Test] + public void EqualityIsValueSensitive() + { + // Note: Without some care, it's a little easier than one might + // hope to see hash collisions, but only in some environments... + var map1 = new MapField(); + map1.Add("a", "first value"); + map1.Add("b", "second value"); + + var map2 = new MapField(); + map2.Add("a", "third value"); + map2.Add("b", "fourth value"); + + EqualityTester.AssertInequality(map1, map2); + } + + [Test] + public void Add_Dictionary() + { + var map1 = new MapField + { + { "x", "y" }, + { "a", "b" } + }; + var map2 = new MapField + { + { "before", "" }, + map1, + { "after", "" } + }; + var expected = new MapField + { + { "before", "" }, + { "x", "y" }, + { "a", "b" }, + { "after", "" } + }; + Assert.AreEqual(expected, map2); + CollectionAssert.AreEqual(new[] { "before", "x", "a", "after" }, map2.Keys); + } + + // General IDictionary behavior tests + [Test] + public void Add_KeyAlreadyExists() + { + var map = new MapField(); + map.Add("foo", "bar"); + Assert.Throws(() => map.Add("foo", "baz")); + } + + [Test] + public void Add_Pair() + { + var map = new MapField(); + ICollection> collection = map; + collection.Add(NewKeyValuePair("x", "y")); + Assert.AreEqual("y", map["x"]); + Assert.Throws(() => collection.Add(NewKeyValuePair("x", "z"))); + } + + [Test] + public void Contains_Pair() + { + var map = new MapField { { "x", "y" } }; + ICollection> collection = map; + Assert.IsTrue(collection.Contains(NewKeyValuePair("x", "y"))); + Assert.IsFalse(collection.Contains(NewKeyValuePair("x", "z"))); + Assert.IsFalse(collection.Contains(NewKeyValuePair("z", "y"))); + } + + [Test] + public void Remove_Key() + { + var map = new MapField(); + map.Add("foo", "bar"); + Assert.AreEqual(1, map.Count); + Assert.IsFalse(map.Remove("missing")); + Assert.AreEqual(1, map.Count); + Assert.IsTrue(map.Remove("foo")); + Assert.AreEqual(0, map.Count); + Assert.Throws(() => map.Remove(null)); + } + + [Test] + public void Remove_Pair() + { + var map = new MapField(); + map.Add("foo", "bar"); + ICollection> collection = map; + Assert.AreEqual(1, map.Count); + Assert.IsFalse(collection.Remove(NewKeyValuePair("wrong key", "bar"))); + Assert.AreEqual(1, map.Count); + Assert.IsFalse(collection.Remove(NewKeyValuePair("foo", "wrong value"))); + Assert.AreEqual(1, map.Count); + Assert.IsTrue(collection.Remove(NewKeyValuePair("foo", "bar"))); + Assert.AreEqual(0, map.Count); + Assert.Throws(() => collection.Remove(new KeyValuePair(null, ""))); + } + + [Test] + public void CopyTo_Pair() + { + var map = new MapField(); + map.Add("foo", "bar"); + ICollection> collection = map; + KeyValuePair[] array = new KeyValuePair[3]; + collection.CopyTo(array, 1); + Assert.AreEqual(NewKeyValuePair("foo", "bar"), array[1]); + } + + [Test] + public void Clear() + { + var map = new MapField { { "x", "y" } }; + Assert.AreEqual(1, map.Count); + map.Clear(); + Assert.AreEqual(0, map.Count); + map.Add("x", "y"); + Assert.AreEqual(1, map.Count); + } + + [Test] + public void Indexer_Get() + { + var map = new MapField { { "x", "y" } }; + Assert.AreEqual("y", map["x"]); + Assert.Throws(() => { var ignored = map["z"]; }); + } + + [Test] + public void Indexer_Set() + { + var map = new MapField(); + map["x"] = "y"; + Assert.AreEqual("y", map["x"]); + map["x"] = "z"; // This won't throw, unlike Add. + Assert.AreEqual("z", map["x"]); + } + + [Test] + public void GetEnumerator_NonGeneric() + { + IEnumerable map = new MapField { { "x", "y" } }; + CollectionAssert.AreEqual(new[] { new KeyValuePair("x", "y") }, + map.Cast().ToList()); + } + + // Test for the explicitly-implemented non-generic IDictionary interface + [Test] + public void IDictionary_GetEnumerator() + { + IDictionary map = new MapField { { "x", "y" } }; + var enumerator = map.GetEnumerator(); + + // Commented assertions show an ideal situation - it looks like + // the LinkedList enumerator doesn't throw when you ask for the current entry + // at an inappropriate time; fixing this would be more work than it's worth. + // Assert.Throws(() => enumerator.Current.GetHashCode()); + Assert.IsTrue(enumerator.MoveNext()); + Assert.AreEqual("x", enumerator.Key); + Assert.AreEqual("y", enumerator.Value); + Assert.AreEqual(new DictionaryEntry("x", "y"), enumerator.Current); + Assert.AreEqual(new DictionaryEntry("x", "y"), enumerator.Entry); + Assert.IsFalse(enumerator.MoveNext()); + // Assert.Throws(() => enumerator.Current.GetHashCode()); + enumerator.Reset(); + // Assert.Throws(() => enumerator.Current.GetHashCode()); + Assert.IsTrue(enumerator.MoveNext()); + Assert.AreEqual("x", enumerator.Key); // Assume the rest are okay + } + + [Test] + public void IDictionary_Add() + { + var map = new MapField { { "x", "y" } }; + IDictionary dictionary = map; + dictionary.Add("a", "b"); + Assert.AreEqual("b", map["a"]); + Assert.Throws(() => dictionary.Add("a", "duplicate")); + Assert.Throws(() => dictionary.Add(new object(), "key is bad")); + Assert.Throws(() => dictionary.Add("value is bad", new object())); + } + + [Test] + public void IDictionary_Contains() + { + var map = new MapField { { "x", "y" } }; + IDictionary dictionary = map; + + Assert.IsFalse(dictionary.Contains("a")); + Assert.IsFalse(dictionary.Contains(5)); + // Surprising, but IDictionary.Contains is only about keys. + Assert.IsFalse(dictionary.Contains(new DictionaryEntry("x", "y"))); + Assert.IsTrue(dictionary.Contains("x")); + } + + [Test] + public void IDictionary_Remove() + { + var map = new MapField { { "x", "y" } }; + IDictionary dictionary = map; + dictionary.Remove("a"); + Assert.AreEqual(1, dictionary.Count); + dictionary.Remove(5); + Assert.AreEqual(1, dictionary.Count); + dictionary.Remove(new DictionaryEntry("x", "y")); + Assert.AreEqual(1, dictionary.Count); + dictionary.Remove("x"); + Assert.AreEqual(0, dictionary.Count); + Assert.Throws(() => dictionary.Remove(null)); + } + + [Test] + public void IDictionary_CopyTo() + { + var map = new MapField { { "x", "y" } }; + IDictionary dictionary = map; + var array = new DictionaryEntry[3]; + dictionary.CopyTo(array, 1); + CollectionAssert.AreEqual(new[] { default(DictionaryEntry), new DictionaryEntry("x", "y"), default(DictionaryEntry) }, + array); + var objectArray = new object[3]; + dictionary.CopyTo(objectArray, 1); + CollectionAssert.AreEqual(new object[] { null, new DictionaryEntry("x", "y"), null }, + objectArray); + } + + [Test] + public void IDictionary_IsFixedSize() + { + var map = new MapField { { "x", "y" } }; + IDictionary dictionary = map; + Assert.IsFalse(dictionary.IsFixedSize); + } + + [Test] + public void IDictionary_Keys() + { + IDictionary dictionary = new MapField { { "x", "y" } }; + CollectionAssert.AreEqual(new[] { "x" }, dictionary.Keys); + } + + [Test] + public void IDictionary_Values() + { + IDictionary dictionary = new MapField { { "x", "y" } }; + CollectionAssert.AreEqual(new[] { "y" }, dictionary.Values); + } + + [Test] + public void IDictionary_IsSynchronized() + { + IDictionary dictionary = new MapField { { "x", "y" } }; + Assert.IsFalse(dictionary.IsSynchronized); + } + + [Test] + public void IDictionary_SyncRoot() + { + IDictionary dictionary = new MapField { { "x", "y" } }; + Assert.AreSame(dictionary, dictionary.SyncRoot); + } + + [Test] + public void IDictionary_Indexer_Get() + { + IDictionary dictionary = new MapField { { "x", "y" } }; + Assert.AreEqual("y", dictionary["x"]); + Assert.IsNull(dictionary["a"]); + Assert.IsNull(dictionary[5]); + Assert.Throws(() => dictionary[null].GetHashCode()); + } + + [Test] + public void IDictionary_Indexer_Set() + { + var map = new MapField { { "x", "y" } }; + IDictionary dictionary = map; + map["a"] = "b"; + Assert.AreEqual("b", map["a"]); + map["a"] = "c"; + Assert.AreEqual("c", map["a"]); + Assert.Throws(() => dictionary[5] = "x"); + Assert.Throws(() => dictionary["x"] = 5); + Assert.Throws(() => dictionary[null] = "z"); + Assert.Throws(() => dictionary["x"] = null); + } + + [Test] + public void KeysReturnsLiveView() + { + var map = new MapField(); + var keys = map.Keys; + CollectionAssert.AreEqual(new string[0], keys); + map["foo"] = "bar"; + map["x"] = "y"; + CollectionAssert.AreEqual(new[] { "foo", "x" }, keys); + } + + [Test] + public void ValuesReturnsLiveView() + { + var map = new MapField(); + var values = map.Values; + CollectionAssert.AreEqual(new string[0], values); + map["foo"] = "bar"; + map["x"] = "y"; + CollectionAssert.AreEqual(new[] { "bar", "y" }, values); + } + + // Just test keys - we know the implementation is the same for values + [Test] + public void ViewsAreReadOnly() + { + var map = new MapField(); + var keys = map.Keys; + Assert.IsTrue(keys.IsReadOnly); + Assert.Throws(() => keys.Clear()); + Assert.Throws(() => keys.Remove("a")); + Assert.Throws(() => keys.Add("a")); + } + + // Just test keys - we know the implementation is the same for values + [Test] + public void ViewCopyTo() + { + var map = new MapField { { "foo", "bar" }, { "x", "y" } }; + var keys = map.Keys; + var array = new string[4]; + Assert.Throws(() => keys.CopyTo(array, 3)); + Assert.Throws(() => keys.CopyTo(array, -1)); + keys.CopyTo(array, 1); + CollectionAssert.AreEqual(new[] { null, "foo", "x", null }, array); + } + + // Just test keys - we know the implementation is the same for values + [Test] + public void NonGenericViewCopyTo() + { + IDictionary map = new MapField { { "foo", "bar" }, { "x", "y" } }; + ICollection keys = map.Keys; + // Note the use of the Array type here rather than string[] + Array array = new string[4]; + Assert.Throws(() => keys.CopyTo(array, 3)); + Assert.Throws(() => keys.CopyTo(array, -1)); + keys.CopyTo(array, 1); + CollectionAssert.AreEqual(new[] { null, "foo", "x", null }, array); + } + + [Test] + public void KeysContains() + { + var map = new MapField { { "foo", "bar" }, { "x", "y" } }; + var keys = map.Keys; + Assert.IsTrue(keys.Contains("foo")); + Assert.IsFalse(keys.Contains("bar")); // It's a value! + Assert.IsFalse(keys.Contains("1")); + // Keys can't be null, so we should prevent contains check + Assert.Throws(() => keys.Contains(null)); + } + + [Test] + public void KeysCopyTo() + { + var map = new MapField { { "foo", "bar" }, { "x", "y" } }; + var keys = map.Keys.ToArray(); // Uses CopyTo internally + CollectionAssert.AreEquivalent(new[] { "foo", "x" }, keys); + } + + [Test] + public void ValuesContains() + { + var map = new MapField { { "foo", "bar" }, { "x", "y" } }; + var values = map.Values; + Assert.IsTrue(values.Contains("bar")); + Assert.IsFalse(values.Contains("foo")); // It's a key! + Assert.IsFalse(values.Contains("1")); + // Values can be null, so this makes sense + Assert.IsFalse(values.Contains(null)); + } + + [Test] + public void ValuesCopyTo() + { + var map = new MapField { { "foo", "bar" }, { "x", "y" } }; + var values = map.Values.ToArray(); // Uses CopyTo internally + CollectionAssert.AreEquivalent(new[] { "bar", "y" }, values); + } + + [Test] + public void ToString_StringToString() + { + var map = new MapField { { "foo", "bar" }, { "x", "y" } }; + Assert.AreEqual("{ \"foo\": \"bar\", \"x\": \"y\" }", map.ToString()); + } + + [Test] + public void ToString_UnsupportedKeyType() + { + var map = new MapField { { 10, "foo" } }; + Assert.Throws(() => map.ToString()); + } + + [Test] + public void NaNValuesComparedBitwise() + { + var map1 = new MapField + { + { "x", SampleNaNs.Regular }, + { "y", SampleNaNs.SignallingFlipped } + }; + + var map2 = new MapField + { + { "x", SampleNaNs.Regular }, + { "y", SampleNaNs.PayloadFlipped } + }; + + var map3 = new MapField + { + { "x", SampleNaNs.Regular }, + { "y", SampleNaNs.SignallingFlipped } + }; + + EqualityTester.AssertInequality(map1, map2); + EqualityTester.AssertEquality(map1, map3); + Assert.True(map1.Values.Contains(SampleNaNs.SignallingFlipped)); + Assert.False(map2.Values.Contains(SampleNaNs.SignallingFlipped)); + } + + // This wouldn't usually happen, as protos can't use doubles as map keys, + // but let's be consistent. + [Test] + public void NaNKeysComparedBitwise() + { + var map = new MapField + { + { SampleNaNs.Regular, "x" }, + { SampleNaNs.SignallingFlipped, "y" } + }; + Assert.AreEqual("x", map[SampleNaNs.Regular]); + Assert.AreEqual("y", map[SampleNaNs.SignallingFlipped]); + string ignored; + Assert.False(map.TryGetValue(SampleNaNs.PayloadFlipped, out ignored)); + } + + [Test] + public void AddEntriesFrom_CodedInputStream() + { + // map will have string key and string value + var keyTag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); + var valueTag = WireFormat.MakeTag(2, WireFormat.WireType.LengthDelimited); + + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + output.WriteLength(20); // total of keyTag + key + valueTag + value + output.WriteTag(keyTag); + output.WriteString("the_key"); + output.WriteTag(valueTag); + output.WriteString("the_value"); + output.Flush(); + + var field = new MapField(); + var mapCodec = new MapField.Codec(FieldCodec.ForString(keyTag, ""), FieldCodec.ForString(valueTag, ""), 10); + var input = new CodedInputStream(memoryStream.ToArray()); + + // test the legacy overload of AddEntriesFrom that takes a CodedInputStream + field.AddEntriesFrom(input, mapCodec); + CollectionAssert.AreEquivalent(new[] { "the_key" }, field.Keys); + CollectionAssert.AreEquivalent(new[] { "the_value" }, field.Values); + Assert.IsTrue(input.IsAtEnd); + } + + [Test] + public void AddEntriesFrom_CodedInputStream_MissingKey() + { + // map will have string key and string value + var keyTag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); + var valueTag = WireFormat.MakeTag(2, WireFormat.WireType.LengthDelimited); + + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + output.WriteLength(11); // total of valueTag + value + output.WriteTag(valueTag); + output.WriteString("the_value"); + output.Flush(); + + Console.WriteLine(BitConverter.ToString(memoryStream.ToArray())); + + var field = new MapField(); + var mapCodec = new MapField.Codec(FieldCodec.ForString(keyTag, ""), FieldCodec.ForString(valueTag, ""), 10); + var input = new CodedInputStream(memoryStream.ToArray()); + + field.AddEntriesFrom(input, mapCodec); + CollectionAssert.AreEquivalent(new[] { "" }, field.Keys); + CollectionAssert.AreEquivalent(new[] { "the_value" }, field.Values); + Assert.IsTrue(input.IsAtEnd); + } + +#if !NET35 + [Test] + public void IDictionaryKeys_Equals_IReadOnlyDictionaryKeys() + { + var map = new MapField { { "foo", "bar" }, { "x", "y" } }; + CollectionAssert.AreEquivalent(((IDictionary)map).Keys, ((IReadOnlyDictionary)map).Keys); + } + + [Test] + public void IDictionaryValues_Equals_IReadOnlyDictionaryValues() + { + var map = new MapField { { "foo", "bar" }, { "x", "y" } }; + CollectionAssert.AreEquivalent(((IDictionary)map).Values, ((IReadOnlyDictionary)map).Values); + } +#endif + + private static KeyValuePair NewKeyValuePair(TKey key, TValue value) + { + return new KeyValuePair(key, value); + } + } +} diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/Compatibility/StreamExtensionsTest.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/Compatibility/StreamExtensionsTest.cs new file mode 100644 index 0000000..48c0725 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/Compatibility/StreamExtensionsTest.cs @@ -0,0 +1,67 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +#if NET35 +using System; +using System.IO; +using NUnit.Framework; +using Google.Protobuf.Compatibility; + +namespace Google.Protobuf.Test.Compatibility +{ + public class StreamExtensionsTest + { + [Test] + public void CopyToNullArgument() + { + var memoryStream = new MemoryStream(); + Assert.Throws(() => memoryStream.CopyTo(null)); + } + + [Test] + public void CopyToTest() + { + byte[] bytesToStream = new byte[] { 0x31, 0x08, 0xFF, 0x00 }; + Stream source = new MemoryStream(bytesToStream); + Stream destination = new MemoryStream((int)source.Length); + source.CopyTo(destination); + destination.Seek(0, SeekOrigin.Begin); + + Assert.AreEqual(0x31, destination.ReadByte()); + Assert.AreEqual(0x08, destination.ReadByte()); + Assert.AreEqual(0xFF, destination.ReadByte()); + Assert.AreEqual(0x00, destination.ReadByte()); + Assert.AreEqual(-1, destination.ReadByte()); + } + } +} +#endif diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj new file mode 100644 index 0000000..deb17e9 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj @@ -0,0 +1,31 @@ + + + + net451;netcoreapp3.1;net60 + ../../keys/Google.Protobuf.snk + true + False + True + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs new file mode 100644 index 0000000..1a65093 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs @@ -0,0 +1,698 @@ +#region Copyright notice and license +// 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. +#endregion + +using System; +using Google.Protobuf.TestProtos; +using NUnit.Framework; +using UnitTest.Issues.TestProtos; +using Google.Protobuf.WellKnownTypes; +using Google.Protobuf.Reflection; + +using static Google.Protobuf.JsonParserTest; // For WrapInQuotes +using System.IO; +using Google.Protobuf.Collections; +using ProtobufUnittest; + +namespace Google.Protobuf +{ + /// + /// Tests for the JSON formatter. Note that in these tests, double quotes are replaced with apostrophes + /// for the sake of readability (embedding \" everywhere is painful). See the AssertJson method for details. + /// + public class JsonFormatterTest + { + [Test] + public void DefaultValues_WhenOmitted() + { + var formatter = JsonFormatter.Default; + + AssertJson("{ }", formatter.Format(new ForeignMessage())); + AssertJson("{ }", formatter.Format(new TestAllTypes())); + AssertJson("{ }", formatter.Format(new TestMap())); + } + + [Test] + public void DefaultValues_WhenIncluded() + { + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); + AssertJson("{ 'c': 0 }", formatter.Format(new ForeignMessage())); + } + + [Test] + public void EnumAllowAlias() + { + var message = new TestEnumAllowAlias + { + Value = TestEnumWithDupValue.Foo2, + }; + var actualText = JsonFormatter.Default.Format(message); + var expectedText = "{ 'value': 'FOO1' }"; + AssertJson(expectedText, actualText); + } + + [Test] + public void EnumAsInt() + { + var message = new TestAllTypes + { + SingleForeignEnum = ForeignEnum.ForeignBar, + RepeatedForeignEnum = { ForeignEnum.ForeignBaz, (ForeignEnum) 100, ForeignEnum.ForeignFoo } + }; + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatEnumsAsIntegers(true)); + var actualText = formatter.Format(message); + var expectedText = "{ " + + "'singleForeignEnum': 5, " + + "'repeatedForeignEnum': [ 6, 100, 4 ]" + + " }"; + AssertJson(expectedText, actualText); + } + + [Test] + public void AllSingleFields() + { + var message = new TestAllTypes + { + SingleBool = true, + SingleBytes = ByteString.CopyFrom(1, 2, 3, 4), + SingleDouble = 23.5, + SingleFixed32 = 23, + SingleFixed64 = 1234567890123, + SingleFloat = 12.25f, + SingleForeignEnum = ForeignEnum.ForeignBar, + SingleForeignMessage = new ForeignMessage { C = 10 }, + SingleImportEnum = ImportEnum.ImportBaz, + SingleImportMessage = new ImportMessage { D = 20 }, + SingleInt32 = 100, + SingleInt64 = 3210987654321, + SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo, + SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 35 }, + SinglePublicImportMessage = new PublicImportMessage { E = 54 }, + SingleSfixed32 = -123, + SingleSfixed64 = -12345678901234, + SingleSint32 = -456, + SingleSint64 = -12345678901235, + SingleString = "test\twith\ttabs", + SingleUint32 = uint.MaxValue, + SingleUint64 = ulong.MaxValue, + }; + var actualText = JsonFormatter.Default.Format(message); + + // Fields in numeric order + var expectedText = "{ " + + "'singleInt32': 100, " + + "'singleInt64': '3210987654321', " + + "'singleUint32': 4294967295, " + + "'singleUint64': '18446744073709551615', " + + "'singleSint32': -456, " + + "'singleSint64': '-12345678901235', " + + "'singleFixed32': 23, " + + "'singleFixed64': '1234567890123', " + + "'singleSfixed32': -123, " + + "'singleSfixed64': '-12345678901234', " + + "'singleFloat': 12.25, " + + "'singleDouble': 23.5, " + + "'singleBool': true, " + + "'singleString': 'test\\twith\\ttabs', " + + "'singleBytes': 'AQIDBA==', " + + "'singleNestedMessage': { 'bb': 35 }, " + + "'singleForeignMessage': { 'c': 10 }, " + + "'singleImportMessage': { 'd': 20 }, " + + "'singleNestedEnum': 'FOO', " + + "'singleForeignEnum': 'FOREIGN_BAR', " + + "'singleImportEnum': 'IMPORT_BAZ', " + + "'singlePublicImportMessage': { 'e': 54 }" + + " }"; + AssertJson(expectedText, actualText); + } + + [Test] + public void WithFormatDefaultValues_DoesNotAffectMessageFields() + { + var message = new TestAllTypes(); + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); + var json = formatter.Format(message); + Assert.IsFalse(json.Contains("\"singleNestedMessage\"")); + Assert.IsFalse(json.Contains("\"singleForeignMessage\"")); + Assert.IsFalse(json.Contains("\"singleImportMessage\"")); + } + + [Test] + public void WithFormatDefaultValues_DoesNotAffectProto3OptionalFields() + { + var message = new TestProto3Optional(); + message.OptionalInt32 = 0; + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); + var json = formatter.Format(message); + // The non-optional proto3 fields are formatted, as is the optional-but-specified field. + AssertJson("{ 'optionalInt32': 0, 'singularInt32': 0, 'singularInt64': '0' }", json); + } + + [Test] + public void WithFormatDefaultValues_DoesNotAffectProto2Fields() + { + var message = new TestProtos.Proto2.ForeignMessage(); + message.C = 0; + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); + var json = formatter.Format(message); + // The specified field is formatted, but the non-specified field (d) is not. + AssertJson("{ 'c': 0 }", json); + } + + [Test] + public void WithFormatDefaultValues_DoesNotAffectOneofFields() + { + var message = new TestOneof(); + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); + var json = formatter.Format(message); + AssertJson("{ }", json); + } + + [Test] + public void RepeatedField() + { + AssertJson("{ 'repeatedInt32': [ 1, 2, 3, 4, 5 ] }", + JsonFormatter.Default.Format(new TestAllTypes { RepeatedInt32 = { 1, 2, 3, 4, 5 } })); + } + + [Test] + public void MapField_StringString() + { + AssertJson("{ 'mapStringString': { 'with spaces': 'bar', 'a': 'b' } }", + JsonFormatter.Default.Format(new TestMap { MapStringString = { { "with spaces", "bar" }, { "a", "b" } } })); + } + + [Test] + public void MapField_Int32Int32() + { + // The keys are quoted, but the values aren't. + AssertJson("{ 'mapInt32Int32': { '0': 1, '2': 3 } }", + JsonFormatter.Default.Format(new TestMap { MapInt32Int32 = { { 0, 1 }, { 2, 3 } } })); + } + + [Test] + public void MapField_BoolBool() + { + // The keys are quoted, but the values aren't. + AssertJson("{ 'mapBoolBool': { 'false': true, 'true': false } }", + JsonFormatter.Default.Format(new TestMap { MapBoolBool = { { false, true }, { true, false } } })); + } + + [Test] + public void NullValueOutsideStruct() + { + var message = new NullValueOutsideStruct { NullValue = NullValue.NullValue }; + AssertJson("{ 'nullValue': null }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void NullValueNotInOneof() + { + var message = new NullValueNotInOneof(); + AssertJson("{ }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void NullValueNotInOneof_FormatDefaults() + { + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); + var message = new NullValueNotInOneof(); + AssertJson("{ 'nullValue': null }", formatter.Format(message)); + } + + [TestCase(1.0, "1")] + [TestCase(double.NaN, "'NaN'")] + [TestCase(double.PositiveInfinity, "'Infinity'")] + [TestCase(double.NegativeInfinity, "'-Infinity'")] + public void DoubleRepresentations(double value, string expectedValueText) + { + var message = new TestAllTypes { SingleDouble = value }; + string actualText = JsonFormatter.Default.Format(message); + string expectedText = "{ 'singleDouble': " + expectedValueText + " }"; + AssertJson(expectedText, actualText); + } + + [Test] + public void UnknownEnumValueNumeric_SingleField() + { + var message = new TestAllTypes { SingleForeignEnum = (ForeignEnum) 100 }; + AssertJson("{ 'singleForeignEnum': 100 }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void UnknownEnumValueNumeric_RepeatedField() + { + var message = new TestAllTypes { RepeatedForeignEnum = { ForeignEnum.ForeignBaz, (ForeignEnum) 100, ForeignEnum.ForeignFoo } }; + AssertJson("{ 'repeatedForeignEnum': [ 'FOREIGN_BAZ', 100, 'FOREIGN_FOO' ] }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void UnknownEnumValueNumeric_MapField() + { + var message = new TestMap { MapInt32Enum = { { 1, MapEnum.Foo }, { 2, (MapEnum) 100 }, { 3, MapEnum.Bar } } }; + AssertJson("{ 'mapInt32Enum': { '1': 'MAP_ENUM_FOO', '2': 100, '3': 'MAP_ENUM_BAR' } }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void UnknownEnumValue_RepeatedField_AllEntriesUnknown() + { + var message = new TestAllTypes { RepeatedForeignEnum = { (ForeignEnum) 200, (ForeignEnum) 100 } }; + AssertJson("{ 'repeatedForeignEnum': [ 200, 100 ] }", JsonFormatter.Default.Format(message)); + } + + [Test] + [TestCase("a\u17b4b", "a\\u17b4b")] // Explicit + [TestCase("a\u0601b", "a\\u0601b")] // Ranged + [TestCase("a\u0605b", "a\u0605b")] // Passthrough (note lack of double backslash...) + public void SimpleNonAscii(string text, string encoded) + { + var message = new TestAllTypes { SingleString = text }; + AssertJson("{ 'singleString': '" + encoded + "' }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void SurrogatePairEscaping() + { + var message = new TestAllTypes { SingleString = "a\uD801\uDC01b" }; + AssertJson("{ 'singleString': 'a\\ud801\\udc01b' }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void InvalidSurrogatePairsFail() + { + // Note: don't use TestCase for these, as the strings can't be reliably represented + // See http://codeblog.jonskeet.uk/2014/11/07/when-is-a-string-not-a-string/ + + // Lone low surrogate + var message = new TestAllTypes { SingleString = "a\uDC01b" }; + Assert.Throws(() => JsonFormatter.Default.Format(message)); + + // Lone high surrogate + message = new TestAllTypes { SingleString = "a\uD801b" }; + Assert.Throws(() => JsonFormatter.Default.Format(message)); + } + + [Test] + [TestCase("foo_bar", "fooBar")] + [TestCase("bananaBanana", "bananaBanana")] + [TestCase("BANANABanana", "BANANABanana")] + [TestCase("simple", "simple")] + [TestCase("ACTION_AND_ADVENTURE", "ACTIONANDADVENTURE")] + [TestCase("action_and_adventure", "actionAndAdventure")] + [TestCase("kFoo", "kFoo")] + [TestCase("HTTPServer", "HTTPServer")] + [TestCase("CLIENT", "CLIENT")] + public void ToJsonName(string original, string expected) + { + Assert.AreEqual(expected, JsonFormatter.ToJsonName(original)); + } + + [Test] + [TestCase(null, "{ }")] + [TestCase("x", "{ 'fooString': 'x' }")] + [TestCase("", "{ 'fooString': '' }")] + public void Oneof(string fooStringValue, string expectedJson) + { + var message = new TestOneof(); + if (fooStringValue != null) + { + message.FooString = fooStringValue; + } + + // We should get the same result both with and without "format default values". + var formatter = JsonFormatter.Default; + AssertJson(expectedJson, formatter.Format(message)); + formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); + AssertJson(expectedJson, formatter.Format(message)); + } + + [Test] + public void WrapperFormatting_Single() + { + // Just a few examples, handling both classes and value types, and + // default vs non-default values + var message = new TestWellKnownTypes + { + Int64Field = 10, + Int32Field = 0, + BytesField = ByteString.FromBase64("ABCD"), + StringField = "" + }; + var expectedJson = "{ 'int64Field': '10', 'int32Field': 0, 'stringField': '', 'bytesField': 'ABCD' }"; + AssertJson(expectedJson, JsonFormatter.Default.Format(message)); + } + + [Test] + public void WrapperFormatting_Message() + { + Assert.AreEqual("\"\"", JsonFormatter.Default.Format(new StringValue())); + Assert.AreEqual("0", JsonFormatter.Default.Format(new Int32Value())); + } + + [Test] + public void WrapperFormatting_FormatDefaultValuesDoesNotFormatNull() + { + // The actual JSON here is very large because there are lots of fields. Just test a couple of them. + var message = new TestWellKnownTypes { Int32Field = 10 }; + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); + var actualJson = formatter.Format(message); + // This *used* to include "int64Field": null, but that was a bug. + // WithDefaultValues should not affect message fields, including wrapper types. + Assert.IsFalse(actualJson.Contains("\"int64Field\": null")); + Assert.IsTrue(actualJson.Contains("\"int32Field\": 10")); + } + + [Test] + public void OutputIsInNumericFieldOrder_NoDefaults() + { + var formatter = JsonFormatter.Default; + var message = new TestJsonFieldOrdering { PlainString = "p1", PlainInt32 = 2 }; + AssertJson("{ 'plainString': 'p1', 'plainInt32': 2 }", formatter.Format(message)); + message = new TestJsonFieldOrdering { O1Int32 = 5, O2String = "o2", PlainInt32 = 10, PlainString = "plain" }; + AssertJson("{ 'plainString': 'plain', 'o2String': 'o2', 'plainInt32': 10, 'o1Int32': 5 }", formatter.Format(message)); + message = new TestJsonFieldOrdering { O1String = "", O2Int32 = 0, PlainInt32 = 10, PlainString = "plain" }; + AssertJson("{ 'plainString': 'plain', 'o1String': '', 'plainInt32': 10, 'o2Int32': 0 }", formatter.Format(message)); + } + + [Test] + public void OutputIsInNumericFieldOrder_WithDefaults() + { + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); + var message = new TestJsonFieldOrdering(); + AssertJson("{ 'plainString': '', 'plainInt32': 0 }", formatter.Format(message)); + message = new TestJsonFieldOrdering { O1Int32 = 5, O2String = "o2", PlainInt32 = 10, PlainString = "plain" }; + AssertJson("{ 'plainString': 'plain', 'o2String': 'o2', 'plainInt32': 10, 'o1Int32': 5 }", formatter.Format(message)); + message = new TestJsonFieldOrdering { O1String = "", O2Int32 = 0, PlainInt32 = 10, PlainString = "plain" }; + AssertJson("{ 'plainString': 'plain', 'o1String': '', 'plainInt32': 10, 'o2Int32': 0 }", formatter.Format(message)); + } + + [Test] + [TestCase("1970-01-01T00:00:00Z", 0)] + [TestCase("1970-01-01T00:00:00.000000001Z", 1)] + [TestCase("1970-01-01T00:00:00.000000010Z", 10)] + [TestCase("1970-01-01T00:00:00.000000100Z", 100)] + [TestCase("1970-01-01T00:00:00.000001Z", 1000)] + [TestCase("1970-01-01T00:00:00.000010Z", 10000)] + [TestCase("1970-01-01T00:00:00.000100Z", 100000)] + [TestCase("1970-01-01T00:00:00.001Z", 1000000)] + [TestCase("1970-01-01T00:00:00.010Z", 10000000)] + [TestCase("1970-01-01T00:00:00.100Z", 100000000)] + [TestCase("1970-01-01T00:00:00.120Z", 120000000)] + [TestCase("1970-01-01T00:00:00.123Z", 123000000)] + [TestCase("1970-01-01T00:00:00.123400Z", 123400000)] + [TestCase("1970-01-01T00:00:00.123450Z", 123450000)] + [TestCase("1970-01-01T00:00:00.123456Z", 123456000)] + [TestCase("1970-01-01T00:00:00.123456700Z", 123456700)] + [TestCase("1970-01-01T00:00:00.123456780Z", 123456780)] + [TestCase("1970-01-01T00:00:00.123456789Z", 123456789)] + public void TimestampStandalone(string expected, int nanos) + { + Assert.AreEqual(WrapInQuotes(expected), new Timestamp { Nanos = nanos }.ToString()); + } + + [Test] + public void TimestampStandalone_FromDateTime() + { + // One before and one after the Unix epoch, more easily represented via DateTime. + Assert.AreEqual("\"1673-06-19T12:34:56Z\"", + new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp().ToString()); + Assert.AreEqual("\"2015-07-31T10:29:34Z\"", + new DateTime(2015, 7, 31, 10, 29, 34, DateTimeKind.Utc).ToTimestamp().ToString()); + } + + [Test] + [TestCase(-1, -1)] // Would be valid as duration + [TestCase(1, Timestamp.MaxNanos + 1)] + [TestCase(Timestamp.UnixSecondsAtBclMaxValue + 1, 0)] + [TestCase(Timestamp.UnixSecondsAtBclMinValue - 1, 0)] + public void TimestampStandalone_NonNormalized(long seconds, int nanoseconds) + { + var timestamp = new Timestamp { Seconds = seconds, Nanos = nanoseconds }; + Assert.Throws(() => JsonFormatter.Default.Format(timestamp)); + } + + [Test] + public void TimestampField() + { + var message = new TestWellKnownTypes { TimestampField = new Timestamp() }; + AssertJson("{ 'timestampField': '1970-01-01T00:00:00Z' }", JsonFormatter.Default.Format(message)); + } + + [Test] + [TestCase(0, 0, "0s")] + [TestCase(1, 0, "1s")] + [TestCase(-1, 0, "-1s")] + [TestCase(0, 1, "0.000000001s")] + [TestCase(0, 10, "0.000000010s")] + [TestCase(0, 100, "0.000000100s")] + [TestCase(0, 1000, "0.000001s")] + [TestCase(0, 10000, "0.000010s")] + [TestCase(0, 100000, "0.000100s")] + [TestCase(0, 1000000, "0.001s")] + [TestCase(0, 10000000, "0.010s")] + [TestCase(0, 100000000, "0.100s")] + [TestCase(0, 120000000, "0.120s")] + [TestCase(0, 123000000, "0.123s")] + [TestCase(0, 123400000, "0.123400s")] + [TestCase(0, 123450000, "0.123450s")] + [TestCase(0, 123456000, "0.123456s")] + [TestCase(0, 123456700, "0.123456700s")] + [TestCase(0, 123456780, "0.123456780s")] + [TestCase(0, 123456789, "0.123456789s")] + [TestCase(0, -100000000, "-0.100s")] + [TestCase(1, 100000000, "1.100s")] + [TestCase(-1, -100000000, "-1.100s")] + public void DurationStandalone(long seconds, int nanoseconds, string expected) + { + var json = JsonFormatter.Default.Format(new Duration { Seconds = seconds, Nanos = nanoseconds }); + Assert.AreEqual(WrapInQuotes(expected), json); + } + + [Test] + [TestCase(1, 2123456789)] + [TestCase(1, -100000000)] + public void DurationStandalone_NonNormalized(long seconds, int nanoseconds) + { + var duration = new Duration { Seconds = seconds, Nanos = nanoseconds }; + Assert.Throws(() => JsonFormatter.Default.Format(duration)); + } + + [Test] + public void DurationField() + { + var message = new TestWellKnownTypes { DurationField = new Duration() }; + AssertJson("{ 'durationField': '0s' }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void StructSample() + { + var message = new Struct + { + Fields = + { + { "a", Value.ForNull() }, + { "b", Value.ForBool(false) }, + { "c", Value.ForNumber(10.5) }, + { "d", Value.ForString("text") }, + { "e", Value.ForList(Value.ForString("t1"), Value.ForNumber(5)) }, + { "f", Value.ForStruct(new Struct { Fields = { { "nested", Value.ForString("value") } } }) } + } + }; + AssertJson("{ 'a': null, 'b': false, 'c': 10.5, 'd': 'text', 'e': [ 't1', 5 ], 'f': { 'nested': 'value' } }", message.ToString()); + } + + [Test] + [TestCase("foo__bar")] + [TestCase("foo_3_ar")] + [TestCase("fooBar")] + public void FieldMaskInvalid(string input) + { + var mask = new FieldMask { Paths = { input } }; + Assert.Throws(() => JsonFormatter.Default.Format(mask)); + } + + [Test] + public void FieldMaskStandalone() + { + var fieldMask = new FieldMask { Paths = { "", "single", "with_underscore", "nested.field.name", "nested..double_dot" } }; + Assert.AreEqual("\",single,withUnderscore,nested.field.name,nested..doubleDot\"", fieldMask.ToString()); + + // Invalid, but we shouldn't create broken JSON... + fieldMask = new FieldMask { Paths = { "x\\y" } }; + Assert.AreEqual(@"""x\\y""", fieldMask.ToString()); + } + + [Test] + public void FieldMaskField() + { + var message = new TestWellKnownTypes { FieldMaskField = new FieldMask { Paths = { "user.display_name", "photo" } } }; + AssertJson("{ 'fieldMaskField': 'user.displayName,photo' }", JsonFormatter.Default.Format(message)); + } + + // SourceContext is an example of a well-known type with no special JSON handling + [Test] + public void SourceContextStandalone() + { + var message = new SourceContext { FileName = "foo.proto" }; + AssertJson("{ 'fileName': 'foo.proto' }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void AnyWellKnownType() + { + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithTypeRegistry(TypeRegistry.FromMessages(Timestamp.Descriptor))); + var timestamp = new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp(); + var any = Any.Pack(timestamp); + AssertJson("{ '@type': 'type.googleapis.com/google.protobuf.Timestamp', 'value': '1673-06-19T12:34:56Z' }", formatter.Format(any)); + } + + [Test] + public void AnyMessageType() + { + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithTypeRegistry(TypeRegistry.FromMessages(TestAllTypes.Descriptor))); + var message = new TestAllTypes { SingleInt32 = 10, SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } }; + var any = Any.Pack(message); + AssertJson("{ '@type': 'type.googleapis.com/protobuf_unittest3.TestAllTypes', 'singleInt32': 10, 'singleNestedMessage': { 'bb': 20 } }", formatter.Format(any)); + } + + [Test] + public void AnyMessageType_CustomPrefix() + { + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithTypeRegistry(TypeRegistry.FromMessages(TestAllTypes.Descriptor))); + var message = new TestAllTypes { SingleInt32 = 10 }; + var any = Any.Pack(message, "foo.bar/baz"); + AssertJson("{ '@type': 'foo.bar/baz/protobuf_unittest3.TestAllTypes', 'singleInt32': 10 }", formatter.Format(any)); + } + + [Test] + public void AnyNested() + { + var registry = TypeRegistry.FromMessages(TestWellKnownTypes.Descriptor, TestAllTypes.Descriptor); + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithTypeRegistry(registry)); + + // Nest an Any as the value of an Any. + var doubleNestedMessage = new TestAllTypes { SingleInt32 = 20 }; + var nestedMessage = Any.Pack(doubleNestedMessage); + var message = new TestWellKnownTypes { AnyField = Any.Pack(nestedMessage) }; + AssertJson("{ 'anyField': { '@type': 'type.googleapis.com/google.protobuf.Any', 'value': { '@type': 'type.googleapis.com/protobuf_unittest3.TestAllTypes', 'singleInt32': 20 } } }", + formatter.Format(message)); + } + + [Test] + public void AnyUnknownType() + { + // The default type registry doesn't have any types in it. + var message = new TestAllTypes(); + var any = Any.Pack(message); + Assert.Throws(() => JsonFormatter.Default.Format(any)); + } + + [Test] + [TestCase(typeof(BoolValue), true, "true")] + [TestCase(typeof(Int32Value), 32, "32")] + [TestCase(typeof(Int64Value), 32L, "\"32\"")] + [TestCase(typeof(UInt32Value), 32U, "32")] + [TestCase(typeof(UInt64Value), 32UL, "\"32\"")] + [TestCase(typeof(StringValue), "foo", "\"foo\"")] + [TestCase(typeof(FloatValue), 1.5f, "1.5")] + [TestCase(typeof(DoubleValue), 1.5d, "1.5")] + public void Wrappers_Standalone(System.Type wrapperType, object value, string expectedJson) + { + IMessage populated = (IMessage)Activator.CreateInstance(wrapperType); + populated.Descriptor.Fields[WrappersReflection.WrapperValueFieldNumber].Accessor.SetValue(populated, value); + Assert.AreEqual(expectedJson, JsonFormatter.Default.Format(populated)); + } + + // Sanity tests for WriteValue. Not particularly comprehensive, as it's all covered above already, + // as FormatMessage uses WriteValue. + + [TestCase(null, "null")] + [TestCase(1, "1")] + [TestCase(1L, "'1'")] + [TestCase(0.5f, "0.5")] + [TestCase(0.5d, "0.5")] + [TestCase("text", "'text'")] + [TestCase("x\ny", @"'x\ny'")] + [TestCase(ForeignEnum.ForeignBar, "'FOREIGN_BAR'")] + public void WriteValue_Constant(object value, string expectedJson) + { + AssertWriteValue(value, expectedJson); + } + + [Test] + public void WriteValue_Timestamp() + { + var value = new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp(); + AssertWriteValue(value, "'1673-06-19T12:34:56Z'"); + } + + [Test] + public void WriteValue_Message() + { + var value = new TestAllTypes { SingleInt32 = 100, SingleInt64 = 3210987654321L }; + AssertWriteValue(value, "{ 'singleInt32': 100, 'singleInt64': '3210987654321' }"); + } + + [Test] + public void WriteValue_List() + { + var value = new RepeatedField { 1, 2, 3 }; + AssertWriteValue(value, "[ 1, 2, 3 ]"); + } + + [Test] + public void Proto2_DefaultValuesWritten() + { + var value = new ProtobufTestMessages.Proto2.TestAllTypesProto2() { FieldName13 = 0 }; + AssertWriteValue(value, "{ 'FieldName13': 0 }"); + } + + private static void AssertWriteValue(object value, string expectedJson) + { + var writer = new StringWriter(); + JsonFormatter.Default.WriteValue(writer, value); + string actual = writer.ToString(); + AssertJson(expectedJson, actual); + } + + /// + /// Checks that the actual JSON is the same as the expected JSON - but after replacing + /// all apostrophes in the expected JSON with double quotes. This basically makes the tests easier + /// to read. + /// + private static void AssertJson(string expectedJsonWithApostrophes, string actualJson) + { + var expectedJson = expectedJsonWithApostrophes.Replace("'", "\""); + Assert.AreEqual(expectedJson, actualJson); + } + } +} diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/Proto3OptionalTest.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/Proto3OptionalTest.cs new file mode 100644 index 0000000..46a8c57 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/Proto3OptionalTest.cs @@ -0,0 +1,153 @@ +#region Copyright notice and license +// 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. +#endregion + +using NUnit.Framework; +using ProtobufUnittest; +using System; +using System.IO; +using UnitTest.Issues.TestProtos; + +namespace Google.Protobuf.Test +{ + class Proto3OptionalTest + { + [Test] + public void OptionalInt32FieldLifecycle() + { + var message = new TestProto3Optional(); + Assert.IsFalse(message.HasOptionalInt32); + Assert.AreEqual(0, message.OptionalInt32); + + message.OptionalInt32 = 5; + Assert.IsTrue(message.HasOptionalInt32); + Assert.AreEqual(5, message.OptionalInt32); + + message.OptionalInt32 = 0; + Assert.IsTrue(message.HasOptionalInt32); + Assert.AreEqual(0, message.OptionalInt32); + + message.ClearOptionalInt32(); + Assert.IsFalse(message.HasOptionalInt32); + Assert.AreEqual(0, message.OptionalInt32); + } + + [Test] + public void OptionalStringFieldLifecycle() + { + var message = new TestProto3Optional(); + Assert.IsFalse(message.HasOptionalString); + Assert.AreEqual("", message.OptionalString); + + message.OptionalString = "x"; + Assert.IsTrue(message.HasOptionalString); + Assert.AreEqual("x", message.OptionalString); + + message.OptionalString = ""; + Assert.IsTrue(message.HasOptionalString); + Assert.AreEqual("", message.OptionalString); + + message.ClearOptionalString(); + Assert.IsFalse(message.HasOptionalString); + Assert.AreEqual("", message.OptionalString); + + Assert.Throws(() => message.OptionalString = null); + } + + [Test] + public void Clone() + { + var original = new TestProto3Optional { OptionalInt64 = 0L }; + + var clone = original.Clone(); + Assert.False(clone.HasOptionalInt32); + Assert.AreEqual(0, clone.OptionalInt32); + Assert.True(clone.HasOptionalInt64); + Assert.AreEqual(0L, clone.OptionalInt64); + } + + [Test] + public void Serialization_NotSet() + { + var stream = new MemoryStream(); + var message = new TestProto3Optional(); + message.WriteTo(stream); + Assert.AreEqual(0, stream.Length); + } + + [Test] + public void Serialization_SetToDefault() + { + var stream = new MemoryStream(); + var message = new TestProto3Optional { OptionalInt32 = 0 }; + message.WriteTo(stream); + Assert.AreEqual(2, stream.Length); // Tag and value + } + + [Test] + public void Serialization_Roundtrip() + { + var original = new TestProto3Optional { OptionalInt64 = 0L, OptionalFixed32 = 5U }; + var stream = new MemoryStream(); + original.WriteTo(stream); + stream.Position = 0; + var deserialized = TestProto3Optional.Parser.ParseFrom(stream); + + Assert.AreEqual(0, deserialized.OptionalInt32); + Assert.IsFalse(deserialized.HasOptionalInt32); + + Assert.AreEqual(0L, deserialized.OptionalInt64); + Assert.IsTrue(deserialized.HasOptionalInt64); + + Assert.AreEqual(5U, deserialized.OptionalFixed32); + Assert.IsTrue(deserialized.HasOptionalFixed32); + } + + [Test] + public void Equality_IgnoresPresence() + { + var message1 = new TestProto3Optional { OptionalInt32 = 0 }; + var message2 = new TestProto3Optional(); + + Assert.IsTrue(message1.Equals(message2)); + message1.ClearOptionalInt32(); + } + + [Test] + public void MixedFields() + { + var descriptor = MixedRegularAndOptional.Descriptor; + Assert.AreEqual(1, descriptor.Oneofs.Count); + Assert.AreEqual(0, descriptor.RealOneofCount); + Assert.True(descriptor.Oneofs[0].IsSynthetic); + } + } +} diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/SampleMessages.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/SampleMessages.cs new file mode 100644 index 0000000..03a20d6 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/SampleMessages.cs @@ -0,0 +1,207 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; +using Google.Protobuf.TestProtos; +using Proto2 = Google.Protobuf.TestProtos.Proto2; + +using static Google.Protobuf.TestProtos.Proto2.UnittestExtensions; + +namespace Google.Protobuf +{ + /// + /// Helper methods to create sample instances of types generated from unit test messages. + /// + public class SampleMessages + { + /// + /// Creates a new sample TestAllTypes message with all fields populated. + /// The "oneof" field is populated with the string property (OneofString). + /// + public static TestAllTypes CreateFullTestAllTypes() + { + return new TestAllTypes + { + SingleBool = true, + SingleBytes = ByteString.CopyFrom(1, 2, 3, 4), + SingleDouble = 23.5, + SingleFixed32 = 23, + SingleFixed64 = 1234567890123, + SingleFloat = 12.25f, + SingleForeignEnum = ForeignEnum.ForeignBar, + SingleForeignMessage = new ForeignMessage { C = 10 }, + SingleImportEnum = ImportEnum.ImportBaz, + SingleImportMessage = new ImportMessage { D = 20 }, + SingleInt32 = 100, + SingleInt64 = 3210987654321, + SingleNestedEnum = TestProtos.TestAllTypes.Types.NestedEnum.Foo, + SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 35 }, + SinglePublicImportMessage = new PublicImportMessage { E = 54 }, + SingleSfixed32 = -123, + SingleSfixed64 = -12345678901234, + SingleSint32 = -456, + SingleSint64 = -12345678901235, + SingleString = "test", + SingleUint32 = UInt32.MaxValue, + SingleUint64 = UInt64.MaxValue, + RepeatedBool = { true, false }, + RepeatedBytes = { ByteString.CopyFrom(1, 2, 3, 4), ByteString.CopyFrom(5, 6), ByteString.CopyFrom(new byte[1000]) }, + RepeatedDouble = { -12.25, 23.5 }, + RepeatedFixed32 = { UInt32.MaxValue, 23 }, + RepeatedFixed64 = { UInt64.MaxValue, 1234567890123 }, + RepeatedFloat = { 100f, 12.25f }, + RepeatedForeignEnum = { ForeignEnum.ForeignFoo, ForeignEnum.ForeignBar }, + RepeatedForeignMessage = { new ForeignMessage(), new ForeignMessage { C = 10 } }, + RepeatedImportEnum = { ImportEnum.ImportBaz, ImportEnum.Unspecified }, + RepeatedImportMessage = { new ImportMessage { D = 20 }, new ImportMessage { D = 25 } }, + RepeatedInt32 = { 100, 200 }, + RepeatedInt64 = { 3210987654321, Int64.MaxValue }, + RepeatedNestedEnum = { TestProtos.TestAllTypes.Types.NestedEnum.Foo, TestProtos.TestAllTypes.Types.NestedEnum.Neg }, + RepeatedNestedMessage = { new TestAllTypes.Types.NestedMessage { Bb = 35 }, new TestAllTypes.Types.NestedMessage { Bb = 10 } }, + RepeatedPublicImportMessage = { new PublicImportMessage { E = 54 }, new PublicImportMessage { E = -1 } }, + RepeatedSfixed32 = { -123, 123 }, + RepeatedSfixed64 = { -12345678901234, 12345678901234 }, + RepeatedSint32 = { -456, 100 }, + RepeatedSint64 = { -12345678901235, 123 }, + RepeatedString = { "foo", "bar" }, + RepeatedUint32 = { UInt32.MaxValue, UInt32.MinValue }, + RepeatedUint64 = { UInt64.MaxValue, UInt32.MinValue }, + OneofString = "Oneof string" + }; + } + + public static Proto2.TestAllTypes CreateFullTestAllTypesProto2() + { + return new Proto2.TestAllTypes + { + OptionalBool = true, + OptionalBytes = ByteString.CopyFrom(1, 2, 3, 4), + OptionalDouble = 23.5, + OptionalFixed32 = 23, + OptionalFixed64 = 1234567890123, + OptionalFloat = 12.25f, + OptionalForeignEnum = Proto2.ForeignEnum.ForeignBar, + OptionalForeignMessage = new Proto2.ForeignMessage { C = 10 }, + OptionalImportEnum = Proto2.ImportEnum.ImportBaz, + OptionalImportMessage = new Proto2.ImportMessage { D = 20 }, + OptionalInt32 = 100, + OptionalInt64 = 3210987654321, + OptionalNestedEnum = Proto2.TestAllTypes.Types.NestedEnum.Foo, + OptionalNestedMessage = new Proto2.TestAllTypes.Types.NestedMessage { Bb = 35 }, + OptionalPublicImportMessage = new Proto2.PublicImportMessage { E = 54 }, + OptionalSfixed32 = -123, + OptionalSfixed64 = -12345678901234, + OptionalSint32 = -456, + OptionalSint64 = -12345678901235, + OptionalString = "test", + OptionalUint32 = UInt32.MaxValue, + OptionalUint64 = UInt64.MaxValue, + OptionalGroup = new Proto2.TestAllTypes.Types.OptionalGroup { A = 10 }, + RepeatedBool = { true, false }, + RepeatedBytes = { ByteString.CopyFrom(1, 2, 3, 4), ByteString.CopyFrom(5, 6), ByteString.CopyFrom(new byte[1000]) }, + RepeatedDouble = { -12.25, 23.5 }, + RepeatedFixed32 = { UInt32.MaxValue, 23 }, + RepeatedFixed64 = { UInt64.MaxValue, 1234567890123 }, + RepeatedFloat = { 100f, 12.25f }, + RepeatedForeignEnum = { Proto2.ForeignEnum.ForeignFoo, Proto2.ForeignEnum.ForeignBar }, + RepeatedForeignMessage = { new Proto2.ForeignMessage(), new Proto2.ForeignMessage { C = 10 } }, + RepeatedImportEnum = { Proto2.ImportEnum.ImportBaz, Proto2.ImportEnum.ImportFoo }, + RepeatedImportMessage = { new Proto2.ImportMessage { D = 20 }, new Proto2.ImportMessage { D = 25 } }, + RepeatedInt32 = { 100, 200 }, + RepeatedInt64 = { 3210987654321, Int64.MaxValue }, + RepeatedNestedEnum = { Proto2.TestAllTypes.Types.NestedEnum.Foo, Proto2.TestAllTypes.Types.NestedEnum.Neg }, + RepeatedNestedMessage = { new Proto2.TestAllTypes.Types.NestedMessage { Bb = 35 }, new Proto2.TestAllTypes.Types.NestedMessage { Bb = 10 } }, + RepeatedSfixed32 = { -123, 123 }, + RepeatedSfixed64 = { -12345678901234, 12345678901234 }, + RepeatedSint32 = { -456, 100 }, + RepeatedSint64 = { -12345678901235, 123 }, + RepeatedString = { "foo", "bar" }, + RepeatedUint32 = { UInt32.MaxValue, UInt32.MinValue }, + RepeatedUint64 = { UInt64.MaxValue, UInt32.MinValue }, + RepeatedGroup = { new Proto2.TestAllTypes.Types.RepeatedGroup { A = 10 }, new Proto2.TestAllTypes.Types.RepeatedGroup { A = 20 } }, + OneofString = "Oneof string" + }; + } + + public static Proto2.TestAllExtensions CreateFullTestAllExtensions() + { + var message = new Proto2.TestAllExtensions(); + message.SetExtension(OptionalBoolExtension, true); + message.SetExtension(OptionalBytesExtension, ByteString.CopyFrom(1, 2, 3, 4)); + message.SetExtension(OptionalDoubleExtension, 23.5); + message.SetExtension(OptionalFixed32Extension, 23u); + message.SetExtension(OptionalFixed64Extension, 1234567890123u); + message.SetExtension(OptionalFloatExtension, 12.25f); + message.SetExtension(OptionalForeignEnumExtension, Proto2.ForeignEnum.ForeignBar); + message.SetExtension(OptionalForeignMessageExtension, new Proto2.ForeignMessage { C = 10 }); + message.SetExtension(OptionalImportEnumExtension, Proto2.ImportEnum.ImportBaz); + message.SetExtension(OptionalImportMessageExtension, new Proto2.ImportMessage { D = 20 }); + message.SetExtension(OptionalInt32Extension, 100); + message.SetExtension(OptionalInt64Extension, 3210987654321); + message.SetExtension(OptionalNestedEnumExtension, Proto2.TestAllTypes.Types.NestedEnum.Foo); + message.SetExtension(OptionalNestedMessageExtension, new Proto2.TestAllTypes.Types.NestedMessage { Bb = 35 }); + message.SetExtension(OptionalPublicImportMessageExtension, new Proto2.PublicImportMessage { E = 54 }); + message.SetExtension(OptionalSfixed32Extension, -123); + message.SetExtension(OptionalSfixed64Extension, -12345678901234); + message.SetExtension(OptionalSint32Extension, -456); + message.SetExtension(OptionalSint64Extension, -12345678901235); + message.SetExtension(OptionalStringExtension, "test"); + message.SetExtension(OptionalUint32Extension, UInt32.MaxValue); + message.SetExtension(OptionalUint64Extension, UInt64.MaxValue); + message.SetExtension(OptionalGroupExtension, new Proto2.OptionalGroup_extension { A = 10 }); + message.GetOrInitializeExtension(RepeatedBoolExtension).AddRange(new[] { true, false }); + message.GetOrInitializeExtension(RepeatedBytesExtension).AddRange(new[] { ByteString.CopyFrom(1, 2, 3, 4), ByteString.CopyFrom(5, 6), ByteString.CopyFrom(new byte[1000]) }); + message.GetOrInitializeExtension(RepeatedDoubleExtension).AddRange(new[] { -12.25, 23.5 }); + message.GetOrInitializeExtension(RepeatedFixed32Extension).AddRange(new[] { UInt32.MaxValue, 23u }); + message.GetOrInitializeExtension(RepeatedFixed64Extension).AddRange(new[] { UInt64.MaxValue, 1234567890123ul }); + message.GetOrInitializeExtension(RepeatedFloatExtension).AddRange(new[] { 100f, 12.25f }); + message.GetOrInitializeExtension(RepeatedForeignEnumExtension).AddRange(new[] { Proto2.ForeignEnum.ForeignFoo, Proto2.ForeignEnum.ForeignBar }); + message.GetOrInitializeExtension(RepeatedForeignMessageExtension).AddRange(new[] { new Proto2.ForeignMessage(), new Proto2.ForeignMessage { C = 10 } }); + message.GetOrInitializeExtension(RepeatedImportEnumExtension).AddRange(new[] { Proto2.ImportEnum.ImportBaz, Proto2.ImportEnum.ImportFoo }); + message.GetOrInitializeExtension(RepeatedImportMessageExtension).AddRange(new[] { new Proto2.ImportMessage { D = 20 }, new Proto2.ImportMessage { D = 25 } }); + message.GetOrInitializeExtension(RepeatedInt32Extension).AddRange(new[] { 100, 200 }); + message.GetOrInitializeExtension(RepeatedInt64Extension).AddRange(new[] { 3210987654321, Int64.MaxValue }); + message.GetOrInitializeExtension(RepeatedNestedEnumExtension).AddRange(new[] { Proto2.TestAllTypes.Types.NestedEnum.Foo, Proto2.TestAllTypes.Types.NestedEnum.Neg }); + message.GetOrInitializeExtension(RepeatedNestedMessageExtension).AddRange(new[] { new Proto2.TestAllTypes.Types.NestedMessage { Bb = 35 }, new Proto2.TestAllTypes.Types.NestedMessage { Bb = 10 } }); + message.GetOrInitializeExtension(RepeatedSfixed32Extension).AddRange(new[] { -123, 123 }); + message.GetOrInitializeExtension(RepeatedSfixed64Extension).AddRange(new[] { -12345678901234, 12345678901234 }); + message.GetOrInitializeExtension(RepeatedSint32Extension).AddRange(new[] { -456, 100 }); + message.GetOrInitializeExtension(RepeatedSint64Extension).AddRange(new[] { -12345678901235, 123 }); + message.GetOrInitializeExtension(RepeatedStringExtension).AddRange(new[] { "foo", "bar" }); + message.GetOrInitializeExtension(RepeatedUint32Extension).AddRange(new[] { UInt32.MaxValue, UInt32.MinValue }); + message.GetOrInitializeExtension(RepeatedUint64Extension).AddRange(new[] { UInt64.MaxValue, UInt32.MinValue }); + message.GetOrInitializeExtension(RepeatedGroupExtension).AddRange(new[] { new Proto2.RepeatedGroup_extension { A = 10 }, new Proto2.RepeatedGroup_extension { A = 20 } }); + message.SetExtension(OneofStringExtension, "Oneof string"); + return message; + } + } +} \ No newline at end of file diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs new file mode 100644 index 0000000..5b0e5e8 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs @@ -0,0 +1,546 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; +using Google.Protobuf.TestProtos; +using NUnit.Framework; +using System.Collections; +using System.IO; + +namespace Google.Protobuf.WellKnownTypes +{ + public class WrappersTest + { + [Test] + public void NullIsDefault() + { + var message = new TestWellKnownTypes(); + Assert.IsNull(message.StringField); + Assert.IsNull(message.BytesField); + Assert.IsNull(message.BoolField); + Assert.IsNull(message.FloatField); + Assert.IsNull(message.DoubleField); + Assert.IsNull(message.Int32Field); + Assert.IsNull(message.Int64Field); + Assert.IsNull(message.Uint32Field); + Assert.IsNull(message.Uint64Field); + } + + [Test] + public void NonDefaultSingleValues() + { + var message = new TestWellKnownTypes + { + StringField = "x", + BytesField = ByteString.CopyFrom(1, 2, 3), + BoolField = true, + FloatField = 12.5f, + DoubleField = 12.25d, + Int32Field = 1, + Int64Field = 2, + Uint32Field = 3, + Uint64Field = 4 + }; + + MessageParsingHelpers.AssertWritingMessage(message); + + MessageParsingHelpers.AssertRoundtrip(TestWellKnownTypes.Parser, message, parsed => + { + Assert.AreEqual("x", parsed.StringField); + Assert.AreEqual(ByteString.CopyFrom(1, 2, 3), parsed.BytesField); + Assert.AreEqual(true, parsed.BoolField); + Assert.AreEqual(12.5f, parsed.FloatField); + Assert.AreEqual(12.25d, parsed.DoubleField); + Assert.AreEqual(1, parsed.Int32Field); + Assert.AreEqual(2L, parsed.Int64Field); + Assert.AreEqual(3U, parsed.Uint32Field); + Assert.AreEqual(4UL, parsed.Uint64Field); + }); + } + + [Test] + public void NegativeSingleValues() + { + var message = new TestWellKnownTypes + { + FloatField = -12.5f, + DoubleField = -12.25d, + Int32Field = -1, + Int64Field = -2 + }; + + MessageParsingHelpers.AssertWritingMessage(message); + + MessageParsingHelpers.AssertRoundtrip(TestWellKnownTypes.Parser, message, parsed => + { + Assert.AreEqual(-12.5f, parsed.FloatField); + Assert.AreEqual(-12.25d, parsed.DoubleField); + Assert.AreEqual(-1, parsed.Int32Field); + Assert.AreEqual(-2L, parsed.Int64Field); + }); + } + + [Test] + public void NonNullDefaultIsPreservedThroughSerialization() + { + var message = new TestWellKnownTypes + { + StringField = "", + BytesField = ByteString.Empty, + BoolField = false, + FloatField = 0f, + DoubleField = 0d, + Int32Field = 0, + Int64Field = 0, + Uint32Field = 0, + Uint64Field = 0 + }; + + MessageParsingHelpers.AssertWritingMessage(message); + + MessageParsingHelpers.AssertRoundtrip(TestWellKnownTypes.Parser, message, parsed => + { + Assert.AreEqual("", parsed.StringField); + Assert.AreEqual(ByteString.Empty, parsed.BytesField); + Assert.AreEqual(false, parsed.BoolField); + Assert.AreEqual(0f, parsed.FloatField); + Assert.AreEqual(0d, parsed.DoubleField); + Assert.AreEqual(0, parsed.Int32Field); + Assert.AreEqual(0L, parsed.Int64Field); + Assert.AreEqual(0U, parsed.Uint32Field); + Assert.AreEqual(0UL, parsed.Uint64Field); + }); + } + + [Test] + public void RepeatedWrappersProhibitNullItems() + { + var message = new RepeatedWellKnownTypes(); + Assert.Throws(() => message.BoolField.Add((bool?) null)); + Assert.Throws(() => message.Int32Field.Add((int?) null)); + Assert.Throws(() => message.StringField.Add((string) null)); + Assert.Throws(() => message.BytesField.Add((ByteString) null)); + } + + [Test] + public void RepeatedWrappersSerializeDeserialize() + { + var message = new RepeatedWellKnownTypes + { + BoolField = { true, false }, + BytesField = { ByteString.CopyFrom(1, 2, 3), ByteString.CopyFrom(4, 5, 6), ByteString.Empty }, + DoubleField = { 12.5, -1.5, 0d }, + FloatField = { 123.25f, -20f, 0f }, + Int32Field = { int.MaxValue, int.MinValue, 0 }, + Int64Field = { long.MaxValue, long.MinValue, 0L }, + StringField = { "First", "Second", "" }, + Uint32Field = { uint.MaxValue, uint.MinValue, 0U }, + Uint64Field = { ulong.MaxValue, ulong.MinValue, 0UL }, + }; + + // Just to test a single value for sanity... + Assert.AreEqual("Second", message.StringField[1]); + + MessageParsingHelpers.AssertWritingMessage(message); + + MessageParsingHelpers.AssertRoundtrip(RepeatedWellKnownTypes.Parser, message); + } + + [Test] + public void RepeatedWrappersBinaryFormat() + { + // At one point we accidentally used a packed format for repeated wrappers, which is wrong (and weird). + // This test is just to prove that we use the right format. + + var rawOutput = new MemoryStream(); + var output = new CodedOutputStream(rawOutput); + // Write a value of 5 + output.WriteTag(RepeatedWellKnownTypes.Int32FieldFieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(2); + output.WriteTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Varint); + output.WriteInt32(5); + // Write a value of 0 (empty message) + output.WriteTag(RepeatedWellKnownTypes.Int32FieldFieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(0); + output.Flush(); + var expectedBytes = rawOutput.ToArray(); + + var message = new RepeatedWellKnownTypes { Int32Field = { 5, 0 } }; + var actualBytes = message.ToByteArray(); + Assert.AreEqual(expectedBytes, actualBytes); + + MessageParsingHelpers.AssertWritingMessage(message); + } + + [Test] + public void MapWrappersSerializeDeserialize() + { + // Note: no null values here, as they are prohibited in map fields + // (despite being representable). + var message = new MapWellKnownTypes + { + BoolField = { { 10, false }, { 20, true } }, + BytesField = { + { -1, ByteString.CopyFrom(1, 2, 3) }, + { 10, ByteString.CopyFrom(4, 5, 6) }, + { 1000, ByteString.Empty }, + }, + DoubleField = { { 1, 12.5 }, { 10, -1.5 }, { 20, 0d } }, + FloatField = { { 2, 123.25f }, { 3, -20f }, { 4, 0f } }, + Int32Field = { { 5, int.MaxValue }, { 6, int.MinValue }, { 7, 0 } }, + Int64Field = { { 8, long.MaxValue }, { 9, long.MinValue }, { 10, 0L } }, + StringField = { { 11, "First" }, { 12, "Second" }, { 13, "" } }, + Uint32Field = { { 15, uint.MaxValue }, { 16, uint.MinValue }, { 17, 0U } }, + Uint64Field = { { 18, ulong.MaxValue }, { 19, ulong.MinValue }, { 20, 0UL } }, + }; + + // Just to test a single value for sanity... + Assert.AreEqual("Second", message.StringField[12]); + + MessageParsingHelpers.AssertWritingMessage(message); + + MessageParsingHelpers.AssertRoundtrip(MapWellKnownTypes.Parser, message); + } + + [Test] + public void Reflection_SingleValues() + { + var message = new TestWellKnownTypes + { + StringField = "x", + BytesField = ByteString.CopyFrom(1, 2, 3), + BoolField = true, + FloatField = 12.5f, + DoubleField = 12.25d, + Int32Field = 1, + Int64Field = 2, + Uint32Field = 3, + Uint64Field = 4 + }; + var fields = TestWellKnownTypes.Descriptor.Fields; + + Assert.AreEqual("x", fields[TestWellKnownTypes.StringFieldFieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(ByteString.CopyFrom(1, 2, 3), fields[TestWellKnownTypes.BytesFieldFieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(true, fields[TestWellKnownTypes.BoolFieldFieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(12.5f, fields[TestWellKnownTypes.FloatFieldFieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(12.25d, fields[TestWellKnownTypes.DoubleFieldFieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(1, fields[TestWellKnownTypes.Int32FieldFieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(2L, fields[TestWellKnownTypes.Int64FieldFieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(3U, fields[TestWellKnownTypes.Uint32FieldFieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(4UL, fields[TestWellKnownTypes.Uint64FieldFieldNumber].Accessor.GetValue(message)); + + // And a couple of null fields... + message.StringField = null; + message.FloatField = null; + Assert.IsNull(fields[TestWellKnownTypes.StringFieldFieldNumber].Accessor.GetValue(message)); + Assert.IsNull(fields[TestWellKnownTypes.FloatFieldFieldNumber].Accessor.GetValue(message)); + } + + [Test] + public void Reflection_RepeatedFields() + { + // Just a single example... note that we can't have a null value here + var message = new RepeatedWellKnownTypes { Int32Field = { 1, 2 } }; + var fields = RepeatedWellKnownTypes.Descriptor.Fields; + var list = (IList) fields[RepeatedWellKnownTypes.Int32FieldFieldNumber].Accessor.GetValue(message); + CollectionAssert.AreEqual(new[] { 1, 2 }, list); + } + + [Test] + public void Reflection_MapFields() + { + // Just a single example... note that we can't have a null value here despite the value type being int? + var message = new MapWellKnownTypes { Int32Field = { { 1, 2 } } }; + var fields = MapWellKnownTypes.Descriptor.Fields; + var dictionary = (IDictionary) fields[MapWellKnownTypes.Int32FieldFieldNumber].Accessor.GetValue(message); + Assert.AreEqual(2, dictionary[1]); + } + + [Test] + public void Oneof() + { + var message = new OneofWellKnownTypes { EmptyField = new Empty() }; + // Start off with a non-wrapper + Assert.AreEqual(OneofWellKnownTypes.OneofFieldOneofCase.EmptyField, message.OneofFieldCase); + AssertOneofRoundTrip(message); + + message.StringField = "foo"; + Assert.AreEqual(OneofWellKnownTypes.OneofFieldOneofCase.StringField, message.OneofFieldCase); + AssertOneofRoundTrip(message); + + message.StringField = "foo"; + Assert.AreEqual(OneofWellKnownTypes.OneofFieldOneofCase.StringField, message.OneofFieldCase); + AssertOneofRoundTrip(message); + + message.DoubleField = 0.0f; + Assert.AreEqual(OneofWellKnownTypes.OneofFieldOneofCase.DoubleField, message.OneofFieldCase); + AssertOneofRoundTrip(message); + + message.DoubleField = 1.0f; + Assert.AreEqual(OneofWellKnownTypes.OneofFieldOneofCase.DoubleField, message.OneofFieldCase); + AssertOneofRoundTrip(message); + + message.ClearOneofField(); + Assert.AreEqual(OneofWellKnownTypes.OneofFieldOneofCase.None, message.OneofFieldCase); + AssertOneofRoundTrip(message); + } + + private void AssertOneofRoundTrip(OneofWellKnownTypes message) + { + // Normal roundtrip, but explicitly checking the case... + MessageParsingHelpers.AssertRoundtrip(OneofWellKnownTypes.Parser, message, parsed => + { + Assert.AreEqual(message.OneofFieldCase, parsed.OneofFieldCase); + }); + } + + [Test] + [TestCase("x", "y", "y")] + [TestCase("x", "", "x")] + [TestCase("x", null, "x")] + [TestCase("", "y", "y")] + [TestCase("", "", "")] + [TestCase("", null, "")] + [TestCase(null, "y", "y")] + [TestCase(null, "", "")] + [TestCase(null, null, null)] + public void Merging(string original, string merged, string expected) + { + var originalMessage = new TestWellKnownTypes { StringField = original }; + var mergingMessage = new TestWellKnownTypes { StringField = merged }; + originalMessage.MergeFrom(mergingMessage); + Assert.AreEqual(expected, originalMessage.StringField); + + // Try it using MergeFrom(CodedInputStream) too... + originalMessage = new TestWellKnownTypes { StringField = original }; + originalMessage.MergeFrom(mergingMessage.ToByteArray()); + Assert.AreEqual(expected, originalMessage.StringField); + } + + // Merging is odd with wrapper types, due to the way that default values aren't emitted in + // the binary stream. In fact we cheat a little bit - a message with an explicitly present default + // value will have that default value ignored. See issue 615. Fixing this would require significant upheaval to + // the FieldCodec side of things. + [Test] + public void MergingStreamExplicitValue() + { + var message = new TestWellKnownTypes { Int32Field = 5 }; + + // Create a byte array which has the data of an Int32Value explicitly containing a value of 0. + // This wouldn't normally happen. + byte[] bytes; + var wrapperTag = WireFormat.MakeTag(TestWellKnownTypes.Int32FieldFieldNumber, WireFormat.WireType.LengthDelimited); + var valueTag = WireFormat.MakeTag(Int32Value.ValueFieldNumber, WireFormat.WireType.Varint); + using (var stream = new MemoryStream()) + { + var coded = new CodedOutputStream(stream); + coded.WriteTag(wrapperTag); + coded.WriteLength(2); // valueTag + a value 0, each one byte + coded.WriteTag(valueTag); + coded.WriteInt32(0); + coded.Flush(); + bytes = stream.ToArray(); + } + + message.MergeFrom(bytes); + // A normal implementation would have 0 now, as the explicit default would have been overwritten the 5. + // With the FieldCodec for Nullable, we can't tell the difference between an implicit 0 and an explicit 0. + Assert.AreEqual(5, message.Int32Field); + } + + [Test] + public void MergingStreamNoValue() + { + var message = new TestWellKnownTypes { Int32Field = 5 }; + + // Create a byte array which an Int32 field, but with no value. + var bytes = new TestWellKnownTypes { Int32Field = 0 }.ToByteArray(); + Assert.AreEqual(2, bytes.Length); // The tag for Int32Field is a single byte, then a byte indicating a 0-length message. + message.MergeFrom(bytes); + + // The "implicit" 0 did *not* overwrite the value. + // (This is the correct behaviour.) + Assert.AreEqual(5, message.Int32Field); + } + + // All permutations of origin/merging value being null, zero (default) or non-default. + // As this is the in-memory version, we don't need to worry about the difference between implicit and explicit 0. + [Test] + [TestCase(null, null, null)] + [TestCase(null, 0, 0)] + [TestCase(null, 5, 5)] + [TestCase(0, null, 0)] + [TestCase(0, 0, 0)] + [TestCase(0, 5, 5)] + [TestCase(5, null, 5)] + [TestCase(5, 0, 5)] + [TestCase(5, 10, 10)] + public void MergingMessageWithZero(int? originValue, int? mergingValue, int? expectedResult) + { + // This differs from the MergingStreamCornerCase because when we merge message *objects*, + // we ignore default values from the "source". + var message1 = new TestWellKnownTypes { Int32Field = originValue }; + var message2 = new TestWellKnownTypes { Int32Field = mergingValue }; + message1.MergeFrom(message2); + Assert.AreEqual(expectedResult, message1.Int32Field); + } + + [Test] + public void UnknownFieldInWrapperInt32FastPath() + { + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + var wrapperTag = WireFormat.MakeTag(TestWellKnownTypes.Int32FieldFieldNumber, WireFormat.WireType.LengthDelimited); + var unknownTag = WireFormat.MakeTag(15, WireFormat.WireType.Varint); + var valueTag = WireFormat.MakeTag(Int32Value.ValueFieldNumber, WireFormat.WireType.Varint); + + output.WriteTag(wrapperTag); + // Wrapper message is just long enough - 6 bytes - to use the wrapper fast-path. + output.WriteLength(6); // unknownTag + value 5 + valueType, each 1 byte, + value 65536, 3 bytes + output.WriteTag(unknownTag); + output.WriteInt32((int) valueTag); // Sneakily "pretend" it's a tag when it's really a value + output.WriteTag(valueTag); + output.WriteInt32(65536); + + output.Flush(); + Assert.AreEqual(8, stream.Length); // tag (1 byte) + length (1 byte) + message (6 bytes) + stream.Position = 0; + + MessageParsingHelpers.AssertReadingMessage( + TestWellKnownTypes.Parser, + stream.ToArray(), + message => Assert.AreEqual(65536, message.Int32Field)); + } + + [Test] + public void UnknownFieldInWrapperInt32SlowPath() + { + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + var wrapperTag = WireFormat.MakeTag(TestWellKnownTypes.Int32FieldFieldNumber, WireFormat.WireType.LengthDelimited); + var unknownTag = WireFormat.MakeTag(15, WireFormat.WireType.Varint); + var valueTag = WireFormat.MakeTag(Int32Value.ValueFieldNumber, WireFormat.WireType.Varint); + + output.WriteTag(wrapperTag); + // Wrapper message is too short to be used on the wrapper fast-path. + output.WriteLength(4); // unknownTag + value 5 + valueType + value 6, each 1 byte + output.WriteTag(unknownTag); + output.WriteInt32((int)valueTag); // Sneakily "pretend" it's a tag when it's really a value + output.WriteTag(valueTag); + output.WriteInt32(6); + + output.Flush(); + Assert.Less(stream.Length, 8); // tag (1 byte) + length (1 byte) + message + stream.Position = 0; + + MessageParsingHelpers.AssertReadingMessage( + TestWellKnownTypes.Parser, + stream.ToArray(), + message => Assert.AreEqual(6, message.Int32Field)); + } + + [Test] + public void UnknownFieldInWrapperInt64FastPath() + { + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + var wrapperTag = WireFormat.MakeTag(TestWellKnownTypes.Int64FieldFieldNumber, WireFormat.WireType.LengthDelimited); + var unknownTag = WireFormat.MakeTag(15, WireFormat.WireType.Varint); + var valueTag = WireFormat.MakeTag(Int64Value.ValueFieldNumber, WireFormat.WireType.Varint); + + output.WriteTag(wrapperTag); + // Wrapper message is just long enough - 10 bytes - to use the wrapper fast-path. + output.WriteLength(11); // unknownTag + value 5 + valueType, each 1 byte, + value 0xfffffffffffff, 8 bytes + output.WriteTag(unknownTag); + output.WriteInt64((int)valueTag); // Sneakily "pretend" it's a tag when it's really a value + output.WriteTag(valueTag); + output.WriteInt64(0xfffffffffffffL); + + output.Flush(); + Assert.AreEqual(13, stream.Length); // tag (1 byte) + length (1 byte) + message (11 bytes) + stream.Position = 0; + + MessageParsingHelpers.AssertReadingMessage( + TestWellKnownTypes.Parser, + stream.ToArray(), + message => Assert.AreEqual(0xfffffffffffffL, message.Int64Field)); + } + + [Test] + public void UnknownFieldInWrapperInt64SlowPath() + { + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + var wrapperTag = WireFormat.MakeTag(TestWellKnownTypes.Int64FieldFieldNumber, WireFormat.WireType.LengthDelimited); + var unknownTag = WireFormat.MakeTag(15, WireFormat.WireType.Varint); + var valueTag = WireFormat.MakeTag(Int64Value.ValueFieldNumber, WireFormat.WireType.Varint); + + output.WriteTag(wrapperTag); + // Wrapper message is too short to be used on the wrapper fast-path. + output.WriteLength(4); // unknownTag + value 5 + valueType + value 6, each 1 byte + output.WriteTag(unknownTag); + output.WriteInt64((int)valueTag); // Sneakily "pretend" it's a tag when it's really a value + output.WriteTag(valueTag); + output.WriteInt64(6); + + output.Flush(); + Assert.Less(stream.Length, 12); // tag (1 byte) + length (1 byte) + message + stream.Position = 0; + + MessageParsingHelpers.AssertReadingMessage( + TestWellKnownTypes.Parser, + stream.ToArray(), + message => Assert.AreEqual(6L, message.Int64Field)); + } + + [Test] + public void ClearWithReflection() + { + // String and Bytes are the tricky ones here, as the CLR type of the property + // is the same between the wrapper and non-wrapper types. + var message = new TestWellKnownTypes { StringField = "foo" }; + TestWellKnownTypes.Descriptor.Fields[TestWellKnownTypes.StringFieldFieldNumber].Accessor.Clear(message); + Assert.IsNull(message.StringField); + } + + [Test] + public void NaNComparisons() + { + var message1 = new TestWellKnownTypes { DoubleField = SampleNaNs.Regular }; + var message2 = new TestWellKnownTypes { DoubleField = SampleNaNs.PayloadFlipped }; + var message3 = new TestWellKnownTypes { DoubleField = SampleNaNs.Regular }; + + EqualityTester.AssertInequality(message1, message2); + EqualityTester.AssertEquality(message1, message3); + } + } +} diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Collections/RepeatedField.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Collections/RepeatedField.cs new file mode 100644 index 0000000..19114ca --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Collections/RepeatedField.cs @@ -0,0 +1,698 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Security; +using System.Threading; + +namespace Google.Protobuf.Collections +{ + /// + /// The contents of a repeated field: essentially, a collection with some extra + /// restrictions (no null values) and capabilities (deep cloning). + /// + /// + /// This implementation does not generally prohibit the use of types which are not + /// supported by Protocol Buffers but nor does it guarantee that all operations will work in such cases. + /// + /// The element type of the repeated field. + public sealed class RepeatedField : IList, IList, IDeepCloneable>, IEquatable> +#if !NET35 + , IReadOnlyList +#endif + { + private static readonly EqualityComparer EqualityComparer = ProtobufEqualityComparers.GetEqualityComparer(); + private static readonly T[] EmptyArray = new T[0]; + private const int MinArraySize = 8; + + private T[] array = EmptyArray; + private int count = 0; + + /// + /// Creates a deep clone of this repeated field. + /// + /// + /// If the field type is + /// a message type, each element is also cloned; otherwise, it is + /// assumed that the field type is primitive (including string and + /// bytes, both of which are immutable) and so a simple copy is + /// equivalent to a deep clone. + /// + /// A deep clone of this repeated field. + public RepeatedField Clone() + { + RepeatedField clone = new RepeatedField(); + if (array != EmptyArray) + { + clone.array = (T[])array.Clone(); + IDeepCloneable[] cloneableArray = clone.array as IDeepCloneable[]; + if (cloneableArray != null) + { + for (int i = 0; i < count; i++) + { + clone.array[i] = cloneableArray[i].Clone(); + } + } + } + clone.count = count; + return clone; + } + + /// + /// Adds the entries from the given input stream, decoding them with the specified codec. + /// + /// The input stream to read from. + /// The codec to use in order to read each entry. + public void AddEntriesFrom(CodedInputStream input, FieldCodec codec) + { + ParseContext.Initialize(input, out ParseContext ctx); + try + { + AddEntriesFrom(ref ctx, codec); + } + finally + { + ctx.CopyStateTo(input); + } + } + + /// + /// Adds the entries from the given parse context, decoding them with the specified codec. + /// + /// The input to read from. + /// The codec to use in order to read each entry. + [SecuritySafeCritical] + public void AddEntriesFrom(ref ParseContext ctx, FieldCodec codec) + { + // TODO: Inline some of the Add code, so we can avoid checking the size on every + // iteration. + uint tag = ctx.state.lastTag; + var reader = codec.ValueReader; + // Non-nullable value types can be packed or not. + if (FieldCodec.IsPackedRepeatedField(tag)) + { + int length = ctx.ReadLength(); + if (length > 0) + { + int oldLimit = SegmentedBufferHelper.PushLimit(ref ctx.state, length); + + // If the content is fixed size then we can calculate the length + // of the repeated field and pre-initialize the underlying collection. + // + // Check that the supplied length doesn't exceed the underlying buffer. + // That prevents a malicious length from initializing a very large collection. + if (codec.FixedSize > 0 && length % codec.FixedSize == 0 && ParsingPrimitives.IsDataAvailable(ref ctx.state, length)) + { + EnsureSize(count + (length / codec.FixedSize)); + + while (!SegmentedBufferHelper.IsReachedLimit(ref ctx.state)) + { + // Only FieldCodecs with a fixed size can reach here, and they are all known + // types that don't allow the user to specify a custom reader action. + // reader action will never return null. + array[count++] = reader(ref ctx); + } + } + else + { + // Content is variable size so add until we reach the limit. + while (!SegmentedBufferHelper.IsReachedLimit(ref ctx.state)) + { + Add(reader(ref ctx)); + } + } + SegmentedBufferHelper.PopLimit(ref ctx.state, oldLimit); + } + // Empty packed field. Odd, but valid - just ignore. + } + else + { + // Not packed... (possibly not packable) + do + { + Add(reader(ref ctx)); + } while (ParsingPrimitives.MaybeConsumeTag(ref ctx.buffer, ref ctx.state, tag)); + } + } + + /// + /// Calculates the size of this collection based on the given codec. + /// + /// The codec to use when encoding each field. + /// The number of bytes that would be written to an output by one of the WriteTo methods, + /// using the same codec. + public int CalculateSize(FieldCodec codec) + { + if (count == 0) + { + return 0; + } + uint tag = codec.Tag; + if (codec.PackedRepeatedField) + { + int dataSize = CalculatePackedDataSize(codec); + return CodedOutputStream.ComputeRawVarint32Size(tag) + + CodedOutputStream.ComputeLengthSize(dataSize) + + dataSize; + } + else + { + var sizeCalculator = codec.ValueSizeCalculator; + int size = count * CodedOutputStream.ComputeRawVarint32Size(tag); + if (codec.EndTag != 0) + { + size += count * CodedOutputStream.ComputeRawVarint32Size(codec.EndTag); + } + for (int i = 0; i < count; i++) + { + size += sizeCalculator(array[i]); + } + return size; + } + } + + private int CalculatePackedDataSize(FieldCodec codec) + { + int fixedSize = codec.FixedSize; + if (fixedSize == 0) + { + var calculator = codec.ValueSizeCalculator; + int tmp = 0; + for (int i = 0; i < count; i++) + { + tmp += calculator(array[i]); + } + return tmp; + } + else + { + return fixedSize * Count; + } + } + + /// + /// Writes the contents of this collection to the given , + /// encoding each value using the specified codec. + /// + /// The output stream to write to. + /// The codec to use when encoding each value. + public void WriteTo(CodedOutputStream output, FieldCodec codec) + { + WriteContext.Initialize(output, out WriteContext ctx); + try + { + WriteTo(ref ctx, codec); + } + finally + { + ctx.CopyStateTo(output); + } + } + + /// + /// Writes the contents of this collection to the given write context, + /// encoding each value using the specified codec. + /// + /// The write context to write to. + /// The codec to use when encoding each value. + [SecuritySafeCritical] + public void WriteTo(ref WriteContext ctx, FieldCodec codec) + { + if (count == 0) + { + return; + } + var writer = codec.ValueWriter; + var tag = codec.Tag; + if (codec.PackedRepeatedField) + { + // Packed primitive type + int size = CalculatePackedDataSize(codec); + ctx.WriteTag(tag); + ctx.WriteLength(size); + for (int i = 0; i < count; i++) + { + writer(ref ctx, array[i]); + } + } + else + { + // Not packed: a simple tag/value pair for each value. + // Can't use codec.WriteTagAndValue, as that omits default values. + for (int i = 0; i < count; i++) + { + ctx.WriteTag(tag); + writer(ref ctx, array[i]); + if (codec.EndTag != 0) + { + ctx.WriteTag(codec.EndTag); + } + } + } + } + + /// + /// Gets and sets the capacity of the RepeatedField's internal array. WHen set, the internal array is reallocated to the given capacity. + /// The new value is less than Count -or- when Count is less than 0. + /// + public int Capacity + { + get { return array.Length; } + set + { + if (value < count) + { + throw new ArgumentOutOfRangeException("Capacity", value, + $"Cannot set Capacity to a value smaller than the current item count, {count}"); + } + + if (value >= 0 && value != array.Length) + { + SetSize(value); + } + } + } + + // May increase the size of the internal array, but will never shrink it. + private void EnsureSize(int size) + { + if (array.Length < size) + { + size = Math.Max(size, MinArraySize); + int newSize = Math.Max(array.Length * 2, size); + SetSize(newSize); + } + } + + // Sets the internal array to an exact size. + private void SetSize(int size) + { + if (size != array.Length) + { + var tmp = new T[size]; + Array.Copy(array, 0, tmp, 0, count); + array = tmp; + } + } + + /// + /// Adds the specified item to the collection. + /// + /// The item to add. + public void Add(T item) + { + ProtoPreconditions.CheckNotNullUnconstrained(item, nameof(item)); + EnsureSize(count + 1); + array[count++] = item; + } + + /// + /// Removes all items from the collection. + /// + public void Clear() + { + array = EmptyArray; + count = 0; + } + + /// + /// Determines whether this collection contains the given item. + /// + /// The item to find. + /// true if this collection contains the given item; false otherwise. + public bool Contains(T item) + { + return IndexOf(item) != -1; + } + + /// + /// Copies this collection to the given array. + /// + /// The array to copy to. + /// The first index of the array to copy to. + public void CopyTo(T[] array, int arrayIndex) + { + Array.Copy(this.array, 0, array, arrayIndex, count); + } + + /// + /// Removes the specified item from the collection + /// + /// The item to remove. + /// true if the item was found and removed; false otherwise. + public bool Remove(T item) + { + int index = IndexOf(item); + if (index == -1) + { + return false; + } + Array.Copy(array, index + 1, array, index, count - index - 1); + count--; + array[count] = default(T); + return true; + } + + /// + /// Gets the number of elements contained in the collection. + /// + public int Count => count; + + /// + /// Gets a value indicating whether the collection is read-only. + /// + public bool IsReadOnly => false; + + /// + /// Adds all of the specified values into this collection. + /// + /// The values to add to this collection. + public void AddRange(IEnumerable values) + { + ProtoPreconditions.CheckNotNull(values, nameof(values)); + + // Optimization 1: If the collection we're adding is already a RepeatedField, + // we know the values are valid. + var otherRepeatedField = values as RepeatedField; + if (otherRepeatedField != null) + { + EnsureSize(count + otherRepeatedField.count); + Array.Copy(otherRepeatedField.array, 0, array, count, otherRepeatedField.count); + count += otherRepeatedField.count; + return; + } + + // Optimization 2: The collection is an ICollection, so we can expand + // just once and ask the collection to copy itself into the array. + var collection = values as ICollection; + if (collection != null) + { + var extraCount = collection.Count; + // For reference types and nullable value types, we need to check that there are no nulls + // present. (This isn't a thread-safe approach, but we don't advertise this is thread-safe.) + // We expect the JITter to optimize this test to true/false, so it's effectively conditional + // specialization. + if (default(T) == null) + { + // TODO: Measure whether iterating once to check and then letting the collection copy + // itself is faster or slower than iterating and adding as we go. For large + // collections this will not be great in terms of cache usage... but the optimized + // copy may be significantly faster than doing it one at a time. + foreach (var item in collection) + { + if (item == null) + { + throw new ArgumentException("Sequence contained null element", nameof(values)); + } + } + } + EnsureSize(count + extraCount); + collection.CopyTo(array, count); + count += extraCount; + return; + } + + // We *could* check for ICollection as well, but very very few collections implement + // ICollection but not ICollection. (HashSet does, for one...) + + // Fall back to a slower path of adding items one at a time. + foreach (T item in values) + { + Add(item); + } + } + + /// + /// Adds all of the specified values into this collection. This method is present to + /// allow repeated fields to be constructed from queries within collection initializers. + /// Within non-collection-initializer code, consider using the equivalent + /// method instead for clarity. + /// + /// The values to add to this collection. + public void Add(IEnumerable values) + { + AddRange(values); + } + + /// + /// Returns an enumerator that iterates through the collection. + /// + /// + /// An enumerator that can be used to iterate through the collection. + /// + public IEnumerator GetEnumerator() + { + for (int i = 0; i < count; i++) + { + yield return array[i]; + } + } + + /// + /// Determines whether the specified , is equal to this instance. + /// + /// The to compare with this instance. + /// + /// true if the specified is equal to this instance; otherwise, false. + /// + public override bool Equals(object obj) + { + return Equals(obj as RepeatedField); + } + + /// + /// Returns an enumerator that iterates through a collection. + /// + /// + /// An object that can be used to iterate through the collection. + /// + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + /// + /// Returns a hash code for this instance. + /// + /// + /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. + /// + public override int GetHashCode() + { + int hash = 0; + for (int i = 0; i < count; i++) + { + hash = hash * 31 + array[i].GetHashCode(); + } + return hash; + } + + /// + /// Compares this repeated field with another for equality. + /// + /// The repeated field to compare this with. + /// true if refers to an equal repeated field; false otherwise. + public bool Equals(RepeatedField other) + { + if (ReferenceEquals(other, null)) + { + return false; + } + if (ReferenceEquals(other, this)) + { + return true; + } + if (other.Count != this.Count) + { + return false; + } + EqualityComparer comparer = EqualityComparer; + for (int i = 0; i < count; i++) + { + if (!comparer.Equals(array[i], other.array[i])) + { + return false; + } + } + return true; + } + + /// + /// Returns the index of the given item within the collection, or -1 if the item is not + /// present. + /// + /// The item to find in the collection. + /// The zero-based index of the item, or -1 if it is not found. + public int IndexOf(T item) + { + ProtoPreconditions.CheckNotNullUnconstrained(item, nameof(item)); + EqualityComparer comparer = EqualityComparer; + for (int i = 0; i < count; i++) + { + if (comparer.Equals(array[i], item)) + { + return i; + } + } + return -1; + } + + /// + /// Inserts the given item at the specified index. + /// + /// The index at which to insert the item. + /// The item to insert. + public void Insert(int index, T item) + { + ProtoPreconditions.CheckNotNullUnconstrained(item, nameof(item)); + if (index < 0 || index > count) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + EnsureSize(count + 1); + Array.Copy(array, index, array, index + 1, count - index); + array[index] = item; + count++; + } + + /// + /// Removes the item at the given index. + /// + /// The zero-based index of the item to remove. + public void RemoveAt(int index) + { + if (index < 0 || index >= count) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + Array.Copy(array, index + 1, array, index, count - index - 1); + count--; + array[count] = default(T); + } + + /// + /// Returns a string representation of this repeated field, in the same + /// way as it would be represented by the default JSON formatter. + /// + public override string ToString() + { + var writer = new StringWriter(); + JsonFormatter.Default.WriteList(writer, this); + return writer.ToString(); + } + + /// + /// Gets or sets the item at the specified index. + /// + /// + /// The element at the specified index. + /// + /// The zero-based index of the element to get or set. + /// The item at the specified index. + public T this[int index] + { + get + { + if (index < 0 || index >= count) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + return array[index]; + } + set + { + if (index < 0 || index >= count) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + ProtoPreconditions.CheckNotNullUnconstrained(value, nameof(value)); + array[index] = value; + } + } + + #region Explicit interface implementation for IList and ICollection. + bool IList.IsFixedSize => false; + + void ICollection.CopyTo(Array array, int index) + { + Array.Copy(this.array, 0, array, index, count); + } + + bool ICollection.IsSynchronized => false; + + object ICollection.SyncRoot => this; + + object IList.this[int index] + { + get { return this[index]; } + set { this[index] = (T)value; } + } + + int IList.Add(object value) + { + Add((T) value); + return count - 1; + } + + bool IList.Contains(object value) + { + return (value is T && Contains((T)value)); + } + + int IList.IndexOf(object value) + { + if (!(value is T)) + { + return -1; + } + return IndexOf((T)value); + } + + void IList.Insert(int index, object value) + { + Insert(index, (T) value); + } + + void IList.Remove(object value) + { + if (!(value is T)) + { + return; + } + Remove((T)value); + } + #endregion + } +} diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Compatibility/UnconditionalSuppressMessageAttribute.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Compatibility/UnconditionalSuppressMessageAttribute.cs new file mode 100644 index 0000000..a02a145 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Compatibility/UnconditionalSuppressMessageAttribute.cs @@ -0,0 +1,117 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +#if !NET5_0_OR_GREATER +// Copied with permission from https://github.com/dotnet/runtime/tree/8fbf206d0e518b45ca855832e8bfb391afa85972/src/libraries/System.Private.CoreLib/src/System/Diagnostics/CodeAnalysis +namespace System.Diagnostics.CodeAnalysis +{ + /// + /// Suppresses reporting of a specific rule violation, allowing multiple suppressions on a + /// single code artifact. + /// + /// + /// is different than + /// in that it doesn't have a + /// . So it is always preserved in the compiled assembly. + /// + [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] + internal sealed class UnconditionalSuppressMessageAttribute : Attribute + { + /// + /// Initializes a new instance of the + /// class, specifying the category of the tool and the identifier for an analysis rule. + /// + /// The category for the attribute. + /// The identifier of the analysis rule the attribute applies to. + public UnconditionalSuppressMessageAttribute(string category, string checkId) + { + Category = category; + CheckId = checkId; + } + + /// + /// Gets the category identifying the classification of the attribute. + /// + /// + /// The property describes the tool or tool analysis category + /// for which a message suppression attribute applies. + /// + public string Category { get; } + + /// + /// Gets the identifier of the analysis tool rule to be suppressed. + /// + /// + /// Concatenated together, the and + /// properties form a unique check identifier. + /// + public string CheckId { get; } + + /// + /// Gets or sets the scope of the code that is relevant for the attribute. + /// + /// + /// The Scope property is an optional argument that specifies the metadata scope for which + /// the attribute is relevant. + /// + public string Scope { get; set; } + + /// + /// Gets or sets a fully qualified path that represents the target of the attribute. + /// + /// + /// The property is an optional argument identifying the analysis target + /// of the attribute. An example value is "System.IO.Stream.ctor():System.Void". + /// Because it is fully qualified, it can be long, particularly for targets such as parameters. + /// The analysis tool user interface should be capable of automatically formatting the parameter. + /// + public string Target { get; set; } + + /// + /// Gets or sets an optional argument expanding on exclusion criteria. + /// + /// + /// The property is an optional argument that specifies additional + /// exclusion where the literal metadata target is not sufficiently precise. For example, + /// the cannot be applied within a method, + /// and it may be desirable to suppress a violation against a statement in the method that will + /// give a rule violation, but not against all statements in the method. + /// + public string MessageId { get; set; } + + /// + /// Gets or sets the justification for suppressing the code analysis message. + /// + public string Justification { get; set; } + } +} +#endif diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/LimitedInputStream.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/LimitedInputStream.cs new file mode 100644 index 0000000..50ead9c --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/LimitedInputStream.cs @@ -0,0 +1,110 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; +using System.IO; + +namespace Google.Protobuf +{ + /// + /// Stream implementation which proxies another stream, only allowing a certain amount + /// of data to be read. Note that this is only used to read delimited streams, so it + /// doesn't attempt to implement everything. + /// + internal sealed class LimitedInputStream : Stream + { + private readonly Stream proxied; + private int bytesLeft; + + internal LimitedInputStream(Stream proxied, int size) + { + this.proxied = proxied; + bytesLeft = size; + } + + public override bool CanRead + { + get { return true; } + } + + public override bool CanSeek + { + get { return false; } + } + + public override bool CanWrite + { + get { return false; } + } + + public override void Flush() + { + } + + public override long Length + { + get { throw new NotSupportedException(); } + } + + public override long Position + { + get { throw new NotSupportedException(); } + set { throw new NotSupportedException(); } + } + + public override int Read(byte[] buffer, int offset, int count) + { + if (bytesLeft > 0) + { + int bytesRead = proxied.Read(buffer, offset, Math.Min(bytesLeft, count)); + bytesLeft -= bytesRead; + return bytesRead; + } + return 0; + } + + public override long Seek(long offset, SeekOrigin origin) + { + throw new NotSupportedException(); + } + + public override void SetLength(long value) + { + throw new NotSupportedException(); + } + + public override void Write(byte[] buffer, int offset, int count) + { + throw new NotSupportedException(); + } + } +} diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/ParserInternalState.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/ParserInternalState.cs new file mode 100644 index 0000000..cb4f471 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/ParserInternalState.cs @@ -0,0 +1,115 @@ +#region Copyright notice and license +// 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. +#endregion + +using System; +using System.Buffers; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security; +using System.Text; +using Google.Protobuf.Collections; + +namespace Google.Protobuf +{ + + // warning: this is a mutable struct, so it needs to be only passed as a ref! + internal struct ParserInternalState + { + // NOTE: the Span representing the current buffer is kept separate so that this doesn't have to be a ref struct and so it can + // be included in CodedInputStream's internal state + + /// + /// The position within the current buffer (i.e. the next byte to read) + /// + internal int bufferPos; + + /// + /// Size of the current buffer + /// + internal int bufferSize; + + /// + /// If we are currently inside a length-delimited block, this is the number of + /// bytes in the buffer that are still available once we leave the delimited block. + /// + internal int bufferSizeAfterLimit; + + /// + /// The absolute position of the end of the current length-delimited block (including totalBytesRetired) + /// + internal int currentLimit; + + /// + /// The total number of consumed before the start of the current buffer. The + /// total bytes read up to the current position can be computed as + /// totalBytesRetired + bufferPos. + /// + internal int totalBytesRetired; + + internal int recursionDepth; // current recursion depth + + internal SegmentedBufferHelper segmentedBufferHelper; + + /// + /// The last tag we read. 0 indicates we've read to the end of the stream + /// (or haven't read anything yet). + /// + internal uint lastTag; + + /// + /// The next tag, used to store the value read by PeekTag. + /// + internal uint nextTag; + internal bool hasNextTag; + + // these fields are configuration, they should be readonly + internal int sizeLimit; + internal int recursionLimit; + + // If non-null, the top level parse method was started with given coded input stream as an argument + // which also means we can potentially fallback to calling MergeFrom(CodedInputStream cis) if needed. + internal CodedInputStream CodedInputStream => segmentedBufferHelper.CodedInputStream; + + /// + /// Internal-only property; when set to true, unknown fields will be discarded while parsing. + /// + internal bool DiscardUnknownFields { get; set; } + + /// + /// Internal-only property; provides extension identifiers to compatible messages while parsing. + /// + internal ExtensionRegistry ExtensionRegistry { get; set; } + } +} \ No newline at end of file diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/Descriptor.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/Descriptor.cs new file mode 100644 index 0000000..8d39856 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/Descriptor.cs @@ -0,0 +1,11020 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/descriptor.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Google.Protobuf.Reflection { + + /// Holder for reflection information generated from google/protobuf/descriptor.proto + public static partial class DescriptorReflection { + + #region Descriptor + /// File descriptor for google/protobuf/descriptor.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static DescriptorReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "CiBnb29nbGUvcHJvdG9idWYvZGVzY3JpcHRvci5wcm90bxIPZ29vZ2xlLnBy", + "b3RvYnVmIkcKEUZpbGVEZXNjcmlwdG9yU2V0EjIKBGZpbGUYASADKAsyJC5n", + "b29nbGUucHJvdG9idWYuRmlsZURlc2NyaXB0b3JQcm90byLbAwoTRmlsZURl", + "c2NyaXB0b3JQcm90bxIMCgRuYW1lGAEgASgJEg8KB3BhY2thZ2UYAiABKAkS", + "EgoKZGVwZW5kZW5jeRgDIAMoCRIZChFwdWJsaWNfZGVwZW5kZW5jeRgKIAMo", + "BRIXCg93ZWFrX2RlcGVuZGVuY3kYCyADKAUSNgoMbWVzc2FnZV90eXBlGAQg", + "AygLMiAuZ29vZ2xlLnByb3RvYnVmLkRlc2NyaXB0b3JQcm90bxI3CgllbnVt", + "X3R5cGUYBSADKAsyJC5nb29nbGUucHJvdG9idWYuRW51bURlc2NyaXB0b3JQ", + "cm90bxI4CgdzZXJ2aWNlGAYgAygLMicuZ29vZ2xlLnByb3RvYnVmLlNlcnZp", + "Y2VEZXNjcmlwdG9yUHJvdG8SOAoJZXh0ZW5zaW9uGAcgAygLMiUuZ29vZ2xl", + "LnByb3RvYnVmLkZpZWxkRGVzY3JpcHRvclByb3RvEi0KB29wdGlvbnMYCCAB", + "KAsyHC5nb29nbGUucHJvdG9idWYuRmlsZU9wdGlvbnMSOQoQc291cmNlX2Nv", + "ZGVfaW5mbxgJIAEoCzIfLmdvb2dsZS5wcm90b2J1Zi5Tb3VyY2VDb2RlSW5m", + "bxIOCgZzeW50YXgYDCABKAkiqQUKD0Rlc2NyaXB0b3JQcm90bxIMCgRuYW1l", + "GAEgASgJEjQKBWZpZWxkGAIgAygLMiUuZ29vZ2xlLnByb3RvYnVmLkZpZWxk", + "RGVzY3JpcHRvclByb3RvEjgKCWV4dGVuc2lvbhgGIAMoCzIlLmdvb2dsZS5w", + "cm90b2J1Zi5GaWVsZERlc2NyaXB0b3JQcm90bxI1CgtuZXN0ZWRfdHlwZRgD", + "IAMoCzIgLmdvb2dsZS5wcm90b2J1Zi5EZXNjcmlwdG9yUHJvdG8SNwoJZW51", + "bV90eXBlGAQgAygLMiQuZ29vZ2xlLnByb3RvYnVmLkVudW1EZXNjcmlwdG9y", + "UHJvdG8SSAoPZXh0ZW5zaW9uX3JhbmdlGAUgAygLMi8uZ29vZ2xlLnByb3Rv", + "YnVmLkRlc2NyaXB0b3JQcm90by5FeHRlbnNpb25SYW5nZRI5CgpvbmVvZl9k", + "ZWNsGAggAygLMiUuZ29vZ2xlLnByb3RvYnVmLk9uZW9mRGVzY3JpcHRvclBy", + "b3RvEjAKB29wdGlvbnMYByABKAsyHy5nb29nbGUucHJvdG9idWYuTWVzc2Fn", + "ZU9wdGlvbnMSRgoOcmVzZXJ2ZWRfcmFuZ2UYCSADKAsyLi5nb29nbGUucHJv", + "dG9idWYuRGVzY3JpcHRvclByb3RvLlJlc2VydmVkUmFuZ2USFQoNcmVzZXJ2", + "ZWRfbmFtZRgKIAMoCRplCg5FeHRlbnNpb25SYW5nZRINCgVzdGFydBgBIAEo", + "BRILCgNlbmQYAiABKAUSNwoHb3B0aW9ucxgDIAEoCzImLmdvb2dsZS5wcm90", + "b2J1Zi5FeHRlbnNpb25SYW5nZU9wdGlvbnMaKwoNUmVzZXJ2ZWRSYW5nZRIN", + "CgVzdGFydBgBIAEoBRILCgNlbmQYAiABKAUiZwoVRXh0ZW5zaW9uUmFuZ2VP", + "cHRpb25zEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdvb2ds", + "ZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uKgkI6AcQgICAgAIi1QUK", + "FEZpZWxkRGVzY3JpcHRvclByb3RvEgwKBG5hbWUYASABKAkSDgoGbnVtYmVy", + "GAMgASgFEjoKBWxhYmVsGAQgASgOMisuZ29vZ2xlLnByb3RvYnVmLkZpZWxk", + "RGVzY3JpcHRvclByb3RvLkxhYmVsEjgKBHR5cGUYBSABKA4yKi5nb29nbGUu", + "cHJvdG9idWYuRmllbGREZXNjcmlwdG9yUHJvdG8uVHlwZRIRCgl0eXBlX25h", + "bWUYBiABKAkSEAoIZXh0ZW5kZWUYAiABKAkSFQoNZGVmYXVsdF92YWx1ZRgH", + "IAEoCRITCgtvbmVvZl9pbmRleBgJIAEoBRIRCglqc29uX25hbWUYCiABKAkS", + "LgoHb3B0aW9ucxgIIAEoCzIdLmdvb2dsZS5wcm90b2J1Zi5GaWVsZE9wdGlv", + "bnMSFwoPcHJvdG8zX29wdGlvbmFsGBEgASgIIrYCCgRUeXBlEg8KC1RZUEVf", + "RE9VQkxFEAESDgoKVFlQRV9GTE9BVBACEg4KClRZUEVfSU5UNjQQAxIPCgtU", + "WVBFX1VJTlQ2NBAEEg4KClRZUEVfSU5UMzIQBRIQCgxUWVBFX0ZJWEVENjQQ", + "BhIQCgxUWVBFX0ZJWEVEMzIQBxINCglUWVBFX0JPT0wQCBIPCgtUWVBFX1NU", + "UklORxAJEg4KClRZUEVfR1JPVVAQChIQCgxUWVBFX01FU1NBR0UQCxIOCgpU", + "WVBFX0JZVEVTEAwSDwoLVFlQRV9VSU5UMzIQDRINCglUWVBFX0VOVU0QDhIR", + "Cg1UWVBFX1NGSVhFRDMyEA8SEQoNVFlQRV9TRklYRUQ2NBAQEg8KC1RZUEVf", + "U0lOVDMyEBESDwoLVFlQRV9TSU5UNjQQEiJDCgVMYWJlbBISCg5MQUJFTF9P", + "UFRJT05BTBABEhIKDkxBQkVMX1JFUVVJUkVEEAISEgoOTEFCRUxfUkVQRUFU", + "RUQQAyJUChRPbmVvZkRlc2NyaXB0b3JQcm90bxIMCgRuYW1lGAEgASgJEi4K", + "B29wdGlvbnMYAiABKAsyHS5nb29nbGUucHJvdG9idWYuT25lb2ZPcHRpb25z", + "IqQCChNFbnVtRGVzY3JpcHRvclByb3RvEgwKBG5hbWUYASABKAkSOAoFdmFs", + "dWUYAiADKAsyKS5nb29nbGUucHJvdG9idWYuRW51bVZhbHVlRGVzY3JpcHRv", + "clByb3RvEi0KB29wdGlvbnMYAyABKAsyHC5nb29nbGUucHJvdG9idWYuRW51", + "bU9wdGlvbnMSTgoOcmVzZXJ2ZWRfcmFuZ2UYBCADKAsyNi5nb29nbGUucHJv", + "dG9idWYuRW51bURlc2NyaXB0b3JQcm90by5FbnVtUmVzZXJ2ZWRSYW5nZRIV", + "Cg1yZXNlcnZlZF9uYW1lGAUgAygJGi8KEUVudW1SZXNlcnZlZFJhbmdlEg0K", + "BXN0YXJ0GAEgASgFEgsKA2VuZBgCIAEoBSJsChhFbnVtVmFsdWVEZXNjcmlw", + "dG9yUHJvdG8SDAoEbmFtZRgBIAEoCRIOCgZudW1iZXIYAiABKAUSMgoHb3B0", + "aW9ucxgDIAEoCzIhLmdvb2dsZS5wcm90b2J1Zi5FbnVtVmFsdWVPcHRpb25z", + "IpABChZTZXJ2aWNlRGVzY3JpcHRvclByb3RvEgwKBG5hbWUYASABKAkSNgoG", + "bWV0aG9kGAIgAygLMiYuZ29vZ2xlLnByb3RvYnVmLk1ldGhvZERlc2NyaXB0", + "b3JQcm90bxIwCgdvcHRpb25zGAMgASgLMh8uZ29vZ2xlLnByb3RvYnVmLlNl", + "cnZpY2VPcHRpb25zIsEBChVNZXRob2REZXNjcmlwdG9yUHJvdG8SDAoEbmFt", + "ZRgBIAEoCRISCgppbnB1dF90eXBlGAIgASgJEhMKC291dHB1dF90eXBlGAMg", + "ASgJEi8KB29wdGlvbnMYBCABKAsyHi5nb29nbGUucHJvdG9idWYuTWV0aG9k", + "T3B0aW9ucxIfChBjbGllbnRfc3RyZWFtaW5nGAUgASgIOgVmYWxzZRIfChBz", + "ZXJ2ZXJfc3RyZWFtaW5nGAYgASgIOgVmYWxzZSKlBgoLRmlsZU9wdGlvbnMS", + "FAoMamF2YV9wYWNrYWdlGAEgASgJEhwKFGphdmFfb3V0ZXJfY2xhc3NuYW1l", + "GAggASgJEiIKE2phdmFfbXVsdGlwbGVfZmlsZXMYCiABKAg6BWZhbHNlEikK", + "HWphdmFfZ2VuZXJhdGVfZXF1YWxzX2FuZF9oYXNoGBQgASgIQgIYARIlChZq", + "YXZhX3N0cmluZ19jaGVja191dGY4GBsgASgIOgVmYWxzZRJGCgxvcHRpbWl6", + "ZV9mb3IYCSABKA4yKS5nb29nbGUucHJvdG9idWYuRmlsZU9wdGlvbnMuT3B0", + "aW1pemVNb2RlOgVTUEVFRBISCgpnb19wYWNrYWdlGAsgASgJEiIKE2NjX2dl", + "bmVyaWNfc2VydmljZXMYECABKAg6BWZhbHNlEiQKFWphdmFfZ2VuZXJpY19z", + "ZXJ2aWNlcxgRIAEoCDoFZmFsc2USIgoTcHlfZ2VuZXJpY19zZXJ2aWNlcxgS", + "IAEoCDoFZmFsc2USIwoUcGhwX2dlbmVyaWNfc2VydmljZXMYKiABKAg6BWZh", + "bHNlEhkKCmRlcHJlY2F0ZWQYFyABKAg6BWZhbHNlEh4KEGNjX2VuYWJsZV9h", + "cmVuYXMYHyABKAg6BHRydWUSGQoRb2JqY19jbGFzc19wcmVmaXgYJCABKAkS", + "GAoQY3NoYXJwX25hbWVzcGFjZRglIAEoCRIUCgxzd2lmdF9wcmVmaXgYJyAB", + "KAkSGAoQcGhwX2NsYXNzX3ByZWZpeBgoIAEoCRIVCg1waHBfbmFtZXNwYWNl", + "GCkgASgJEh4KFnBocF9tZXRhZGF0YV9uYW1lc3BhY2UYLCABKAkSFAoMcnVi", + "eV9wYWNrYWdlGC0gASgJEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMo", + "CzIkLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uIjoKDE9w", + "dGltaXplTW9kZRIJCgVTUEVFRBABEg0KCUNPREVfU0laRRACEhAKDExJVEVf", + "UlVOVElNRRADKgkI6AcQgICAgAJKBAgmECcihAIKDk1lc3NhZ2VPcHRpb25z", + "EiYKF21lc3NhZ2Vfc2V0X3dpcmVfZm9ybWF0GAEgASgIOgVmYWxzZRIuCh9u", + "b19zdGFuZGFyZF9kZXNjcmlwdG9yX2FjY2Vzc29yGAIgASgIOgVmYWxzZRIZ", + "CgpkZXByZWNhdGVkGAMgASgIOgVmYWxzZRIRCgltYXBfZW50cnkYByABKAgS", + "QwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3Rv", + "YnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAkoECAQQBUoECAUQ", + "BkoECAYQB0oECAgQCUoECAkQCiKeAwoMRmllbGRPcHRpb25zEjoKBWN0eXBl", + "GAEgASgOMiMuZ29vZ2xlLnByb3RvYnVmLkZpZWxkT3B0aW9ucy5DVHlwZToG", + "U1RSSU5HEg4KBnBhY2tlZBgCIAEoCBI/CgZqc3R5cGUYBiABKA4yJC5nb29n", + "bGUucHJvdG9idWYuRmllbGRPcHRpb25zLkpTVHlwZToJSlNfTk9STUFMEhMK", + "BGxhenkYBSABKAg6BWZhbHNlEhkKCmRlcHJlY2F0ZWQYAyABKAg6BWZhbHNl", + "EhMKBHdlYWsYCiABKAg6BWZhbHNlEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9u", + "GOcHIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9u", + "Ii8KBUNUeXBlEgoKBlNUUklORxAAEggKBENPUkQQARIQCgxTVFJJTkdfUElF", + "Q0UQAiI1CgZKU1R5cGUSDQoJSlNfTk9STUFMEAASDQoJSlNfU1RSSU5HEAES", + "DQoJSlNfTlVNQkVSEAIqCQjoBxCAgICAAkoECAQQBSJeCgxPbmVvZk9wdGlv", + "bnMSQwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnBy", + "b3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAiKTAQoLRW51", + "bU9wdGlvbnMSEwoLYWxsb3dfYWxpYXMYAiABKAgSGQoKZGVwcmVjYXRlZBgD", + "IAEoCDoFZmFsc2USQwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQu", + "Z29vZ2xlLnByb3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICA", + "AkoECAUQBiJ9ChBFbnVtVmFsdWVPcHRpb25zEhkKCmRlcHJlY2F0ZWQYASAB", + "KAg6BWZhbHNlEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdv", + "b2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uKgkI6AcQgICAgAIi", + "ewoOU2VydmljZU9wdGlvbnMSGQoKZGVwcmVjYXRlZBghIAEoCDoFZmFsc2US", + "QwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3Rv", + "YnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAiKtAgoNTWV0aG9k", + "T3B0aW9ucxIZCgpkZXByZWNhdGVkGCEgASgIOgVmYWxzZRJfChFpZGVtcG90", + "ZW5jeV9sZXZlbBgiIAEoDjIvLmdvb2dsZS5wcm90b2J1Zi5NZXRob2RPcHRp", + "b25zLklkZW1wb3RlbmN5TGV2ZWw6E0lERU1QT1RFTkNZX1VOS05PV04SQwoU", + "dW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVm", + "LlVuaW50ZXJwcmV0ZWRPcHRpb24iUAoQSWRlbXBvdGVuY3lMZXZlbBIXChNJ", + "REVNUE9URU5DWV9VTktOT1dOEAASEwoPTk9fU0lERV9FRkZFQ1RTEAESDgoK", + "SURFTVBPVEVOVBACKgkI6AcQgICAgAIingIKE1VuaW50ZXJwcmV0ZWRPcHRp", + "b24SOwoEbmFtZRgCIAMoCzItLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJl", + "dGVkT3B0aW9uLk5hbWVQYXJ0EhgKEGlkZW50aWZpZXJfdmFsdWUYAyABKAkS", + "GgoScG9zaXRpdmVfaW50X3ZhbHVlGAQgASgEEhoKEm5lZ2F0aXZlX2ludF92", + "YWx1ZRgFIAEoAxIUCgxkb3VibGVfdmFsdWUYBiABKAESFAoMc3RyaW5nX3Zh", + "bHVlGAcgASgMEhcKD2FnZ3JlZ2F0ZV92YWx1ZRgIIAEoCRozCghOYW1lUGFy", + "dBIRCgluYW1lX3BhcnQYASACKAkSFAoMaXNfZXh0ZW5zaW9uGAIgAigIItUB", + "Cg5Tb3VyY2VDb2RlSW5mbxI6Cghsb2NhdGlvbhgBIAMoCzIoLmdvb2dsZS5w", + "cm90b2J1Zi5Tb3VyY2VDb2RlSW5mby5Mb2NhdGlvbhqGAQoITG9jYXRpb24S", + "EAoEcGF0aBgBIAMoBUICEAESEAoEc3BhbhgCIAMoBUICEAESGAoQbGVhZGlu", + "Z19jb21tZW50cxgDIAEoCRIZChF0cmFpbGluZ19jb21tZW50cxgEIAEoCRIh", + "ChlsZWFkaW5nX2RldGFjaGVkX2NvbW1lbnRzGAYgAygJIqcBChFHZW5lcmF0", + "ZWRDb2RlSW5mbxJBCgphbm5vdGF0aW9uGAEgAygLMi0uZ29vZ2xlLnByb3Rv", + "YnVmLkdlbmVyYXRlZENvZGVJbmZvLkFubm90YXRpb24aTwoKQW5ub3RhdGlv", + "bhIQCgRwYXRoGAEgAygFQgIQARITCgtzb3VyY2VfZmlsZRgCIAEoCRINCgVi", + "ZWdpbhgDIAEoBRILCgNlbmQYBCABKAVCfgoTY29tLmdvb2dsZS5wcm90b2J1", + "ZkIQRGVzY3JpcHRvclByb3Rvc0gBWi1nb29nbGUuZ29sYW5nLm9yZy9wcm90", + "b2J1Zi90eXBlcy9kZXNjcmlwdG9ycGL4AQGiAgNHUEKqAhpHb29nbGUuUHJv", + "dG9idWYuUmVmbGVjdGlvbg==")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.FileDescriptorSet), global::Google.Protobuf.Reflection.FileDescriptorSet.Parser, new[]{ "File" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.FileDescriptorProto), global::Google.Protobuf.Reflection.FileDescriptorProto.Parser, new[]{ "Name", "Package", "Dependency", "PublicDependency", "WeakDependency", "MessageType", "EnumType", "Service", "Extension", "Options", "SourceCodeInfo", "Syntax" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.DescriptorProto), global::Google.Protobuf.Reflection.DescriptorProto.Parser, new[]{ "Name", "Field", "Extension", "NestedType", "EnumType", "ExtensionRange", "OneofDecl", "Options", "ReservedRange", "ReservedName" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.DescriptorProto.Types.ExtensionRange), global::Google.Protobuf.Reflection.DescriptorProto.Types.ExtensionRange.Parser, new[]{ "Start", "End", "Options" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.DescriptorProto.Types.ReservedRange), global::Google.Protobuf.Reflection.DescriptorProto.Types.ReservedRange.Parser, new[]{ "Start", "End" }, null, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.ExtensionRangeOptions), global::Google.Protobuf.Reflection.ExtensionRangeOptions.Parser, new[]{ "UninterpretedOption" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.FieldDescriptorProto), global::Google.Protobuf.Reflection.FieldDescriptorProto.Parser, new[]{ "Name", "Number", "Label", "Type", "TypeName", "Extendee", "DefaultValue", "OneofIndex", "JsonName", "Options", "Proto3Optional" }, null, new[]{ typeof(global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Type), typeof(global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Label) }, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.OneofDescriptorProto), global::Google.Protobuf.Reflection.OneofDescriptorProto.Parser, new[]{ "Name", "Options" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.EnumDescriptorProto), global::Google.Protobuf.Reflection.EnumDescriptorProto.Parser, new[]{ "Name", "Value", "Options", "ReservedRange", "ReservedName" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.EnumDescriptorProto.Types.EnumReservedRange), global::Google.Protobuf.Reflection.EnumDescriptorProto.Types.EnumReservedRange.Parser, new[]{ "Start", "End" }, null, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.EnumValueDescriptorProto), global::Google.Protobuf.Reflection.EnumValueDescriptorProto.Parser, new[]{ "Name", "Number", "Options" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.ServiceDescriptorProto), global::Google.Protobuf.Reflection.ServiceDescriptorProto.Parser, new[]{ "Name", "Method", "Options" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.MethodDescriptorProto), global::Google.Protobuf.Reflection.MethodDescriptorProto.Parser, new[]{ "Name", "InputType", "OutputType", "Options", "ClientStreaming", "ServerStreaming" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.FileOptions), global::Google.Protobuf.Reflection.FileOptions.Parser, new[]{ "JavaPackage", "JavaOuterClassname", "JavaMultipleFiles", "JavaGenerateEqualsAndHash", "JavaStringCheckUtf8", "OptimizeFor", "GoPackage", "CcGenericServices", "JavaGenericServices", "PyGenericServices", "PhpGenericServices", "Deprecated", "CcEnableArenas", "ObjcClassPrefix", "CsharpNamespace", "SwiftPrefix", "PhpClassPrefix", "PhpNamespace", "PhpMetadataNamespace", "RubyPackage", "UninterpretedOption" }, null, new[]{ typeof(global::Google.Protobuf.Reflection.FileOptions.Types.OptimizeMode) }, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.MessageOptions), global::Google.Protobuf.Reflection.MessageOptions.Parser, new[]{ "MessageSetWireFormat", "NoStandardDescriptorAccessor", "Deprecated", "MapEntry", "UninterpretedOption" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.FieldOptions), global::Google.Protobuf.Reflection.FieldOptions.Parser, new[]{ "Ctype", "Packed", "Jstype", "Lazy", "Deprecated", "Weak", "UninterpretedOption" }, null, new[]{ typeof(global::Google.Protobuf.Reflection.FieldOptions.Types.CType), typeof(global::Google.Protobuf.Reflection.FieldOptions.Types.JSType) }, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.OneofOptions), global::Google.Protobuf.Reflection.OneofOptions.Parser, new[]{ "UninterpretedOption" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.EnumOptions), global::Google.Protobuf.Reflection.EnumOptions.Parser, new[]{ "AllowAlias", "Deprecated", "UninterpretedOption" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.EnumValueOptions), global::Google.Protobuf.Reflection.EnumValueOptions.Parser, new[]{ "Deprecated", "UninterpretedOption" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.ServiceOptions), global::Google.Protobuf.Reflection.ServiceOptions.Parser, new[]{ "Deprecated", "UninterpretedOption" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.MethodOptions), global::Google.Protobuf.Reflection.MethodOptions.Parser, new[]{ "Deprecated", "IdempotencyLevel", "UninterpretedOption" }, null, new[]{ typeof(global::Google.Protobuf.Reflection.MethodOptions.Types.IdempotencyLevel) }, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.UninterpretedOption), global::Google.Protobuf.Reflection.UninterpretedOption.Parser, new[]{ "Name", "IdentifierValue", "PositiveIntValue", "NegativeIntValue", "DoubleValue", "StringValue", "AggregateValue" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.UninterpretedOption.Types.NamePart), global::Google.Protobuf.Reflection.UninterpretedOption.Types.NamePart.Parser, new[]{ "NamePart_", "IsExtension" }, null, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.SourceCodeInfo), global::Google.Protobuf.Reflection.SourceCodeInfo.Parser, new[]{ "Location" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.SourceCodeInfo.Types.Location), global::Google.Protobuf.Reflection.SourceCodeInfo.Types.Location.Parser, new[]{ "Path", "Span", "LeadingComments", "TrailingComments", "LeadingDetachedComments" }, null, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.GeneratedCodeInfo), global::Google.Protobuf.Reflection.GeneratedCodeInfo.Parser, new[]{ "Annotation" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.GeneratedCodeInfo.Types.Annotation), global::Google.Protobuf.Reflection.GeneratedCodeInfo.Types.Annotation.Parser, new[]{ "Path", "SourceFile", "Begin", "End" }, null, null, null, null)}) + })); + } + #endregion + + } + #region Messages + /// + /// The protocol compiler can output a FileDescriptorSet containing the .proto + /// files it parses. + /// + public sealed partial class FileDescriptorSet : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new FileDescriptorSet()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FileDescriptorSet() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FileDescriptorSet(FileDescriptorSet other) : this() { + file_ = other.file_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FileDescriptorSet Clone() { + return new FileDescriptorSet(this); + } + + /// Field number for the "file" field. + public const int FileFieldNumber = 1; + private static readonly pb::FieldCodec _repeated_file_codec + = pb::FieldCodec.ForMessage(10, global::Google.Protobuf.Reflection.FileDescriptorProto.Parser); + private readonly pbc::RepeatedField file_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField File { + get { return file_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as FileDescriptorSet); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(FileDescriptorSet other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!file_.Equals(other.file_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + hash ^= file_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + file_.WriteTo(output, _repeated_file_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + file_.WriteTo(ref output, _repeated_file_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + size += file_.CalculateSize(_repeated_file_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(FileDescriptorSet other) { + if (other == null) { + return; + } + file_.Add(other.file_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + file_.AddEntriesFrom(input, _repeated_file_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + file_.AddEntriesFrom(ref input, _repeated_file_codec); + break; + } + } + } + } + #endif + + } + + /// + /// Describes a complete .proto file. + /// + public sealed partial class FileDescriptorProto : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new FileDescriptorProto()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[1]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FileDescriptorProto() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FileDescriptorProto(FileDescriptorProto other) : this() { + name_ = other.name_; + package_ = other.package_; + dependency_ = other.dependency_.Clone(); + publicDependency_ = other.publicDependency_.Clone(); + weakDependency_ = other.weakDependency_.Clone(); + messageType_ = other.messageType_.Clone(); + enumType_ = other.enumType_.Clone(); + service_ = other.service_.Clone(); + extension_ = other.extension_.Clone(); + options_ = other.options_ != null ? other.options_.Clone() : null; + sourceCodeInfo_ = other.sourceCodeInfo_ != null ? other.sourceCodeInfo_.Clone() : null; + syntax_ = other.syntax_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FileDescriptorProto Clone() { + return new FileDescriptorProto(this); + } + + /// Field number for the "name" field. + public const int NameFieldNumber = 1; + private readonly static string NameDefaultValue = ""; + + private string name_; + /// + /// file name, relative to root of source tree + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string Name { + get { return name_ ?? NameDefaultValue; } + set { + name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "name" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasName { + get { return name_ != null; } + } + /// Clears the value of the "name" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearName() { + name_ = null; + } + + /// Field number for the "package" field. + public const int PackageFieldNumber = 2; + private readonly static string PackageDefaultValue = ""; + + private string package_; + /// + /// e.g. "foo", "foo.bar", etc. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string Package { + get { return package_ ?? PackageDefaultValue; } + set { + package_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "package" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasPackage { + get { return package_ != null; } + } + /// Clears the value of the "package" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearPackage() { + package_ = null; + } + + /// Field number for the "dependency" field. + public const int DependencyFieldNumber = 3; + private static readonly pb::FieldCodec _repeated_dependency_codec + = pb::FieldCodec.ForString(26); + private readonly pbc::RepeatedField dependency_ = new pbc::RepeatedField(); + /// + /// Names of files imported by this file. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Dependency { + get { return dependency_; } + } + + /// Field number for the "public_dependency" field. + public const int PublicDependencyFieldNumber = 10; + private static readonly pb::FieldCodec _repeated_publicDependency_codec + = pb::FieldCodec.ForInt32(80); + private readonly pbc::RepeatedField publicDependency_ = new pbc::RepeatedField(); + /// + /// Indexes of the public imported files in the dependency list above. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField PublicDependency { + get { return publicDependency_; } + } + + /// Field number for the "weak_dependency" field. + public const int WeakDependencyFieldNumber = 11; + private static readonly pb::FieldCodec _repeated_weakDependency_codec + = pb::FieldCodec.ForInt32(88); + private readonly pbc::RepeatedField weakDependency_ = new pbc::RepeatedField(); + /// + /// Indexes of the weak imported files in the dependency list. + /// For Google-internal migration only. Do not use. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField WeakDependency { + get { return weakDependency_; } + } + + /// Field number for the "message_type" field. + public const int MessageTypeFieldNumber = 4; + private static readonly pb::FieldCodec _repeated_messageType_codec + = pb::FieldCodec.ForMessage(34, global::Google.Protobuf.Reflection.DescriptorProto.Parser); + private readonly pbc::RepeatedField messageType_ = new pbc::RepeatedField(); + /// + /// All top-level definitions in this file. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField MessageType { + get { return messageType_; } + } + + /// Field number for the "enum_type" field. + public const int EnumTypeFieldNumber = 5; + private static readonly pb::FieldCodec _repeated_enumType_codec + = pb::FieldCodec.ForMessage(42, global::Google.Protobuf.Reflection.EnumDescriptorProto.Parser); + private readonly pbc::RepeatedField enumType_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField EnumType { + get { return enumType_; } + } + + /// Field number for the "service" field. + public const int ServiceFieldNumber = 6; + private static readonly pb::FieldCodec _repeated_service_codec + = pb::FieldCodec.ForMessage(50, global::Google.Protobuf.Reflection.ServiceDescriptorProto.Parser); + private readonly pbc::RepeatedField service_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Service { + get { return service_; } + } + + /// Field number for the "extension" field. + public const int ExtensionFieldNumber = 7; + private static readonly pb::FieldCodec _repeated_extension_codec + = pb::FieldCodec.ForMessage(58, global::Google.Protobuf.Reflection.FieldDescriptorProto.Parser); + private readonly pbc::RepeatedField extension_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Extension { + get { return extension_; } + } + + /// Field number for the "options" field. + public const int OptionsFieldNumber = 8; + private global::Google.Protobuf.Reflection.FileOptions options_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.Reflection.FileOptions Options { + get { return options_; } + set { + options_ = value; + } + } + + /// Field number for the "source_code_info" field. + public const int SourceCodeInfoFieldNumber = 9; + private global::Google.Protobuf.Reflection.SourceCodeInfo sourceCodeInfo_; + /// + /// This field contains optional information about the original source code. + /// You may safely remove this entire field without harming runtime + /// functionality of the descriptors -- the information is needed only by + /// development tools. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.Reflection.SourceCodeInfo SourceCodeInfo { + get { return sourceCodeInfo_; } + set { + sourceCodeInfo_ = value; + } + } + + /// Field number for the "syntax" field. + public const int SyntaxFieldNumber = 12; + private readonly static string SyntaxDefaultValue = ""; + + private string syntax_; + /// + /// The syntax of the proto file. + /// The supported values are "proto2" and "proto3". + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string Syntax { + get { return syntax_ ?? SyntaxDefaultValue; } + set { + syntax_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "syntax" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasSyntax { + get { return syntax_ != null; } + } + /// Clears the value of the "syntax" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearSyntax() { + syntax_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as FileDescriptorProto); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(FileDescriptorProto other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + if (Package != other.Package) return false; + if(!dependency_.Equals(other.dependency_)) return false; + if(!publicDependency_.Equals(other.publicDependency_)) return false; + if(!weakDependency_.Equals(other.weakDependency_)) return false; + if(!messageType_.Equals(other.messageType_)) return false; + if(!enumType_.Equals(other.enumType_)) return false; + if(!service_.Equals(other.service_)) return false; + if(!extension_.Equals(other.extension_)) return false; + if (!object.Equals(Options, other.Options)) return false; + if (!object.Equals(SourceCodeInfo, other.SourceCodeInfo)) return false; + if (Syntax != other.Syntax) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasName) hash ^= Name.GetHashCode(); + if (HasPackage) hash ^= Package.GetHashCode(); + hash ^= dependency_.GetHashCode(); + hash ^= publicDependency_.GetHashCode(); + hash ^= weakDependency_.GetHashCode(); + hash ^= messageType_.GetHashCode(); + hash ^= enumType_.GetHashCode(); + hash ^= service_.GetHashCode(); + hash ^= extension_.GetHashCode(); + if (options_ != null) hash ^= Options.GetHashCode(); + if (sourceCodeInfo_ != null) hash ^= SourceCodeInfo.GetHashCode(); + if (HasSyntax) hash ^= Syntax.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasName) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (HasPackage) { + output.WriteRawTag(18); + output.WriteString(Package); + } + dependency_.WriteTo(output, _repeated_dependency_codec); + messageType_.WriteTo(output, _repeated_messageType_codec); + enumType_.WriteTo(output, _repeated_enumType_codec); + service_.WriteTo(output, _repeated_service_codec); + extension_.WriteTo(output, _repeated_extension_codec); + if (options_ != null) { + output.WriteRawTag(66); + output.WriteMessage(Options); + } + if (sourceCodeInfo_ != null) { + output.WriteRawTag(74); + output.WriteMessage(SourceCodeInfo); + } + publicDependency_.WriteTo(output, _repeated_publicDependency_codec); + weakDependency_.WriteTo(output, _repeated_weakDependency_codec); + if (HasSyntax) { + output.WriteRawTag(98); + output.WriteString(Syntax); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasName) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (HasPackage) { + output.WriteRawTag(18); + output.WriteString(Package); + } + dependency_.WriteTo(ref output, _repeated_dependency_codec); + messageType_.WriteTo(ref output, _repeated_messageType_codec); + enumType_.WriteTo(ref output, _repeated_enumType_codec); + service_.WriteTo(ref output, _repeated_service_codec); + extension_.WriteTo(ref output, _repeated_extension_codec); + if (options_ != null) { + output.WriteRawTag(66); + output.WriteMessage(Options); + } + if (sourceCodeInfo_ != null) { + output.WriteRawTag(74); + output.WriteMessage(SourceCodeInfo); + } + publicDependency_.WriteTo(ref output, _repeated_publicDependency_codec); + weakDependency_.WriteTo(ref output, _repeated_weakDependency_codec); + if (HasSyntax) { + output.WriteRawTag(98); + output.WriteString(Syntax); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasName) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + if (HasPackage) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Package); + } + size += dependency_.CalculateSize(_repeated_dependency_codec); + size += publicDependency_.CalculateSize(_repeated_publicDependency_codec); + size += weakDependency_.CalculateSize(_repeated_weakDependency_codec); + size += messageType_.CalculateSize(_repeated_messageType_codec); + size += enumType_.CalculateSize(_repeated_enumType_codec); + size += service_.CalculateSize(_repeated_service_codec); + size += extension_.CalculateSize(_repeated_extension_codec); + if (options_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options); + } + if (sourceCodeInfo_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(SourceCodeInfo); + } + if (HasSyntax) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Syntax); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(FileDescriptorProto other) { + if (other == null) { + return; + } + if (other.HasName) { + Name = other.Name; + } + if (other.HasPackage) { + Package = other.Package; + } + dependency_.Add(other.dependency_); + publicDependency_.Add(other.publicDependency_); + weakDependency_.Add(other.weakDependency_); + messageType_.Add(other.messageType_); + enumType_.Add(other.enumType_); + service_.Add(other.service_); + extension_.Add(other.extension_); + if (other.options_ != null) { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.FileOptions(); + } + Options.MergeFrom(other.Options); + } + if (other.sourceCodeInfo_ != null) { + if (sourceCodeInfo_ == null) { + SourceCodeInfo = new global::Google.Protobuf.Reflection.SourceCodeInfo(); + } + SourceCodeInfo.MergeFrom(other.SourceCodeInfo); + } + if (other.HasSyntax) { + Syntax = other.Syntax; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + Package = input.ReadString(); + break; + } + case 26: { + dependency_.AddEntriesFrom(input, _repeated_dependency_codec); + break; + } + case 34: { + messageType_.AddEntriesFrom(input, _repeated_messageType_codec); + break; + } + case 42: { + enumType_.AddEntriesFrom(input, _repeated_enumType_codec); + break; + } + case 50: { + service_.AddEntriesFrom(input, _repeated_service_codec); + break; + } + case 58: { + extension_.AddEntriesFrom(input, _repeated_extension_codec); + break; + } + case 66: { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.FileOptions(); + } + input.ReadMessage(Options); + break; + } + case 74: { + if (sourceCodeInfo_ == null) { + SourceCodeInfo = new global::Google.Protobuf.Reflection.SourceCodeInfo(); + } + input.ReadMessage(SourceCodeInfo); + break; + } + case 82: + case 80: { + publicDependency_.AddEntriesFrom(input, _repeated_publicDependency_codec); + break; + } + case 90: + case 88: { + weakDependency_.AddEntriesFrom(input, _repeated_weakDependency_codec); + break; + } + case 98: { + Syntax = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + Package = input.ReadString(); + break; + } + case 26: { + dependency_.AddEntriesFrom(ref input, _repeated_dependency_codec); + break; + } + case 34: { + messageType_.AddEntriesFrom(ref input, _repeated_messageType_codec); + break; + } + case 42: { + enumType_.AddEntriesFrom(ref input, _repeated_enumType_codec); + break; + } + case 50: { + service_.AddEntriesFrom(ref input, _repeated_service_codec); + break; + } + case 58: { + extension_.AddEntriesFrom(ref input, _repeated_extension_codec); + break; + } + case 66: { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.FileOptions(); + } + input.ReadMessage(Options); + break; + } + case 74: { + if (sourceCodeInfo_ == null) { + SourceCodeInfo = new global::Google.Protobuf.Reflection.SourceCodeInfo(); + } + input.ReadMessage(SourceCodeInfo); + break; + } + case 82: + case 80: { + publicDependency_.AddEntriesFrom(ref input, _repeated_publicDependency_codec); + break; + } + case 90: + case 88: { + weakDependency_.AddEntriesFrom(ref input, _repeated_weakDependency_codec); + break; + } + case 98: { + Syntax = input.ReadString(); + break; + } + } + } + } + #endif + + } + + /// + /// Describes a message type. + /// + public sealed partial class DescriptorProto : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new DescriptorProto()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[2]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public DescriptorProto() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public DescriptorProto(DescriptorProto other) : this() { + name_ = other.name_; + field_ = other.field_.Clone(); + extension_ = other.extension_.Clone(); + nestedType_ = other.nestedType_.Clone(); + enumType_ = other.enumType_.Clone(); + extensionRange_ = other.extensionRange_.Clone(); + oneofDecl_ = other.oneofDecl_.Clone(); + options_ = other.options_ != null ? other.options_.Clone() : null; + reservedRange_ = other.reservedRange_.Clone(); + reservedName_ = other.reservedName_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public DescriptorProto Clone() { + return new DescriptorProto(this); + } + + /// Field number for the "name" field. + public const int NameFieldNumber = 1; + private readonly static string NameDefaultValue = ""; + + private string name_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string Name { + get { return name_ ?? NameDefaultValue; } + set { + name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "name" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasName { + get { return name_ != null; } + } + /// Clears the value of the "name" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearName() { + name_ = null; + } + + /// Field number for the "field" field. + public const int FieldFieldNumber = 2; + private static readonly pb::FieldCodec _repeated_field_codec + = pb::FieldCodec.ForMessage(18, global::Google.Protobuf.Reflection.FieldDescriptorProto.Parser); + private readonly pbc::RepeatedField field_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Field { + get { return field_; } + } + + /// Field number for the "extension" field. + public const int ExtensionFieldNumber = 6; + private static readonly pb::FieldCodec _repeated_extension_codec + = pb::FieldCodec.ForMessage(50, global::Google.Protobuf.Reflection.FieldDescriptorProto.Parser); + private readonly pbc::RepeatedField extension_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Extension { + get { return extension_; } + } + + /// Field number for the "nested_type" field. + public const int NestedTypeFieldNumber = 3; + private static readonly pb::FieldCodec _repeated_nestedType_codec + = pb::FieldCodec.ForMessage(26, global::Google.Protobuf.Reflection.DescriptorProto.Parser); + private readonly pbc::RepeatedField nestedType_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField NestedType { + get { return nestedType_; } + } + + /// Field number for the "enum_type" field. + public const int EnumTypeFieldNumber = 4; + private static readonly pb::FieldCodec _repeated_enumType_codec + = pb::FieldCodec.ForMessage(34, global::Google.Protobuf.Reflection.EnumDescriptorProto.Parser); + private readonly pbc::RepeatedField enumType_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField EnumType { + get { return enumType_; } + } + + /// Field number for the "extension_range" field. + public const int ExtensionRangeFieldNumber = 5; + private static readonly pb::FieldCodec _repeated_extensionRange_codec + = pb::FieldCodec.ForMessage(42, global::Google.Protobuf.Reflection.DescriptorProto.Types.ExtensionRange.Parser); + private readonly pbc::RepeatedField extensionRange_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField ExtensionRange { + get { return extensionRange_; } + } + + /// Field number for the "oneof_decl" field. + public const int OneofDeclFieldNumber = 8; + private static readonly pb::FieldCodec _repeated_oneofDecl_codec + = pb::FieldCodec.ForMessage(66, global::Google.Protobuf.Reflection.OneofDescriptorProto.Parser); + private readonly pbc::RepeatedField oneofDecl_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField OneofDecl { + get { return oneofDecl_; } + } + + /// Field number for the "options" field. + public const int OptionsFieldNumber = 7; + private global::Google.Protobuf.Reflection.MessageOptions options_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.Reflection.MessageOptions Options { + get { return options_; } + set { + options_ = value; + } + } + + /// Field number for the "reserved_range" field. + public const int ReservedRangeFieldNumber = 9; + private static readonly pb::FieldCodec _repeated_reservedRange_codec + = pb::FieldCodec.ForMessage(74, global::Google.Protobuf.Reflection.DescriptorProto.Types.ReservedRange.Parser); + private readonly pbc::RepeatedField reservedRange_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField ReservedRange { + get { return reservedRange_; } + } + + /// Field number for the "reserved_name" field. + public const int ReservedNameFieldNumber = 10; + private static readonly pb::FieldCodec _repeated_reservedName_codec + = pb::FieldCodec.ForString(82); + private readonly pbc::RepeatedField reservedName_ = new pbc::RepeatedField(); + /// + /// Reserved field names, which may not be used by fields in the same message. + /// A given name may only be reserved once. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField ReservedName { + get { return reservedName_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as DescriptorProto); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(DescriptorProto other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + if(!field_.Equals(other.field_)) return false; + if(!extension_.Equals(other.extension_)) return false; + if(!nestedType_.Equals(other.nestedType_)) return false; + if(!enumType_.Equals(other.enumType_)) return false; + if(!extensionRange_.Equals(other.extensionRange_)) return false; + if(!oneofDecl_.Equals(other.oneofDecl_)) return false; + if (!object.Equals(Options, other.Options)) return false; + if(!reservedRange_.Equals(other.reservedRange_)) return false; + if(!reservedName_.Equals(other.reservedName_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasName) hash ^= Name.GetHashCode(); + hash ^= field_.GetHashCode(); + hash ^= extension_.GetHashCode(); + hash ^= nestedType_.GetHashCode(); + hash ^= enumType_.GetHashCode(); + hash ^= extensionRange_.GetHashCode(); + hash ^= oneofDecl_.GetHashCode(); + if (options_ != null) hash ^= Options.GetHashCode(); + hash ^= reservedRange_.GetHashCode(); + hash ^= reservedName_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasName) { + output.WriteRawTag(10); + output.WriteString(Name); + } + field_.WriteTo(output, _repeated_field_codec); + nestedType_.WriteTo(output, _repeated_nestedType_codec); + enumType_.WriteTo(output, _repeated_enumType_codec); + extensionRange_.WriteTo(output, _repeated_extensionRange_codec); + extension_.WriteTo(output, _repeated_extension_codec); + if (options_ != null) { + output.WriteRawTag(58); + output.WriteMessage(Options); + } + oneofDecl_.WriteTo(output, _repeated_oneofDecl_codec); + reservedRange_.WriteTo(output, _repeated_reservedRange_codec); + reservedName_.WriteTo(output, _repeated_reservedName_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasName) { + output.WriteRawTag(10); + output.WriteString(Name); + } + field_.WriteTo(ref output, _repeated_field_codec); + nestedType_.WriteTo(ref output, _repeated_nestedType_codec); + enumType_.WriteTo(ref output, _repeated_enumType_codec); + extensionRange_.WriteTo(ref output, _repeated_extensionRange_codec); + extension_.WriteTo(ref output, _repeated_extension_codec); + if (options_ != null) { + output.WriteRawTag(58); + output.WriteMessage(Options); + } + oneofDecl_.WriteTo(ref output, _repeated_oneofDecl_codec); + reservedRange_.WriteTo(ref output, _repeated_reservedRange_codec); + reservedName_.WriteTo(ref output, _repeated_reservedName_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasName) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + size += field_.CalculateSize(_repeated_field_codec); + size += extension_.CalculateSize(_repeated_extension_codec); + size += nestedType_.CalculateSize(_repeated_nestedType_codec); + size += enumType_.CalculateSize(_repeated_enumType_codec); + size += extensionRange_.CalculateSize(_repeated_extensionRange_codec); + size += oneofDecl_.CalculateSize(_repeated_oneofDecl_codec); + if (options_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options); + } + size += reservedRange_.CalculateSize(_repeated_reservedRange_codec); + size += reservedName_.CalculateSize(_repeated_reservedName_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(DescriptorProto other) { + if (other == null) { + return; + } + if (other.HasName) { + Name = other.Name; + } + field_.Add(other.field_); + extension_.Add(other.extension_); + nestedType_.Add(other.nestedType_); + enumType_.Add(other.enumType_); + extensionRange_.Add(other.extensionRange_); + oneofDecl_.Add(other.oneofDecl_); + if (other.options_ != null) { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.MessageOptions(); + } + Options.MergeFrom(other.Options); + } + reservedRange_.Add(other.reservedRange_); + reservedName_.Add(other.reservedName_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + field_.AddEntriesFrom(input, _repeated_field_codec); + break; + } + case 26: { + nestedType_.AddEntriesFrom(input, _repeated_nestedType_codec); + break; + } + case 34: { + enumType_.AddEntriesFrom(input, _repeated_enumType_codec); + break; + } + case 42: { + extensionRange_.AddEntriesFrom(input, _repeated_extensionRange_codec); + break; + } + case 50: { + extension_.AddEntriesFrom(input, _repeated_extension_codec); + break; + } + case 58: { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.MessageOptions(); + } + input.ReadMessage(Options); + break; + } + case 66: { + oneofDecl_.AddEntriesFrom(input, _repeated_oneofDecl_codec); + break; + } + case 74: { + reservedRange_.AddEntriesFrom(input, _repeated_reservedRange_codec); + break; + } + case 82: { + reservedName_.AddEntriesFrom(input, _repeated_reservedName_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + field_.AddEntriesFrom(ref input, _repeated_field_codec); + break; + } + case 26: { + nestedType_.AddEntriesFrom(ref input, _repeated_nestedType_codec); + break; + } + case 34: { + enumType_.AddEntriesFrom(ref input, _repeated_enumType_codec); + break; + } + case 42: { + extensionRange_.AddEntriesFrom(ref input, _repeated_extensionRange_codec); + break; + } + case 50: { + extension_.AddEntriesFrom(ref input, _repeated_extension_codec); + break; + } + case 58: { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.MessageOptions(); + } + input.ReadMessage(Options); + break; + } + case 66: { + oneofDecl_.AddEntriesFrom(ref input, _repeated_oneofDecl_codec); + break; + } + case 74: { + reservedRange_.AddEntriesFrom(ref input, _repeated_reservedRange_codec); + break; + } + case 82: { + reservedName_.AddEntriesFrom(ref input, _repeated_reservedName_codec); + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the DescriptorProto message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public sealed partial class ExtensionRange : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ExtensionRange()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorProto.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ExtensionRange() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ExtensionRange(ExtensionRange other) : this() { + _hasBits0 = other._hasBits0; + start_ = other.start_; + end_ = other.end_; + options_ = other.options_ != null ? other.options_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ExtensionRange Clone() { + return new ExtensionRange(this); + } + + /// Field number for the "start" field. + public const int StartFieldNumber = 1; + private readonly static int StartDefaultValue = 0; + + private int start_; + /// + /// Inclusive. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Start { + get { if ((_hasBits0 & 1) != 0) { return start_; } else { return StartDefaultValue; } } + set { + _hasBits0 |= 1; + start_ = value; + } + } + /// Gets whether the "start" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasStart { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "start" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearStart() { + _hasBits0 &= ~1; + } + + /// Field number for the "end" field. + public const int EndFieldNumber = 2; + private readonly static int EndDefaultValue = 0; + + private int end_; + /// + /// Exclusive. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int End { + get { if ((_hasBits0 & 2) != 0) { return end_; } else { return EndDefaultValue; } } + set { + _hasBits0 |= 2; + end_ = value; + } + } + /// Gets whether the "end" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasEnd { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "end" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearEnd() { + _hasBits0 &= ~2; + } + + /// Field number for the "options" field. + public const int OptionsFieldNumber = 3; + private global::Google.Protobuf.Reflection.ExtensionRangeOptions options_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.Reflection.ExtensionRangeOptions Options { + get { return options_; } + set { + options_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as ExtensionRange); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(ExtensionRange other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Start != other.Start) return false; + if (End != other.End) return false; + if (!object.Equals(Options, other.Options)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasStart) hash ^= Start.GetHashCode(); + if (HasEnd) hash ^= End.GetHashCode(); + if (options_ != null) hash ^= Options.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasStart) { + output.WriteRawTag(8); + output.WriteInt32(Start); + } + if (HasEnd) { + output.WriteRawTag(16); + output.WriteInt32(End); + } + if (options_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Options); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasStart) { + output.WriteRawTag(8); + output.WriteInt32(Start); + } + if (HasEnd) { + output.WriteRawTag(16); + output.WriteInt32(End); + } + if (options_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Options); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasStart) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Start); + } + if (HasEnd) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(End); + } + if (options_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(ExtensionRange other) { + if (other == null) { + return; + } + if (other.HasStart) { + Start = other.Start; + } + if (other.HasEnd) { + End = other.End; + } + if (other.options_ != null) { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.ExtensionRangeOptions(); + } + Options.MergeFrom(other.Options); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Start = input.ReadInt32(); + break; + } + case 16: { + End = input.ReadInt32(); + break; + } + case 26: { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.ExtensionRangeOptions(); + } + input.ReadMessage(Options); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Start = input.ReadInt32(); + break; + } + case 16: { + End = input.ReadInt32(); + break; + } + case 26: { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.ExtensionRangeOptions(); + } + input.ReadMessage(Options); + break; + } + } + } + } + #endif + + } + + /// + /// Range of reserved tag numbers. Reserved tag numbers may not be used by + /// fields or extension ranges in the same message. Reserved ranges may + /// not overlap. + /// + public sealed partial class ReservedRange : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ReservedRange()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorProto.Descriptor.NestedTypes[1]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ReservedRange() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ReservedRange(ReservedRange other) : this() { + _hasBits0 = other._hasBits0; + start_ = other.start_; + end_ = other.end_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ReservedRange Clone() { + return new ReservedRange(this); + } + + /// Field number for the "start" field. + public const int StartFieldNumber = 1; + private readonly static int StartDefaultValue = 0; + + private int start_; + /// + /// Inclusive. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Start { + get { if ((_hasBits0 & 1) != 0) { return start_; } else { return StartDefaultValue; } } + set { + _hasBits0 |= 1; + start_ = value; + } + } + /// Gets whether the "start" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasStart { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "start" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearStart() { + _hasBits0 &= ~1; + } + + /// Field number for the "end" field. + public const int EndFieldNumber = 2; + private readonly static int EndDefaultValue = 0; + + private int end_; + /// + /// Exclusive. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int End { + get { if ((_hasBits0 & 2) != 0) { return end_; } else { return EndDefaultValue; } } + set { + _hasBits0 |= 2; + end_ = value; + } + } + /// Gets whether the "end" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasEnd { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "end" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearEnd() { + _hasBits0 &= ~2; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as ReservedRange); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(ReservedRange other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Start != other.Start) return false; + if (End != other.End) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasStart) hash ^= Start.GetHashCode(); + if (HasEnd) hash ^= End.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasStart) { + output.WriteRawTag(8); + output.WriteInt32(Start); + } + if (HasEnd) { + output.WriteRawTag(16); + output.WriteInt32(End); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasStart) { + output.WriteRawTag(8); + output.WriteInt32(Start); + } + if (HasEnd) { + output.WriteRawTag(16); + output.WriteInt32(End); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasStart) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Start); + } + if (HasEnd) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(End); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(ReservedRange other) { + if (other == null) { + return; + } + if (other.HasStart) { + Start = other.Start; + } + if (other.HasEnd) { + End = other.End; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Start = input.ReadInt32(); + break; + } + case 16: { + End = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Start = input.ReadInt32(); + break; + } + case 16: { + End = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + } + #endregion + + } + + public sealed partial class ExtensionRangeOptions : pb::IExtendableMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ExtensionRangeOptions()); + private pb::UnknownFieldSet _unknownFields; + internal pb::ExtensionSet _extensions; + private pb::ExtensionSet _Extensions { get { return _extensions; } } + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[3]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ExtensionRangeOptions() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ExtensionRangeOptions(ExtensionRangeOptions other) : this() { + uninterpretedOption_ = other.uninterpretedOption_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + _extensions = pb::ExtensionSet.Clone(other._extensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ExtensionRangeOptions Clone() { + return new ExtensionRangeOptions(this); + } + + /// Field number for the "uninterpreted_option" field. + public const int UninterpretedOptionFieldNumber = 999; + private static readonly pb::FieldCodec _repeated_uninterpretedOption_codec + = pb::FieldCodec.ForMessage(7994, global::Google.Protobuf.Reflection.UninterpretedOption.Parser); + private readonly pbc::RepeatedField uninterpretedOption_ = new pbc::RepeatedField(); + /// + /// The parser stores options it doesn't recognize here. See above. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField UninterpretedOption { + get { return uninterpretedOption_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as ExtensionRangeOptions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(ExtensionRangeOptions other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!uninterpretedOption_.Equals(other.uninterpretedOption_)) return false; + if (!Equals(_extensions, other._extensions)) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + hash ^= uninterpretedOption_.GetHashCode(); + if (_extensions != null) { + hash ^= _extensions.GetHashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + uninterpretedOption_.WriteTo(output, _repeated_uninterpretedOption_codec); + if (_extensions != null) { + _extensions.WriteTo(output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + uninterpretedOption_.WriteTo(ref output, _repeated_uninterpretedOption_codec); + if (_extensions != null) { + _extensions.WriteTo(ref output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + size += uninterpretedOption_.CalculateSize(_repeated_uninterpretedOption_codec); + if (_extensions != null) { + size += _extensions.CalculateSize(); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(ExtensionRangeOptions other) { + if (other == null) { + return; + } + uninterpretedOption_.Add(other.uninterpretedOption_); + pb::ExtensionSet.MergeFrom(ref _extensions, other._extensions); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + } + break; + case 7994: { + uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + } + break; + case 7994: { + uninterpretedOption_.AddEntriesFrom(ref input, _repeated_uninterpretedOption_codec); + break; + } + } + } + } + #endif + + public TValue GetExtension(pb::Extension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetOrInitializeExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.GetOrInitialize(ref _extensions, extension); + } + public void SetExtension(pb::Extension extension, TValue value) { + pb::ExtensionSet.Set(ref _extensions, extension, value); + } + public bool HasExtension(pb::Extension extension) { + return pb::ExtensionSet.Has(ref _extensions, extension); + } + public void ClearExtension(pb::Extension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + public void ClearExtension(pb::RepeatedExtension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + + } + + /// + /// Describes a field within a message. + /// + public sealed partial class FieldDescriptorProto : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new FieldDescriptorProto()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[4]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FieldDescriptorProto() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FieldDescriptorProto(FieldDescriptorProto other) : this() { + _hasBits0 = other._hasBits0; + name_ = other.name_; + number_ = other.number_; + label_ = other.label_; + type_ = other.type_; + typeName_ = other.typeName_; + extendee_ = other.extendee_; + defaultValue_ = other.defaultValue_; + oneofIndex_ = other.oneofIndex_; + jsonName_ = other.jsonName_; + options_ = other.options_ != null ? other.options_.Clone() : null; + proto3Optional_ = other.proto3Optional_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FieldDescriptorProto Clone() { + return new FieldDescriptorProto(this); + } + + /// Field number for the "name" field. + public const int NameFieldNumber = 1; + private readonly static string NameDefaultValue = ""; + + private string name_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string Name { + get { return name_ ?? NameDefaultValue; } + set { + name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "name" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasName { + get { return name_ != null; } + } + /// Clears the value of the "name" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearName() { + name_ = null; + } + + /// Field number for the "number" field. + public const int NumberFieldNumber = 3; + private readonly static int NumberDefaultValue = 0; + + private int number_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Number { + get { if ((_hasBits0 & 1) != 0) { return number_; } else { return NumberDefaultValue; } } + set { + _hasBits0 |= 1; + number_ = value; + } + } + /// Gets whether the "number" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasNumber { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "number" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearNumber() { + _hasBits0 &= ~1; + } + + /// Field number for the "label" field. + public const int LabelFieldNumber = 4; + private readonly static global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Label LabelDefaultValue = global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Label.Optional; + + private global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Label label_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Label Label { + get { if ((_hasBits0 & 2) != 0) { return label_; } else { return LabelDefaultValue; } } + set { + _hasBits0 |= 2; + label_ = value; + } + } + /// Gets whether the "label" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasLabel { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "label" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearLabel() { + _hasBits0 &= ~2; + } + + /// Field number for the "type" field. + public const int TypeFieldNumber = 5; + private readonly static global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Type TypeDefaultValue = global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Type.Double; + + private global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Type type_; + /// + /// If type_name is set, this need not be set. If both this and type_name + /// are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Type Type { + get { if ((_hasBits0 & 4) != 0) { return type_; } else { return TypeDefaultValue; } } + set { + _hasBits0 |= 4; + type_ = value; + } + } + /// Gets whether the "type" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasType { + get { return (_hasBits0 & 4) != 0; } + } + /// Clears the value of the "type" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearType() { + _hasBits0 &= ~4; + } + + /// Field number for the "type_name" field. + public const int TypeNameFieldNumber = 6; + private readonly static string TypeNameDefaultValue = ""; + + private string typeName_; + /// + /// For message and enum types, this is the name of the type. If the name + /// starts with a '.', it is fully-qualified. Otherwise, C++-like scoping + /// rules are used to find the type (i.e. first the nested types within this + /// message are searched, then within the parent, on up to the root + /// namespace). + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string TypeName { + get { return typeName_ ?? TypeNameDefaultValue; } + set { + typeName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "type_name" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasTypeName { + get { return typeName_ != null; } + } + /// Clears the value of the "type_name" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearTypeName() { + typeName_ = null; + } + + /// Field number for the "extendee" field. + public const int ExtendeeFieldNumber = 2; + private readonly static string ExtendeeDefaultValue = ""; + + private string extendee_; + /// + /// For extensions, this is the name of the type being extended. It is + /// resolved in the same manner as type_name. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string Extendee { + get { return extendee_ ?? ExtendeeDefaultValue; } + set { + extendee_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "extendee" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasExtendee { + get { return extendee_ != null; } + } + /// Clears the value of the "extendee" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearExtendee() { + extendee_ = null; + } + + /// Field number for the "default_value" field. + public const int DefaultValueFieldNumber = 7; + private readonly static string DefaultValueDefaultValue = ""; + + private string defaultValue_; + /// + /// For numeric types, contains the original text representation of the value. + /// For booleans, "true" or "false". + /// For strings, contains the default text contents (not escaped in any way). + /// For bytes, contains the C escaped value. All bytes >= 128 are escaped. + /// TODO(kenton): Base-64 encode? + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string DefaultValue { + get { return defaultValue_ ?? DefaultValueDefaultValue; } + set { + defaultValue_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "default_value" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDefaultValue { + get { return defaultValue_ != null; } + } + /// Clears the value of the "default_value" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDefaultValue() { + defaultValue_ = null; + } + + /// Field number for the "oneof_index" field. + public const int OneofIndexFieldNumber = 9; + private readonly static int OneofIndexDefaultValue = 0; + + private int oneofIndex_; + /// + /// If set, gives the index of a oneof in the containing type's oneof_decl + /// list. This field is a member of that oneof. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int OneofIndex { + get { if ((_hasBits0 & 8) != 0) { return oneofIndex_; } else { return OneofIndexDefaultValue; } } + set { + _hasBits0 |= 8; + oneofIndex_ = value; + } + } + /// Gets whether the "oneof_index" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOneofIndex { + get { return (_hasBits0 & 8) != 0; } + } + /// Clears the value of the "oneof_index" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOneofIndex() { + _hasBits0 &= ~8; + } + + /// Field number for the "json_name" field. + public const int JsonNameFieldNumber = 10; + private readonly static string JsonNameDefaultValue = ""; + + private string jsonName_; + /// + /// JSON name of this field. The value is set by protocol compiler. If the + /// user has set a "json_name" option on this field, that option's value + /// will be used. Otherwise, it's deduced from the field's name by converting + /// it to camelCase. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string JsonName { + get { return jsonName_ ?? JsonNameDefaultValue; } + set { + jsonName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "json_name" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasJsonName { + get { return jsonName_ != null; } + } + /// Clears the value of the "json_name" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearJsonName() { + jsonName_ = null; + } + + /// Field number for the "options" field. + public const int OptionsFieldNumber = 8; + private global::Google.Protobuf.Reflection.FieldOptions options_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.Reflection.FieldOptions Options { + get { return options_; } + set { + options_ = value; + } + } + + /// Field number for the "proto3_optional" field. + public const int Proto3OptionalFieldNumber = 17; + private readonly static bool Proto3OptionalDefaultValue = false; + + private bool proto3Optional_; + /// + /// If true, this is a proto3 "optional". When a proto3 field is optional, it + /// tracks presence regardless of field type. + /// + /// When proto3_optional is true, this field must be belong to a oneof to + /// signal to old proto3 clients that presence is tracked for this field. This + /// oneof is known as a "synthetic" oneof, and this field must be its sole + /// member (each proto3 optional field gets its own synthetic oneof). Synthetic + /// oneofs exist in the descriptor only, and do not generate any API. Synthetic + /// oneofs must be ordered after all "real" oneofs. + /// + /// For message fields, proto3_optional doesn't create any semantic change, + /// since non-repeated message fields always track presence. However it still + /// indicates the semantic detail of whether the user wrote "optional" or not. + /// This can be useful for round-tripping the .proto file. For consistency we + /// give message fields a synthetic oneof also, even though it is not required + /// to track presence. This is especially important because the parser can't + /// tell if a field is a message or an enum, so it must always create a + /// synthetic oneof. + /// + /// Proto2 optional fields do not set this flag, because they already indicate + /// optional with `LABEL_OPTIONAL`. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Proto3Optional { + get { if ((_hasBits0 & 16) != 0) { return proto3Optional_; } else { return Proto3OptionalDefaultValue; } } + set { + _hasBits0 |= 16; + proto3Optional_ = value; + } + } + /// Gets whether the "proto3_optional" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasProto3Optional { + get { return (_hasBits0 & 16) != 0; } + } + /// Clears the value of the "proto3_optional" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearProto3Optional() { + _hasBits0 &= ~16; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as FieldDescriptorProto); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(FieldDescriptorProto other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + if (Number != other.Number) return false; + if (Label != other.Label) return false; + if (Type != other.Type) return false; + if (TypeName != other.TypeName) return false; + if (Extendee != other.Extendee) return false; + if (DefaultValue != other.DefaultValue) return false; + if (OneofIndex != other.OneofIndex) return false; + if (JsonName != other.JsonName) return false; + if (!object.Equals(Options, other.Options)) return false; + if (Proto3Optional != other.Proto3Optional) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasName) hash ^= Name.GetHashCode(); + if (HasNumber) hash ^= Number.GetHashCode(); + if (HasLabel) hash ^= Label.GetHashCode(); + if (HasType) hash ^= Type.GetHashCode(); + if (HasTypeName) hash ^= TypeName.GetHashCode(); + if (HasExtendee) hash ^= Extendee.GetHashCode(); + if (HasDefaultValue) hash ^= DefaultValue.GetHashCode(); + if (HasOneofIndex) hash ^= OneofIndex.GetHashCode(); + if (HasJsonName) hash ^= JsonName.GetHashCode(); + if (options_ != null) hash ^= Options.GetHashCode(); + if (HasProto3Optional) hash ^= Proto3Optional.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasName) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (HasExtendee) { + output.WriteRawTag(18); + output.WriteString(Extendee); + } + if (HasNumber) { + output.WriteRawTag(24); + output.WriteInt32(Number); + } + if (HasLabel) { + output.WriteRawTag(32); + output.WriteEnum((int) Label); + } + if (HasType) { + output.WriteRawTag(40); + output.WriteEnum((int) Type); + } + if (HasTypeName) { + output.WriteRawTag(50); + output.WriteString(TypeName); + } + if (HasDefaultValue) { + output.WriteRawTag(58); + output.WriteString(DefaultValue); + } + if (options_ != null) { + output.WriteRawTag(66); + output.WriteMessage(Options); + } + if (HasOneofIndex) { + output.WriteRawTag(72); + output.WriteInt32(OneofIndex); + } + if (HasJsonName) { + output.WriteRawTag(82); + output.WriteString(JsonName); + } + if (HasProto3Optional) { + output.WriteRawTag(136, 1); + output.WriteBool(Proto3Optional); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasName) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (HasExtendee) { + output.WriteRawTag(18); + output.WriteString(Extendee); + } + if (HasNumber) { + output.WriteRawTag(24); + output.WriteInt32(Number); + } + if (HasLabel) { + output.WriteRawTag(32); + output.WriteEnum((int) Label); + } + if (HasType) { + output.WriteRawTag(40); + output.WriteEnum((int) Type); + } + if (HasTypeName) { + output.WriteRawTag(50); + output.WriteString(TypeName); + } + if (HasDefaultValue) { + output.WriteRawTag(58); + output.WriteString(DefaultValue); + } + if (options_ != null) { + output.WriteRawTag(66); + output.WriteMessage(Options); + } + if (HasOneofIndex) { + output.WriteRawTag(72); + output.WriteInt32(OneofIndex); + } + if (HasJsonName) { + output.WriteRawTag(82); + output.WriteString(JsonName); + } + if (HasProto3Optional) { + output.WriteRawTag(136, 1); + output.WriteBool(Proto3Optional); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasName) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + if (HasNumber) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Number); + } + if (HasLabel) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Label); + } + if (HasType) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type); + } + if (HasTypeName) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(TypeName); + } + if (HasExtendee) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Extendee); + } + if (HasDefaultValue) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(DefaultValue); + } + if (HasOneofIndex) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(OneofIndex); + } + if (HasJsonName) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(JsonName); + } + if (options_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options); + } + if (HasProto3Optional) { + size += 2 + 1; + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(FieldDescriptorProto other) { + if (other == null) { + return; + } + if (other.HasName) { + Name = other.Name; + } + if (other.HasNumber) { + Number = other.Number; + } + if (other.HasLabel) { + Label = other.Label; + } + if (other.HasType) { + Type = other.Type; + } + if (other.HasTypeName) { + TypeName = other.TypeName; + } + if (other.HasExtendee) { + Extendee = other.Extendee; + } + if (other.HasDefaultValue) { + DefaultValue = other.DefaultValue; + } + if (other.HasOneofIndex) { + OneofIndex = other.OneofIndex; + } + if (other.HasJsonName) { + JsonName = other.JsonName; + } + if (other.options_ != null) { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.FieldOptions(); + } + Options.MergeFrom(other.Options); + } + if (other.HasProto3Optional) { + Proto3Optional = other.Proto3Optional; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + Extendee = input.ReadString(); + break; + } + case 24: { + Number = input.ReadInt32(); + break; + } + case 32: { + Label = (global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Label) input.ReadEnum(); + break; + } + case 40: { + Type = (global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Type) input.ReadEnum(); + break; + } + case 50: { + TypeName = input.ReadString(); + break; + } + case 58: { + DefaultValue = input.ReadString(); + break; + } + case 66: { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.FieldOptions(); + } + input.ReadMessage(Options); + break; + } + case 72: { + OneofIndex = input.ReadInt32(); + break; + } + case 82: { + JsonName = input.ReadString(); + break; + } + case 136: { + Proto3Optional = input.ReadBool(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + Extendee = input.ReadString(); + break; + } + case 24: { + Number = input.ReadInt32(); + break; + } + case 32: { + Label = (global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Label) input.ReadEnum(); + break; + } + case 40: { + Type = (global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Type) input.ReadEnum(); + break; + } + case 50: { + TypeName = input.ReadString(); + break; + } + case 58: { + DefaultValue = input.ReadString(); + break; + } + case 66: { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.FieldOptions(); + } + input.ReadMessage(Options); + break; + } + case 72: { + OneofIndex = input.ReadInt32(); + break; + } + case 82: { + JsonName = input.ReadString(); + break; + } + case 136: { + Proto3Optional = input.ReadBool(); + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the FieldDescriptorProto message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public enum Type { + /// + /// 0 is reserved for errors. + /// Order is weird for historical reasons. + /// + [pbr::OriginalName("TYPE_DOUBLE")] Double = 1, + [pbr::OriginalName("TYPE_FLOAT")] Float = 2, + /// + /// Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if + /// negative values are likely. + /// + [pbr::OriginalName("TYPE_INT64")] Int64 = 3, + [pbr::OriginalName("TYPE_UINT64")] Uint64 = 4, + /// + /// Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if + /// negative values are likely. + /// + [pbr::OriginalName("TYPE_INT32")] Int32 = 5, + [pbr::OriginalName("TYPE_FIXED64")] Fixed64 = 6, + [pbr::OriginalName("TYPE_FIXED32")] Fixed32 = 7, + [pbr::OriginalName("TYPE_BOOL")] Bool = 8, + [pbr::OriginalName("TYPE_STRING")] String = 9, + /// + /// Tag-delimited aggregate. + /// Group type is deprecated and not supported in proto3. However, Proto3 + /// implementations should still be able to parse the group wire format and + /// treat group fields as unknown fields. + /// + [pbr::OriginalName("TYPE_GROUP")] Group = 10, + /// + /// Length-delimited aggregate. + /// + [pbr::OriginalName("TYPE_MESSAGE")] Message = 11, + /// + /// New in version 2. + /// + [pbr::OriginalName("TYPE_BYTES")] Bytes = 12, + [pbr::OriginalName("TYPE_UINT32")] Uint32 = 13, + [pbr::OriginalName("TYPE_ENUM")] Enum = 14, + [pbr::OriginalName("TYPE_SFIXED32")] Sfixed32 = 15, + [pbr::OriginalName("TYPE_SFIXED64")] Sfixed64 = 16, + /// + /// Uses ZigZag encoding. + /// + [pbr::OriginalName("TYPE_SINT32")] Sint32 = 17, + /// + /// Uses ZigZag encoding. + /// + [pbr::OriginalName("TYPE_SINT64")] Sint64 = 18, + } + + public enum Label { + /// + /// 0 is reserved for errors + /// + [pbr::OriginalName("LABEL_OPTIONAL")] Optional = 1, + [pbr::OriginalName("LABEL_REQUIRED")] Required = 2, + [pbr::OriginalName("LABEL_REPEATED")] Repeated = 3, + } + + } + #endregion + + } + + /// + /// Describes a oneof. + /// + public sealed partial class OneofDescriptorProto : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new OneofDescriptorProto()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[5]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneofDescriptorProto() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneofDescriptorProto(OneofDescriptorProto other) : this() { + name_ = other.name_; + options_ = other.options_ != null ? other.options_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneofDescriptorProto Clone() { + return new OneofDescriptorProto(this); + } + + /// Field number for the "name" field. + public const int NameFieldNumber = 1; + private readonly static string NameDefaultValue = ""; + + private string name_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string Name { + get { return name_ ?? NameDefaultValue; } + set { + name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "name" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasName { + get { return name_ != null; } + } + /// Clears the value of the "name" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearName() { + name_ = null; + } + + /// Field number for the "options" field. + public const int OptionsFieldNumber = 2; + private global::Google.Protobuf.Reflection.OneofOptions options_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.Reflection.OneofOptions Options { + get { return options_; } + set { + options_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as OneofDescriptorProto); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(OneofDescriptorProto other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + if (!object.Equals(Options, other.Options)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasName) hash ^= Name.GetHashCode(); + if (options_ != null) hash ^= Options.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasName) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (options_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Options); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasName) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (options_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Options); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasName) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + if (options_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(OneofDescriptorProto other) { + if (other == null) { + return; + } + if (other.HasName) { + Name = other.Name; + } + if (other.options_ != null) { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.OneofOptions(); + } + Options.MergeFrom(other.Options); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.OneofOptions(); + } + input.ReadMessage(Options); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.OneofOptions(); + } + input.ReadMessage(Options); + break; + } + } + } + } + #endif + + } + + /// + /// Describes an enum type. + /// + public sealed partial class EnumDescriptorProto : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new EnumDescriptorProto()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[6]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public EnumDescriptorProto() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public EnumDescriptorProto(EnumDescriptorProto other) : this() { + name_ = other.name_; + value_ = other.value_.Clone(); + options_ = other.options_ != null ? other.options_.Clone() : null; + reservedRange_ = other.reservedRange_.Clone(); + reservedName_ = other.reservedName_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public EnumDescriptorProto Clone() { + return new EnumDescriptorProto(this); + } + + /// Field number for the "name" field. + public const int NameFieldNumber = 1; + private readonly static string NameDefaultValue = ""; + + private string name_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string Name { + get { return name_ ?? NameDefaultValue; } + set { + name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "name" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasName { + get { return name_ != null; } + } + /// Clears the value of the "name" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearName() { + name_ = null; + } + + /// Field number for the "value" field. + public const int ValueFieldNumber = 2; + private static readonly pb::FieldCodec _repeated_value_codec + = pb::FieldCodec.ForMessage(18, global::Google.Protobuf.Reflection.EnumValueDescriptorProto.Parser); + private readonly pbc::RepeatedField value_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Value { + get { return value_; } + } + + /// Field number for the "options" field. + public const int OptionsFieldNumber = 3; + private global::Google.Protobuf.Reflection.EnumOptions options_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.Reflection.EnumOptions Options { + get { return options_; } + set { + options_ = value; + } + } + + /// Field number for the "reserved_range" field. + public const int ReservedRangeFieldNumber = 4; + private static readonly pb::FieldCodec _repeated_reservedRange_codec + = pb::FieldCodec.ForMessage(34, global::Google.Protobuf.Reflection.EnumDescriptorProto.Types.EnumReservedRange.Parser); + private readonly pbc::RepeatedField reservedRange_ = new pbc::RepeatedField(); + /// + /// Range of reserved numeric values. Reserved numeric values may not be used + /// by enum values in the same enum declaration. Reserved ranges may not + /// overlap. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField ReservedRange { + get { return reservedRange_; } + } + + /// Field number for the "reserved_name" field. + public const int ReservedNameFieldNumber = 5; + private static readonly pb::FieldCodec _repeated_reservedName_codec + = pb::FieldCodec.ForString(42); + private readonly pbc::RepeatedField reservedName_ = new pbc::RepeatedField(); + /// + /// Reserved enum value names, which may not be reused. A given name may only + /// be reserved once. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField ReservedName { + get { return reservedName_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as EnumDescriptorProto); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(EnumDescriptorProto other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + if(!value_.Equals(other.value_)) return false; + if (!object.Equals(Options, other.Options)) return false; + if(!reservedRange_.Equals(other.reservedRange_)) return false; + if(!reservedName_.Equals(other.reservedName_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasName) hash ^= Name.GetHashCode(); + hash ^= value_.GetHashCode(); + if (options_ != null) hash ^= Options.GetHashCode(); + hash ^= reservedRange_.GetHashCode(); + hash ^= reservedName_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasName) { + output.WriteRawTag(10); + output.WriteString(Name); + } + value_.WriteTo(output, _repeated_value_codec); + if (options_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Options); + } + reservedRange_.WriteTo(output, _repeated_reservedRange_codec); + reservedName_.WriteTo(output, _repeated_reservedName_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasName) { + output.WriteRawTag(10); + output.WriteString(Name); + } + value_.WriteTo(ref output, _repeated_value_codec); + if (options_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Options); + } + reservedRange_.WriteTo(ref output, _repeated_reservedRange_codec); + reservedName_.WriteTo(ref output, _repeated_reservedName_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasName) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + size += value_.CalculateSize(_repeated_value_codec); + if (options_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options); + } + size += reservedRange_.CalculateSize(_repeated_reservedRange_codec); + size += reservedName_.CalculateSize(_repeated_reservedName_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(EnumDescriptorProto other) { + if (other == null) { + return; + } + if (other.HasName) { + Name = other.Name; + } + value_.Add(other.value_); + if (other.options_ != null) { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.EnumOptions(); + } + Options.MergeFrom(other.Options); + } + reservedRange_.Add(other.reservedRange_); + reservedName_.Add(other.reservedName_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + value_.AddEntriesFrom(input, _repeated_value_codec); + break; + } + case 26: { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.EnumOptions(); + } + input.ReadMessage(Options); + break; + } + case 34: { + reservedRange_.AddEntriesFrom(input, _repeated_reservedRange_codec); + break; + } + case 42: { + reservedName_.AddEntriesFrom(input, _repeated_reservedName_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + value_.AddEntriesFrom(ref input, _repeated_value_codec); + break; + } + case 26: { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.EnumOptions(); + } + input.ReadMessage(Options); + break; + } + case 34: { + reservedRange_.AddEntriesFrom(ref input, _repeated_reservedRange_codec); + break; + } + case 42: { + reservedName_.AddEntriesFrom(ref input, _repeated_reservedName_codec); + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the EnumDescriptorProto message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + /// + /// Range of reserved numeric values. Reserved values may not be used by + /// entries in the same enum. Reserved ranges may not overlap. + /// + /// Note that this is distinct from DescriptorProto.ReservedRange in that it + /// is inclusive such that it can appropriately represent the entire int32 + /// domain. + /// + public sealed partial class EnumReservedRange : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new EnumReservedRange()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.EnumDescriptorProto.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public EnumReservedRange() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public EnumReservedRange(EnumReservedRange other) : this() { + _hasBits0 = other._hasBits0; + start_ = other.start_; + end_ = other.end_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public EnumReservedRange Clone() { + return new EnumReservedRange(this); + } + + /// Field number for the "start" field. + public const int StartFieldNumber = 1; + private readonly static int StartDefaultValue = 0; + + private int start_; + /// + /// Inclusive. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Start { + get { if ((_hasBits0 & 1) != 0) { return start_; } else { return StartDefaultValue; } } + set { + _hasBits0 |= 1; + start_ = value; + } + } + /// Gets whether the "start" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasStart { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "start" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearStart() { + _hasBits0 &= ~1; + } + + /// Field number for the "end" field. + public const int EndFieldNumber = 2; + private readonly static int EndDefaultValue = 0; + + private int end_; + /// + /// Inclusive. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int End { + get { if ((_hasBits0 & 2) != 0) { return end_; } else { return EndDefaultValue; } } + set { + _hasBits0 |= 2; + end_ = value; + } + } + /// Gets whether the "end" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasEnd { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "end" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearEnd() { + _hasBits0 &= ~2; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as EnumReservedRange); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(EnumReservedRange other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Start != other.Start) return false; + if (End != other.End) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasStart) hash ^= Start.GetHashCode(); + if (HasEnd) hash ^= End.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasStart) { + output.WriteRawTag(8); + output.WriteInt32(Start); + } + if (HasEnd) { + output.WriteRawTag(16); + output.WriteInt32(End); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasStart) { + output.WriteRawTag(8); + output.WriteInt32(Start); + } + if (HasEnd) { + output.WriteRawTag(16); + output.WriteInt32(End); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasStart) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Start); + } + if (HasEnd) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(End); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(EnumReservedRange other) { + if (other == null) { + return; + } + if (other.HasStart) { + Start = other.Start; + } + if (other.HasEnd) { + End = other.End; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Start = input.ReadInt32(); + break; + } + case 16: { + End = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Start = input.ReadInt32(); + break; + } + case 16: { + End = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + } + #endregion + + } + + /// + /// Describes a value within an enum. + /// + public sealed partial class EnumValueDescriptorProto : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new EnumValueDescriptorProto()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[7]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public EnumValueDescriptorProto() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public EnumValueDescriptorProto(EnumValueDescriptorProto other) : this() { + _hasBits0 = other._hasBits0; + name_ = other.name_; + number_ = other.number_; + options_ = other.options_ != null ? other.options_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public EnumValueDescriptorProto Clone() { + return new EnumValueDescriptorProto(this); + } + + /// Field number for the "name" field. + public const int NameFieldNumber = 1; + private readonly static string NameDefaultValue = ""; + + private string name_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string Name { + get { return name_ ?? NameDefaultValue; } + set { + name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "name" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasName { + get { return name_ != null; } + } + /// Clears the value of the "name" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearName() { + name_ = null; + } + + /// Field number for the "number" field. + public const int NumberFieldNumber = 2; + private readonly static int NumberDefaultValue = 0; + + private int number_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Number { + get { if ((_hasBits0 & 1) != 0) { return number_; } else { return NumberDefaultValue; } } + set { + _hasBits0 |= 1; + number_ = value; + } + } + /// Gets whether the "number" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasNumber { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "number" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearNumber() { + _hasBits0 &= ~1; + } + + /// Field number for the "options" field. + public const int OptionsFieldNumber = 3; + private global::Google.Protobuf.Reflection.EnumValueOptions options_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.Reflection.EnumValueOptions Options { + get { return options_; } + set { + options_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as EnumValueDescriptorProto); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(EnumValueDescriptorProto other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + if (Number != other.Number) return false; + if (!object.Equals(Options, other.Options)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasName) hash ^= Name.GetHashCode(); + if (HasNumber) hash ^= Number.GetHashCode(); + if (options_ != null) hash ^= Options.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasName) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (HasNumber) { + output.WriteRawTag(16); + output.WriteInt32(Number); + } + if (options_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Options); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasName) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (HasNumber) { + output.WriteRawTag(16); + output.WriteInt32(Number); + } + if (options_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Options); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasName) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + if (HasNumber) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Number); + } + if (options_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(EnumValueDescriptorProto other) { + if (other == null) { + return; + } + if (other.HasName) { + Name = other.Name; + } + if (other.HasNumber) { + Number = other.Number; + } + if (other.options_ != null) { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.EnumValueOptions(); + } + Options.MergeFrom(other.Options); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 16: { + Number = input.ReadInt32(); + break; + } + case 26: { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.EnumValueOptions(); + } + input.ReadMessage(Options); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 16: { + Number = input.ReadInt32(); + break; + } + case 26: { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.EnumValueOptions(); + } + input.ReadMessage(Options); + break; + } + } + } + } + #endif + + } + + /// + /// Describes a service. + /// + public sealed partial class ServiceDescriptorProto : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ServiceDescriptorProto()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[8]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ServiceDescriptorProto() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ServiceDescriptorProto(ServiceDescriptorProto other) : this() { + name_ = other.name_; + method_ = other.method_.Clone(); + options_ = other.options_ != null ? other.options_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ServiceDescriptorProto Clone() { + return new ServiceDescriptorProto(this); + } + + /// Field number for the "name" field. + public const int NameFieldNumber = 1; + private readonly static string NameDefaultValue = ""; + + private string name_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string Name { + get { return name_ ?? NameDefaultValue; } + set { + name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "name" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasName { + get { return name_ != null; } + } + /// Clears the value of the "name" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearName() { + name_ = null; + } + + /// Field number for the "method" field. + public const int MethodFieldNumber = 2; + private static readonly pb::FieldCodec _repeated_method_codec + = pb::FieldCodec.ForMessage(18, global::Google.Protobuf.Reflection.MethodDescriptorProto.Parser); + private readonly pbc::RepeatedField method_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Method { + get { return method_; } + } + + /// Field number for the "options" field. + public const int OptionsFieldNumber = 3; + private global::Google.Protobuf.Reflection.ServiceOptions options_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.Reflection.ServiceOptions Options { + get { return options_; } + set { + options_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as ServiceDescriptorProto); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(ServiceDescriptorProto other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + if(!method_.Equals(other.method_)) return false; + if (!object.Equals(Options, other.Options)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasName) hash ^= Name.GetHashCode(); + hash ^= method_.GetHashCode(); + if (options_ != null) hash ^= Options.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasName) { + output.WriteRawTag(10); + output.WriteString(Name); + } + method_.WriteTo(output, _repeated_method_codec); + if (options_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Options); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasName) { + output.WriteRawTag(10); + output.WriteString(Name); + } + method_.WriteTo(ref output, _repeated_method_codec); + if (options_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Options); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasName) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + size += method_.CalculateSize(_repeated_method_codec); + if (options_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(ServiceDescriptorProto other) { + if (other == null) { + return; + } + if (other.HasName) { + Name = other.Name; + } + method_.Add(other.method_); + if (other.options_ != null) { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.ServiceOptions(); + } + Options.MergeFrom(other.Options); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + method_.AddEntriesFrom(input, _repeated_method_codec); + break; + } + case 26: { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.ServiceOptions(); + } + input.ReadMessage(Options); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + method_.AddEntriesFrom(ref input, _repeated_method_codec); + break; + } + case 26: { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.ServiceOptions(); + } + input.ReadMessage(Options); + break; + } + } + } + } + #endif + + } + + /// + /// Describes a method of a service. + /// + public sealed partial class MethodDescriptorProto : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new MethodDescriptorProto()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[9]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MethodDescriptorProto() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MethodDescriptorProto(MethodDescriptorProto other) : this() { + _hasBits0 = other._hasBits0; + name_ = other.name_; + inputType_ = other.inputType_; + outputType_ = other.outputType_; + options_ = other.options_ != null ? other.options_.Clone() : null; + clientStreaming_ = other.clientStreaming_; + serverStreaming_ = other.serverStreaming_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MethodDescriptorProto Clone() { + return new MethodDescriptorProto(this); + } + + /// Field number for the "name" field. + public const int NameFieldNumber = 1; + private readonly static string NameDefaultValue = ""; + + private string name_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string Name { + get { return name_ ?? NameDefaultValue; } + set { + name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "name" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasName { + get { return name_ != null; } + } + /// Clears the value of the "name" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearName() { + name_ = null; + } + + /// Field number for the "input_type" field. + public const int InputTypeFieldNumber = 2; + private readonly static string InputTypeDefaultValue = ""; + + private string inputType_; + /// + /// Input and output type names. These are resolved in the same way as + /// FieldDescriptorProto.type_name, but must refer to a message type. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string InputType { + get { return inputType_ ?? InputTypeDefaultValue; } + set { + inputType_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "input_type" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasInputType { + get { return inputType_ != null; } + } + /// Clears the value of the "input_type" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearInputType() { + inputType_ = null; + } + + /// Field number for the "output_type" field. + public const int OutputTypeFieldNumber = 3; + private readonly static string OutputTypeDefaultValue = ""; + + private string outputType_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string OutputType { + get { return outputType_ ?? OutputTypeDefaultValue; } + set { + outputType_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "output_type" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOutputType { + get { return outputType_ != null; } + } + /// Clears the value of the "output_type" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOutputType() { + outputType_ = null; + } + + /// Field number for the "options" field. + public const int OptionsFieldNumber = 4; + private global::Google.Protobuf.Reflection.MethodOptions options_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.Reflection.MethodOptions Options { + get { return options_; } + set { + options_ = value; + } + } + + /// Field number for the "client_streaming" field. + public const int ClientStreamingFieldNumber = 5; + private readonly static bool ClientStreamingDefaultValue = false; + + private bool clientStreaming_; + /// + /// Identifies if client streams multiple client messages + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool ClientStreaming { + get { if ((_hasBits0 & 1) != 0) { return clientStreaming_; } else { return ClientStreamingDefaultValue; } } + set { + _hasBits0 |= 1; + clientStreaming_ = value; + } + } + /// Gets whether the "client_streaming" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasClientStreaming { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "client_streaming" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearClientStreaming() { + _hasBits0 &= ~1; + } + + /// Field number for the "server_streaming" field. + public const int ServerStreamingFieldNumber = 6; + private readonly static bool ServerStreamingDefaultValue = false; + + private bool serverStreaming_; + /// + /// Identifies if server streams multiple server messages + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool ServerStreaming { + get { if ((_hasBits0 & 2) != 0) { return serverStreaming_; } else { return ServerStreamingDefaultValue; } } + set { + _hasBits0 |= 2; + serverStreaming_ = value; + } + } + /// Gets whether the "server_streaming" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasServerStreaming { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "server_streaming" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearServerStreaming() { + _hasBits0 &= ~2; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as MethodDescriptorProto); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(MethodDescriptorProto other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + if (InputType != other.InputType) return false; + if (OutputType != other.OutputType) return false; + if (!object.Equals(Options, other.Options)) return false; + if (ClientStreaming != other.ClientStreaming) return false; + if (ServerStreaming != other.ServerStreaming) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasName) hash ^= Name.GetHashCode(); + if (HasInputType) hash ^= InputType.GetHashCode(); + if (HasOutputType) hash ^= OutputType.GetHashCode(); + if (options_ != null) hash ^= Options.GetHashCode(); + if (HasClientStreaming) hash ^= ClientStreaming.GetHashCode(); + if (HasServerStreaming) hash ^= ServerStreaming.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasName) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (HasInputType) { + output.WriteRawTag(18); + output.WriteString(InputType); + } + if (HasOutputType) { + output.WriteRawTag(26); + output.WriteString(OutputType); + } + if (options_ != null) { + output.WriteRawTag(34); + output.WriteMessage(Options); + } + if (HasClientStreaming) { + output.WriteRawTag(40); + output.WriteBool(ClientStreaming); + } + if (HasServerStreaming) { + output.WriteRawTag(48); + output.WriteBool(ServerStreaming); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasName) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (HasInputType) { + output.WriteRawTag(18); + output.WriteString(InputType); + } + if (HasOutputType) { + output.WriteRawTag(26); + output.WriteString(OutputType); + } + if (options_ != null) { + output.WriteRawTag(34); + output.WriteMessage(Options); + } + if (HasClientStreaming) { + output.WriteRawTag(40); + output.WriteBool(ClientStreaming); + } + if (HasServerStreaming) { + output.WriteRawTag(48); + output.WriteBool(ServerStreaming); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasName) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + if (HasInputType) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(InputType); + } + if (HasOutputType) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(OutputType); + } + if (options_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options); + } + if (HasClientStreaming) { + size += 1 + 1; + } + if (HasServerStreaming) { + size += 1 + 1; + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(MethodDescriptorProto other) { + if (other == null) { + return; + } + if (other.HasName) { + Name = other.Name; + } + if (other.HasInputType) { + InputType = other.InputType; + } + if (other.HasOutputType) { + OutputType = other.OutputType; + } + if (other.options_ != null) { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.MethodOptions(); + } + Options.MergeFrom(other.Options); + } + if (other.HasClientStreaming) { + ClientStreaming = other.ClientStreaming; + } + if (other.HasServerStreaming) { + ServerStreaming = other.ServerStreaming; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + InputType = input.ReadString(); + break; + } + case 26: { + OutputType = input.ReadString(); + break; + } + case 34: { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.MethodOptions(); + } + input.ReadMessage(Options); + break; + } + case 40: { + ClientStreaming = input.ReadBool(); + break; + } + case 48: { + ServerStreaming = input.ReadBool(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + InputType = input.ReadString(); + break; + } + case 26: { + OutputType = input.ReadString(); + break; + } + case 34: { + if (options_ == null) { + Options = new global::Google.Protobuf.Reflection.MethodOptions(); + } + input.ReadMessage(Options); + break; + } + case 40: { + ClientStreaming = input.ReadBool(); + break; + } + case 48: { + ServerStreaming = input.ReadBool(); + break; + } + } + } + } + #endif + + } + + public sealed partial class FileOptions : pb::IExtendableMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new FileOptions()); + private pb::UnknownFieldSet _unknownFields; + internal pb::ExtensionSet _extensions; + private pb::ExtensionSet _Extensions { get { return _extensions; } } + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[10]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FileOptions() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FileOptions(FileOptions other) : this() { + _hasBits0 = other._hasBits0; + javaPackage_ = other.javaPackage_; + javaOuterClassname_ = other.javaOuterClassname_; + javaMultipleFiles_ = other.javaMultipleFiles_; + javaGenerateEqualsAndHash_ = other.javaGenerateEqualsAndHash_; + javaStringCheckUtf8_ = other.javaStringCheckUtf8_; + optimizeFor_ = other.optimizeFor_; + goPackage_ = other.goPackage_; + ccGenericServices_ = other.ccGenericServices_; + javaGenericServices_ = other.javaGenericServices_; + pyGenericServices_ = other.pyGenericServices_; + phpGenericServices_ = other.phpGenericServices_; + deprecated_ = other.deprecated_; + ccEnableArenas_ = other.ccEnableArenas_; + objcClassPrefix_ = other.objcClassPrefix_; + csharpNamespace_ = other.csharpNamespace_; + swiftPrefix_ = other.swiftPrefix_; + phpClassPrefix_ = other.phpClassPrefix_; + phpNamespace_ = other.phpNamespace_; + phpMetadataNamespace_ = other.phpMetadataNamespace_; + rubyPackage_ = other.rubyPackage_; + uninterpretedOption_ = other.uninterpretedOption_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + _extensions = pb::ExtensionSet.Clone(other._extensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FileOptions Clone() { + return new FileOptions(this); + } + + /// Field number for the "java_package" field. + public const int JavaPackageFieldNumber = 1; + private readonly static string JavaPackageDefaultValue = ""; + + private string javaPackage_; + /// + /// Sets the Java package where classes generated from this .proto will be + /// placed. By default, the proto package is used, but this is often + /// inappropriate because proto packages do not normally start with backwards + /// domain names. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string JavaPackage { + get { return javaPackage_ ?? JavaPackageDefaultValue; } + set { + javaPackage_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "java_package" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasJavaPackage { + get { return javaPackage_ != null; } + } + /// Clears the value of the "java_package" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearJavaPackage() { + javaPackage_ = null; + } + + /// Field number for the "java_outer_classname" field. + public const int JavaOuterClassnameFieldNumber = 8; + private readonly static string JavaOuterClassnameDefaultValue = ""; + + private string javaOuterClassname_; + /// + /// Controls the name of the wrapper Java class generated for the .proto file. + /// That class will always contain the .proto file's getDescriptor() method as + /// well as any top-level extensions defined in the .proto file. + /// If java_multiple_files is disabled, then all the other classes from the + /// .proto file will be nested inside the single wrapper outer class. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string JavaOuterClassname { + get { return javaOuterClassname_ ?? JavaOuterClassnameDefaultValue; } + set { + javaOuterClassname_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "java_outer_classname" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasJavaOuterClassname { + get { return javaOuterClassname_ != null; } + } + /// Clears the value of the "java_outer_classname" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearJavaOuterClassname() { + javaOuterClassname_ = null; + } + + /// Field number for the "java_multiple_files" field. + public const int JavaMultipleFilesFieldNumber = 10; + private readonly static bool JavaMultipleFilesDefaultValue = false; + + private bool javaMultipleFiles_; + /// + /// If enabled, then the Java code generator will generate a separate .java + /// file for each top-level message, enum, and service defined in the .proto + /// file. Thus, these types will *not* be nested inside the wrapper class + /// named by java_outer_classname. However, the wrapper class will still be + /// generated to contain the file's getDescriptor() method as well as any + /// top-level extensions defined in the file. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool JavaMultipleFiles { + get { if ((_hasBits0 & 2) != 0) { return javaMultipleFiles_; } else { return JavaMultipleFilesDefaultValue; } } + set { + _hasBits0 |= 2; + javaMultipleFiles_ = value; + } + } + /// Gets whether the "java_multiple_files" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasJavaMultipleFiles { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "java_multiple_files" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearJavaMultipleFiles() { + _hasBits0 &= ~2; + } + + /// Field number for the "java_generate_equals_and_hash" field. + public const int JavaGenerateEqualsAndHashFieldNumber = 20; + private readonly static bool JavaGenerateEqualsAndHashDefaultValue = false; + + private bool javaGenerateEqualsAndHash_; + /// + /// This option does nothing. + /// + [global::System.ObsoleteAttribute] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool JavaGenerateEqualsAndHash { + get { if ((_hasBits0 & 32) != 0) { return javaGenerateEqualsAndHash_; } else { return JavaGenerateEqualsAndHashDefaultValue; } } + set { + _hasBits0 |= 32; + javaGenerateEqualsAndHash_ = value; + } + } + /// Gets whether the "java_generate_equals_and_hash" field is set + [global::System.ObsoleteAttribute] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasJavaGenerateEqualsAndHash { + get { return (_hasBits0 & 32) != 0; } + } + /// Clears the value of the "java_generate_equals_and_hash" field + [global::System.ObsoleteAttribute] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearJavaGenerateEqualsAndHash() { + _hasBits0 &= ~32; + } + + /// Field number for the "java_string_check_utf8" field. + public const int JavaStringCheckUtf8FieldNumber = 27; + private readonly static bool JavaStringCheckUtf8DefaultValue = false; + + private bool javaStringCheckUtf8_; + /// + /// If set true, then the Java2 code generator will generate code that + /// throws an exception whenever an attempt is made to assign a non-UTF-8 + /// byte sequence to a string field. + /// Message reflection will do the same. + /// However, an extension field still accepts non-UTF-8 byte sequences. + /// This option has no effect on when used with the lite runtime. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool JavaStringCheckUtf8 { + get { if ((_hasBits0 & 128) != 0) { return javaStringCheckUtf8_; } else { return JavaStringCheckUtf8DefaultValue; } } + set { + _hasBits0 |= 128; + javaStringCheckUtf8_ = value; + } + } + /// Gets whether the "java_string_check_utf8" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasJavaStringCheckUtf8 { + get { return (_hasBits0 & 128) != 0; } + } + /// Clears the value of the "java_string_check_utf8" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearJavaStringCheckUtf8() { + _hasBits0 &= ~128; + } + + /// Field number for the "optimize_for" field. + public const int OptimizeForFieldNumber = 9; + private readonly static global::Google.Protobuf.Reflection.FileOptions.Types.OptimizeMode OptimizeForDefaultValue = global::Google.Protobuf.Reflection.FileOptions.Types.OptimizeMode.Speed; + + private global::Google.Protobuf.Reflection.FileOptions.Types.OptimizeMode optimizeFor_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.Reflection.FileOptions.Types.OptimizeMode OptimizeFor { + get { if ((_hasBits0 & 1) != 0) { return optimizeFor_; } else { return OptimizeForDefaultValue; } } + set { + _hasBits0 |= 1; + optimizeFor_ = value; + } + } + /// Gets whether the "optimize_for" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptimizeFor { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "optimize_for" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptimizeFor() { + _hasBits0 &= ~1; + } + + /// Field number for the "go_package" field. + public const int GoPackageFieldNumber = 11; + private readonly static string GoPackageDefaultValue = ""; + + private string goPackage_; + /// + /// Sets the Go package where structs generated from this .proto will be + /// placed. If omitted, the Go package will be derived from the following: + /// - The basename of the package import path, if provided. + /// - Otherwise, the package statement in the .proto file, if present. + /// - Otherwise, the basename of the .proto file, without extension. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string GoPackage { + get { return goPackage_ ?? GoPackageDefaultValue; } + set { + goPackage_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "go_package" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasGoPackage { + get { return goPackage_ != null; } + } + /// Clears the value of the "go_package" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearGoPackage() { + goPackage_ = null; + } + + /// Field number for the "cc_generic_services" field. + public const int CcGenericServicesFieldNumber = 16; + private readonly static bool CcGenericServicesDefaultValue = false; + + private bool ccGenericServices_; + /// + /// Should generic services be generated in each language? "Generic" services + /// are not specific to any particular RPC system. They are generated by the + /// main code generators in each language (without additional plugins). + /// Generic services were the only kind of service generation supported by + /// early versions of google.protobuf. + /// + /// Generic services are now considered deprecated in favor of using plugins + /// that generate code specific to your particular RPC system. Therefore, + /// these default to false. Old code which depends on generic services should + /// explicitly set them to true. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool CcGenericServices { + get { if ((_hasBits0 & 4) != 0) { return ccGenericServices_; } else { return CcGenericServicesDefaultValue; } } + set { + _hasBits0 |= 4; + ccGenericServices_ = value; + } + } + /// Gets whether the "cc_generic_services" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasCcGenericServices { + get { return (_hasBits0 & 4) != 0; } + } + /// Clears the value of the "cc_generic_services" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearCcGenericServices() { + _hasBits0 &= ~4; + } + + /// Field number for the "java_generic_services" field. + public const int JavaGenericServicesFieldNumber = 17; + private readonly static bool JavaGenericServicesDefaultValue = false; + + private bool javaGenericServices_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool JavaGenericServices { + get { if ((_hasBits0 & 8) != 0) { return javaGenericServices_; } else { return JavaGenericServicesDefaultValue; } } + set { + _hasBits0 |= 8; + javaGenericServices_ = value; + } + } + /// Gets whether the "java_generic_services" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasJavaGenericServices { + get { return (_hasBits0 & 8) != 0; } + } + /// Clears the value of the "java_generic_services" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearJavaGenericServices() { + _hasBits0 &= ~8; + } + + /// Field number for the "py_generic_services" field. + public const int PyGenericServicesFieldNumber = 18; + private readonly static bool PyGenericServicesDefaultValue = false; + + private bool pyGenericServices_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool PyGenericServices { + get { if ((_hasBits0 & 16) != 0) { return pyGenericServices_; } else { return PyGenericServicesDefaultValue; } } + set { + _hasBits0 |= 16; + pyGenericServices_ = value; + } + } + /// Gets whether the "py_generic_services" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasPyGenericServices { + get { return (_hasBits0 & 16) != 0; } + } + /// Clears the value of the "py_generic_services" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearPyGenericServices() { + _hasBits0 &= ~16; + } + + /// Field number for the "php_generic_services" field. + public const int PhpGenericServicesFieldNumber = 42; + private readonly static bool PhpGenericServicesDefaultValue = false; + + private bool phpGenericServices_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool PhpGenericServices { + get { if ((_hasBits0 & 512) != 0) { return phpGenericServices_; } else { return PhpGenericServicesDefaultValue; } } + set { + _hasBits0 |= 512; + phpGenericServices_ = value; + } + } + /// Gets whether the "php_generic_services" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasPhpGenericServices { + get { return (_hasBits0 & 512) != 0; } + } + /// Clears the value of the "php_generic_services" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearPhpGenericServices() { + _hasBits0 &= ~512; + } + + /// Field number for the "deprecated" field. + public const int DeprecatedFieldNumber = 23; + private readonly static bool DeprecatedDefaultValue = false; + + private bool deprecated_; + /// + /// Is this file deprecated? + /// Depending on the target platform, this can emit Deprecated annotations + /// for everything in the file, or it will be completely ignored; in the very + /// least, this is a formalization for deprecating files. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Deprecated { + get { if ((_hasBits0 & 64) != 0) { return deprecated_; } else { return DeprecatedDefaultValue; } } + set { + _hasBits0 |= 64; + deprecated_ = value; + } + } + /// Gets whether the "deprecated" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDeprecated { + get { return (_hasBits0 & 64) != 0; } + } + /// Clears the value of the "deprecated" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDeprecated() { + _hasBits0 &= ~64; + } + + /// Field number for the "cc_enable_arenas" field. + public const int CcEnableArenasFieldNumber = 31; + private readonly static bool CcEnableArenasDefaultValue = true; + + private bool ccEnableArenas_; + /// + /// Enables the use of arenas for the proto messages in this file. This applies + /// only to generated classes for C++. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool CcEnableArenas { + get { if ((_hasBits0 & 256) != 0) { return ccEnableArenas_; } else { return CcEnableArenasDefaultValue; } } + set { + _hasBits0 |= 256; + ccEnableArenas_ = value; + } + } + /// Gets whether the "cc_enable_arenas" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasCcEnableArenas { + get { return (_hasBits0 & 256) != 0; } + } + /// Clears the value of the "cc_enable_arenas" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearCcEnableArenas() { + _hasBits0 &= ~256; + } + + /// Field number for the "objc_class_prefix" field. + public const int ObjcClassPrefixFieldNumber = 36; + private readonly static string ObjcClassPrefixDefaultValue = ""; + + private string objcClassPrefix_; + /// + /// Sets the objective c class prefix which is prepended to all objective c + /// generated classes from this .proto. There is no default. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string ObjcClassPrefix { + get { return objcClassPrefix_ ?? ObjcClassPrefixDefaultValue; } + set { + objcClassPrefix_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "objc_class_prefix" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasObjcClassPrefix { + get { return objcClassPrefix_ != null; } + } + /// Clears the value of the "objc_class_prefix" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearObjcClassPrefix() { + objcClassPrefix_ = null; + } + + /// Field number for the "csharp_namespace" field. + public const int CsharpNamespaceFieldNumber = 37; + private readonly static string CsharpNamespaceDefaultValue = ""; + + private string csharpNamespace_; + /// + /// Namespace for generated classes; defaults to the package. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string CsharpNamespace { + get { return csharpNamespace_ ?? CsharpNamespaceDefaultValue; } + set { + csharpNamespace_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "csharp_namespace" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasCsharpNamespace { + get { return csharpNamespace_ != null; } + } + /// Clears the value of the "csharp_namespace" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearCsharpNamespace() { + csharpNamespace_ = null; + } + + /// Field number for the "swift_prefix" field. + public const int SwiftPrefixFieldNumber = 39; + private readonly static string SwiftPrefixDefaultValue = ""; + + private string swiftPrefix_; + /// + /// By default Swift generators will take the proto package and CamelCase it + /// replacing '.' with underscore and use that to prefix the types/symbols + /// defined. When this options is provided, they will use this value instead + /// to prefix the types/symbols defined. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string SwiftPrefix { + get { return swiftPrefix_ ?? SwiftPrefixDefaultValue; } + set { + swiftPrefix_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "swift_prefix" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasSwiftPrefix { + get { return swiftPrefix_ != null; } + } + /// Clears the value of the "swift_prefix" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearSwiftPrefix() { + swiftPrefix_ = null; + } + + /// Field number for the "php_class_prefix" field. + public const int PhpClassPrefixFieldNumber = 40; + private readonly static string PhpClassPrefixDefaultValue = ""; + + private string phpClassPrefix_; + /// + /// Sets the php class prefix which is prepended to all php generated classes + /// from this .proto. Default is empty. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string PhpClassPrefix { + get { return phpClassPrefix_ ?? PhpClassPrefixDefaultValue; } + set { + phpClassPrefix_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "php_class_prefix" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasPhpClassPrefix { + get { return phpClassPrefix_ != null; } + } + /// Clears the value of the "php_class_prefix" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearPhpClassPrefix() { + phpClassPrefix_ = null; + } + + /// Field number for the "php_namespace" field. + public const int PhpNamespaceFieldNumber = 41; + private readonly static string PhpNamespaceDefaultValue = ""; + + private string phpNamespace_; + /// + /// Use this option to change the namespace of php generated classes. Default + /// is empty. When this option is empty, the package name will be used for + /// determining the namespace. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string PhpNamespace { + get { return phpNamespace_ ?? PhpNamespaceDefaultValue; } + set { + phpNamespace_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "php_namespace" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasPhpNamespace { + get { return phpNamespace_ != null; } + } + /// Clears the value of the "php_namespace" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearPhpNamespace() { + phpNamespace_ = null; + } + + /// Field number for the "php_metadata_namespace" field. + public const int PhpMetadataNamespaceFieldNumber = 44; + private readonly static string PhpMetadataNamespaceDefaultValue = ""; + + private string phpMetadataNamespace_; + /// + /// Use this option to change the namespace of php generated metadata classes. + /// Default is empty. When this option is empty, the proto file name will be + /// used for determining the namespace. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string PhpMetadataNamespace { + get { return phpMetadataNamespace_ ?? PhpMetadataNamespaceDefaultValue; } + set { + phpMetadataNamespace_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "php_metadata_namespace" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasPhpMetadataNamespace { + get { return phpMetadataNamespace_ != null; } + } + /// Clears the value of the "php_metadata_namespace" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearPhpMetadataNamespace() { + phpMetadataNamespace_ = null; + } + + /// Field number for the "ruby_package" field. + public const int RubyPackageFieldNumber = 45; + private readonly static string RubyPackageDefaultValue = ""; + + private string rubyPackage_; + /// + /// Use this option to change the package of ruby generated classes. Default + /// is empty. When this option is not set, the package name will be used for + /// determining the ruby package. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string RubyPackage { + get { return rubyPackage_ ?? RubyPackageDefaultValue; } + set { + rubyPackage_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "ruby_package" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasRubyPackage { + get { return rubyPackage_ != null; } + } + /// Clears the value of the "ruby_package" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearRubyPackage() { + rubyPackage_ = null; + } + + /// Field number for the "uninterpreted_option" field. + public const int UninterpretedOptionFieldNumber = 999; + private static readonly pb::FieldCodec _repeated_uninterpretedOption_codec + = pb::FieldCodec.ForMessage(7994, global::Google.Protobuf.Reflection.UninterpretedOption.Parser); + private readonly pbc::RepeatedField uninterpretedOption_ = new pbc::RepeatedField(); + /// + /// The parser stores options it doesn't recognize here. + /// See the documentation for the "Options" section above. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField UninterpretedOption { + get { return uninterpretedOption_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as FileOptions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(FileOptions other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (JavaPackage != other.JavaPackage) return false; + if (JavaOuterClassname != other.JavaOuterClassname) return false; + if (JavaMultipleFiles != other.JavaMultipleFiles) return false; + if (JavaGenerateEqualsAndHash != other.JavaGenerateEqualsAndHash) return false; + if (JavaStringCheckUtf8 != other.JavaStringCheckUtf8) return false; + if (OptimizeFor != other.OptimizeFor) return false; + if (GoPackage != other.GoPackage) return false; + if (CcGenericServices != other.CcGenericServices) return false; + if (JavaGenericServices != other.JavaGenericServices) return false; + if (PyGenericServices != other.PyGenericServices) return false; + if (PhpGenericServices != other.PhpGenericServices) return false; + if (Deprecated != other.Deprecated) return false; + if (CcEnableArenas != other.CcEnableArenas) return false; + if (ObjcClassPrefix != other.ObjcClassPrefix) return false; + if (CsharpNamespace != other.CsharpNamespace) return false; + if (SwiftPrefix != other.SwiftPrefix) return false; + if (PhpClassPrefix != other.PhpClassPrefix) return false; + if (PhpNamespace != other.PhpNamespace) return false; + if (PhpMetadataNamespace != other.PhpMetadataNamespace) return false; + if (RubyPackage != other.RubyPackage) return false; + if(!uninterpretedOption_.Equals(other.uninterpretedOption_)) return false; + if (!Equals(_extensions, other._extensions)) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasJavaPackage) hash ^= JavaPackage.GetHashCode(); + if (HasJavaOuterClassname) hash ^= JavaOuterClassname.GetHashCode(); + if (HasJavaMultipleFiles) hash ^= JavaMultipleFiles.GetHashCode(); + if (HasJavaGenerateEqualsAndHash) hash ^= JavaGenerateEqualsAndHash.GetHashCode(); + if (HasJavaStringCheckUtf8) hash ^= JavaStringCheckUtf8.GetHashCode(); + if (HasOptimizeFor) hash ^= OptimizeFor.GetHashCode(); + if (HasGoPackage) hash ^= GoPackage.GetHashCode(); + if (HasCcGenericServices) hash ^= CcGenericServices.GetHashCode(); + if (HasJavaGenericServices) hash ^= JavaGenericServices.GetHashCode(); + if (HasPyGenericServices) hash ^= PyGenericServices.GetHashCode(); + if (HasPhpGenericServices) hash ^= PhpGenericServices.GetHashCode(); + if (HasDeprecated) hash ^= Deprecated.GetHashCode(); + if (HasCcEnableArenas) hash ^= CcEnableArenas.GetHashCode(); + if (HasObjcClassPrefix) hash ^= ObjcClassPrefix.GetHashCode(); + if (HasCsharpNamespace) hash ^= CsharpNamespace.GetHashCode(); + if (HasSwiftPrefix) hash ^= SwiftPrefix.GetHashCode(); + if (HasPhpClassPrefix) hash ^= PhpClassPrefix.GetHashCode(); + if (HasPhpNamespace) hash ^= PhpNamespace.GetHashCode(); + if (HasPhpMetadataNamespace) hash ^= PhpMetadataNamespace.GetHashCode(); + if (HasRubyPackage) hash ^= RubyPackage.GetHashCode(); + hash ^= uninterpretedOption_.GetHashCode(); + if (_extensions != null) { + hash ^= _extensions.GetHashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasJavaPackage) { + output.WriteRawTag(10); + output.WriteString(JavaPackage); + } + if (HasJavaOuterClassname) { + output.WriteRawTag(66); + output.WriteString(JavaOuterClassname); + } + if (HasOptimizeFor) { + output.WriteRawTag(72); + output.WriteEnum((int) OptimizeFor); + } + if (HasJavaMultipleFiles) { + output.WriteRawTag(80); + output.WriteBool(JavaMultipleFiles); + } + if (HasGoPackage) { + output.WriteRawTag(90); + output.WriteString(GoPackage); + } + if (HasCcGenericServices) { + output.WriteRawTag(128, 1); + output.WriteBool(CcGenericServices); + } + if (HasJavaGenericServices) { + output.WriteRawTag(136, 1); + output.WriteBool(JavaGenericServices); + } + if (HasPyGenericServices) { + output.WriteRawTag(144, 1); + output.WriteBool(PyGenericServices); + } + if (HasJavaGenerateEqualsAndHash) { + output.WriteRawTag(160, 1); + output.WriteBool(JavaGenerateEqualsAndHash); + } + if (HasDeprecated) { + output.WriteRawTag(184, 1); + output.WriteBool(Deprecated); + } + if (HasJavaStringCheckUtf8) { + output.WriteRawTag(216, 1); + output.WriteBool(JavaStringCheckUtf8); + } + if (HasCcEnableArenas) { + output.WriteRawTag(248, 1); + output.WriteBool(CcEnableArenas); + } + if (HasObjcClassPrefix) { + output.WriteRawTag(162, 2); + output.WriteString(ObjcClassPrefix); + } + if (HasCsharpNamespace) { + output.WriteRawTag(170, 2); + output.WriteString(CsharpNamespace); + } + if (HasSwiftPrefix) { + output.WriteRawTag(186, 2); + output.WriteString(SwiftPrefix); + } + if (HasPhpClassPrefix) { + output.WriteRawTag(194, 2); + output.WriteString(PhpClassPrefix); + } + if (HasPhpNamespace) { + output.WriteRawTag(202, 2); + output.WriteString(PhpNamespace); + } + if (HasPhpGenericServices) { + output.WriteRawTag(208, 2); + output.WriteBool(PhpGenericServices); + } + if (HasPhpMetadataNamespace) { + output.WriteRawTag(226, 2); + output.WriteString(PhpMetadataNamespace); + } + if (HasRubyPackage) { + output.WriteRawTag(234, 2); + output.WriteString(RubyPackage); + } + uninterpretedOption_.WriteTo(output, _repeated_uninterpretedOption_codec); + if (_extensions != null) { + _extensions.WriteTo(output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasJavaPackage) { + output.WriteRawTag(10); + output.WriteString(JavaPackage); + } + if (HasJavaOuterClassname) { + output.WriteRawTag(66); + output.WriteString(JavaOuterClassname); + } + if (HasOptimizeFor) { + output.WriteRawTag(72); + output.WriteEnum((int) OptimizeFor); + } + if (HasJavaMultipleFiles) { + output.WriteRawTag(80); + output.WriteBool(JavaMultipleFiles); + } + if (HasGoPackage) { + output.WriteRawTag(90); + output.WriteString(GoPackage); + } + if (HasCcGenericServices) { + output.WriteRawTag(128, 1); + output.WriteBool(CcGenericServices); + } + if (HasJavaGenericServices) { + output.WriteRawTag(136, 1); + output.WriteBool(JavaGenericServices); + } + if (HasPyGenericServices) { + output.WriteRawTag(144, 1); + output.WriteBool(PyGenericServices); + } + if (HasJavaGenerateEqualsAndHash) { + output.WriteRawTag(160, 1); + output.WriteBool(JavaGenerateEqualsAndHash); + } + if (HasDeprecated) { + output.WriteRawTag(184, 1); + output.WriteBool(Deprecated); + } + if (HasJavaStringCheckUtf8) { + output.WriteRawTag(216, 1); + output.WriteBool(JavaStringCheckUtf8); + } + if (HasCcEnableArenas) { + output.WriteRawTag(248, 1); + output.WriteBool(CcEnableArenas); + } + if (HasObjcClassPrefix) { + output.WriteRawTag(162, 2); + output.WriteString(ObjcClassPrefix); + } + if (HasCsharpNamespace) { + output.WriteRawTag(170, 2); + output.WriteString(CsharpNamespace); + } + if (HasSwiftPrefix) { + output.WriteRawTag(186, 2); + output.WriteString(SwiftPrefix); + } + if (HasPhpClassPrefix) { + output.WriteRawTag(194, 2); + output.WriteString(PhpClassPrefix); + } + if (HasPhpNamespace) { + output.WriteRawTag(202, 2); + output.WriteString(PhpNamespace); + } + if (HasPhpGenericServices) { + output.WriteRawTag(208, 2); + output.WriteBool(PhpGenericServices); + } + if (HasPhpMetadataNamespace) { + output.WriteRawTag(226, 2); + output.WriteString(PhpMetadataNamespace); + } + if (HasRubyPackage) { + output.WriteRawTag(234, 2); + output.WriteString(RubyPackage); + } + uninterpretedOption_.WriteTo(ref output, _repeated_uninterpretedOption_codec); + if (_extensions != null) { + _extensions.WriteTo(ref output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasJavaPackage) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(JavaPackage); + } + if (HasJavaOuterClassname) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(JavaOuterClassname); + } + if (HasJavaMultipleFiles) { + size += 1 + 1; + } + if (HasJavaGenerateEqualsAndHash) { + size += 2 + 1; + } + if (HasJavaStringCheckUtf8) { + size += 2 + 1; + } + if (HasOptimizeFor) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) OptimizeFor); + } + if (HasGoPackage) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(GoPackage); + } + if (HasCcGenericServices) { + size += 2 + 1; + } + if (HasJavaGenericServices) { + size += 2 + 1; + } + if (HasPyGenericServices) { + size += 2 + 1; + } + if (HasPhpGenericServices) { + size += 2 + 1; + } + if (HasDeprecated) { + size += 2 + 1; + } + if (HasCcEnableArenas) { + size += 2 + 1; + } + if (HasObjcClassPrefix) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(ObjcClassPrefix); + } + if (HasCsharpNamespace) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(CsharpNamespace); + } + if (HasSwiftPrefix) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(SwiftPrefix); + } + if (HasPhpClassPrefix) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(PhpClassPrefix); + } + if (HasPhpNamespace) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(PhpNamespace); + } + if (HasPhpMetadataNamespace) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(PhpMetadataNamespace); + } + if (HasRubyPackage) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(RubyPackage); + } + size += uninterpretedOption_.CalculateSize(_repeated_uninterpretedOption_codec); + if (_extensions != null) { + size += _extensions.CalculateSize(); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(FileOptions other) { + if (other == null) { + return; + } + if (other.HasJavaPackage) { + JavaPackage = other.JavaPackage; + } + if (other.HasJavaOuterClassname) { + JavaOuterClassname = other.JavaOuterClassname; + } + if (other.HasJavaMultipleFiles) { + JavaMultipleFiles = other.JavaMultipleFiles; + } + if (other.HasJavaGenerateEqualsAndHash) { + JavaGenerateEqualsAndHash = other.JavaGenerateEqualsAndHash; + } + if (other.HasJavaStringCheckUtf8) { + JavaStringCheckUtf8 = other.JavaStringCheckUtf8; + } + if (other.HasOptimizeFor) { + OptimizeFor = other.OptimizeFor; + } + if (other.HasGoPackage) { + GoPackage = other.GoPackage; + } + if (other.HasCcGenericServices) { + CcGenericServices = other.CcGenericServices; + } + if (other.HasJavaGenericServices) { + JavaGenericServices = other.JavaGenericServices; + } + if (other.HasPyGenericServices) { + PyGenericServices = other.PyGenericServices; + } + if (other.HasPhpGenericServices) { + PhpGenericServices = other.PhpGenericServices; + } + if (other.HasDeprecated) { + Deprecated = other.Deprecated; + } + if (other.HasCcEnableArenas) { + CcEnableArenas = other.CcEnableArenas; + } + if (other.HasObjcClassPrefix) { + ObjcClassPrefix = other.ObjcClassPrefix; + } + if (other.HasCsharpNamespace) { + CsharpNamespace = other.CsharpNamespace; + } + if (other.HasSwiftPrefix) { + SwiftPrefix = other.SwiftPrefix; + } + if (other.HasPhpClassPrefix) { + PhpClassPrefix = other.PhpClassPrefix; + } + if (other.HasPhpNamespace) { + PhpNamespace = other.PhpNamespace; + } + if (other.HasPhpMetadataNamespace) { + PhpMetadataNamespace = other.PhpMetadataNamespace; + } + if (other.HasRubyPackage) { + RubyPackage = other.RubyPackage; + } + uninterpretedOption_.Add(other.uninterpretedOption_); + pb::ExtensionSet.MergeFrom(ref _extensions, other._extensions); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + } + break; + case 10: { + JavaPackage = input.ReadString(); + break; + } + case 66: { + JavaOuterClassname = input.ReadString(); + break; + } + case 72: { + OptimizeFor = (global::Google.Protobuf.Reflection.FileOptions.Types.OptimizeMode) input.ReadEnum(); + break; + } + case 80: { + JavaMultipleFiles = input.ReadBool(); + break; + } + case 90: { + GoPackage = input.ReadString(); + break; + } + case 128: { + CcGenericServices = input.ReadBool(); + break; + } + case 136: { + JavaGenericServices = input.ReadBool(); + break; + } + case 144: { + PyGenericServices = input.ReadBool(); + break; + } + case 160: { + JavaGenerateEqualsAndHash = input.ReadBool(); + break; + } + case 184: { + Deprecated = input.ReadBool(); + break; + } + case 216: { + JavaStringCheckUtf8 = input.ReadBool(); + break; + } + case 248: { + CcEnableArenas = input.ReadBool(); + break; + } + case 290: { + ObjcClassPrefix = input.ReadString(); + break; + } + case 298: { + CsharpNamespace = input.ReadString(); + break; + } + case 314: { + SwiftPrefix = input.ReadString(); + break; + } + case 322: { + PhpClassPrefix = input.ReadString(); + break; + } + case 330: { + PhpNamespace = input.ReadString(); + break; + } + case 336: { + PhpGenericServices = input.ReadBool(); + break; + } + case 354: { + PhpMetadataNamespace = input.ReadString(); + break; + } + case 362: { + RubyPackage = input.ReadString(); + break; + } + case 7994: { + uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + } + break; + case 10: { + JavaPackage = input.ReadString(); + break; + } + case 66: { + JavaOuterClassname = input.ReadString(); + break; + } + case 72: { + OptimizeFor = (global::Google.Protobuf.Reflection.FileOptions.Types.OptimizeMode) input.ReadEnum(); + break; + } + case 80: { + JavaMultipleFiles = input.ReadBool(); + break; + } + case 90: { + GoPackage = input.ReadString(); + break; + } + case 128: { + CcGenericServices = input.ReadBool(); + break; + } + case 136: { + JavaGenericServices = input.ReadBool(); + break; + } + case 144: { + PyGenericServices = input.ReadBool(); + break; + } + case 160: { + JavaGenerateEqualsAndHash = input.ReadBool(); + break; + } + case 184: { + Deprecated = input.ReadBool(); + break; + } + case 216: { + JavaStringCheckUtf8 = input.ReadBool(); + break; + } + case 248: { + CcEnableArenas = input.ReadBool(); + break; + } + case 290: { + ObjcClassPrefix = input.ReadString(); + break; + } + case 298: { + CsharpNamespace = input.ReadString(); + break; + } + case 314: { + SwiftPrefix = input.ReadString(); + break; + } + case 322: { + PhpClassPrefix = input.ReadString(); + break; + } + case 330: { + PhpNamespace = input.ReadString(); + break; + } + case 336: { + PhpGenericServices = input.ReadBool(); + break; + } + case 354: { + PhpMetadataNamespace = input.ReadString(); + break; + } + case 362: { + RubyPackage = input.ReadString(); + break; + } + case 7994: { + uninterpretedOption_.AddEntriesFrom(ref input, _repeated_uninterpretedOption_codec); + break; + } + } + } + } + #endif + + public TValue GetExtension(pb::Extension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetOrInitializeExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.GetOrInitialize(ref _extensions, extension); + } + public void SetExtension(pb::Extension extension, TValue value) { + pb::ExtensionSet.Set(ref _extensions, extension, value); + } + public bool HasExtension(pb::Extension extension) { + return pb::ExtensionSet.Has(ref _extensions, extension); + } + public void ClearExtension(pb::Extension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + public void ClearExtension(pb::RepeatedExtension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + + #region Nested types + /// Container for nested types declared in the FileOptions message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + /// + /// Generated classes can be optimized for speed or code size. + /// + public enum OptimizeMode { + /// + /// Generate complete code for parsing, serialization, + /// + [pbr::OriginalName("SPEED")] Speed = 1, + /// + /// etc. + /// + [pbr::OriginalName("CODE_SIZE")] CodeSize = 2, + /// + /// Generate code using MessageLite and the lite runtime. + /// + [pbr::OriginalName("LITE_RUNTIME")] LiteRuntime = 3, + } + + } + #endregion + + } + + public sealed partial class MessageOptions : pb::IExtendableMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new MessageOptions()); + private pb::UnknownFieldSet _unknownFields; + internal pb::ExtensionSet _extensions; + private pb::ExtensionSet _Extensions { get { return _extensions; } } + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[11]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MessageOptions() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MessageOptions(MessageOptions other) : this() { + _hasBits0 = other._hasBits0; + messageSetWireFormat_ = other.messageSetWireFormat_; + noStandardDescriptorAccessor_ = other.noStandardDescriptorAccessor_; + deprecated_ = other.deprecated_; + mapEntry_ = other.mapEntry_; + uninterpretedOption_ = other.uninterpretedOption_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + _extensions = pb::ExtensionSet.Clone(other._extensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MessageOptions Clone() { + return new MessageOptions(this); + } + + /// Field number for the "message_set_wire_format" field. + public const int MessageSetWireFormatFieldNumber = 1; + private readonly static bool MessageSetWireFormatDefaultValue = false; + + private bool messageSetWireFormat_; + /// + /// Set true to use the old proto1 MessageSet wire format for extensions. + /// This is provided for backwards-compatibility with the MessageSet wire + /// format. You should not use this for any other reason: It's less + /// efficient, has fewer features, and is more complicated. + /// + /// The message must be defined exactly as follows: + /// message Foo { + /// option message_set_wire_format = true; + /// extensions 4 to max; + /// } + /// Note that the message cannot have any defined fields; MessageSets only + /// have extensions. + /// + /// All extensions of your type must be singular messages; e.g. they cannot + /// be int32s, enums, or repeated messages. + /// + /// Because this is an option, the above two restrictions are not enforced by + /// the protocol compiler. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool MessageSetWireFormat { + get { if ((_hasBits0 & 1) != 0) { return messageSetWireFormat_; } else { return MessageSetWireFormatDefaultValue; } } + set { + _hasBits0 |= 1; + messageSetWireFormat_ = value; + } + } + /// Gets whether the "message_set_wire_format" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasMessageSetWireFormat { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "message_set_wire_format" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearMessageSetWireFormat() { + _hasBits0 &= ~1; + } + + /// Field number for the "no_standard_descriptor_accessor" field. + public const int NoStandardDescriptorAccessorFieldNumber = 2; + private readonly static bool NoStandardDescriptorAccessorDefaultValue = false; + + private bool noStandardDescriptorAccessor_; + /// + /// Disables the generation of the standard "descriptor()" accessor, which can + /// conflict with a field of the same name. This is meant to make migration + /// from proto1 easier; new code should avoid fields named "descriptor". + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool NoStandardDescriptorAccessor { + get { if ((_hasBits0 & 2) != 0) { return noStandardDescriptorAccessor_; } else { return NoStandardDescriptorAccessorDefaultValue; } } + set { + _hasBits0 |= 2; + noStandardDescriptorAccessor_ = value; + } + } + /// Gets whether the "no_standard_descriptor_accessor" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasNoStandardDescriptorAccessor { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "no_standard_descriptor_accessor" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearNoStandardDescriptorAccessor() { + _hasBits0 &= ~2; + } + + /// Field number for the "deprecated" field. + public const int DeprecatedFieldNumber = 3; + private readonly static bool DeprecatedDefaultValue = false; + + private bool deprecated_; + /// + /// Is this message deprecated? + /// Depending on the target platform, this can emit Deprecated annotations + /// for the message, or it will be completely ignored; in the very least, + /// this is a formalization for deprecating messages. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Deprecated { + get { if ((_hasBits0 & 4) != 0) { return deprecated_; } else { return DeprecatedDefaultValue; } } + set { + _hasBits0 |= 4; + deprecated_ = value; + } + } + /// Gets whether the "deprecated" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDeprecated { + get { return (_hasBits0 & 4) != 0; } + } + /// Clears the value of the "deprecated" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDeprecated() { + _hasBits0 &= ~4; + } + + /// Field number for the "map_entry" field. + public const int MapEntryFieldNumber = 7; + private readonly static bool MapEntryDefaultValue = false; + + private bool mapEntry_; + /// + /// Whether the message is an automatically generated map entry type for the + /// maps field. + /// + /// For maps fields: + /// map<KeyType, ValueType> map_field = 1; + /// The parsed descriptor looks like: + /// message MapFieldEntry { + /// option map_entry = true; + /// optional KeyType key = 1; + /// optional ValueType value = 2; + /// } + /// repeated MapFieldEntry map_field = 1; + /// + /// Implementations may choose not to generate the map_entry=true message, but + /// use a native map in the target language to hold the keys and values. + /// The reflection APIs in such implementations still need to work as + /// if the field is a repeated message field. + /// + /// NOTE: Do not set the option in .proto files. Always use the maps syntax + /// instead. The option should only be implicitly set by the proto compiler + /// parser. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool MapEntry { + get { if ((_hasBits0 & 8) != 0) { return mapEntry_; } else { return MapEntryDefaultValue; } } + set { + _hasBits0 |= 8; + mapEntry_ = value; + } + } + /// Gets whether the "map_entry" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasMapEntry { + get { return (_hasBits0 & 8) != 0; } + } + /// Clears the value of the "map_entry" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearMapEntry() { + _hasBits0 &= ~8; + } + + /// Field number for the "uninterpreted_option" field. + public const int UninterpretedOptionFieldNumber = 999; + private static readonly pb::FieldCodec _repeated_uninterpretedOption_codec + = pb::FieldCodec.ForMessage(7994, global::Google.Protobuf.Reflection.UninterpretedOption.Parser); + private readonly pbc::RepeatedField uninterpretedOption_ = new pbc::RepeatedField(); + /// + /// The parser stores options it doesn't recognize here. See above. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField UninterpretedOption { + get { return uninterpretedOption_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as MessageOptions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(MessageOptions other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (MessageSetWireFormat != other.MessageSetWireFormat) return false; + if (NoStandardDescriptorAccessor != other.NoStandardDescriptorAccessor) return false; + if (Deprecated != other.Deprecated) return false; + if (MapEntry != other.MapEntry) return false; + if(!uninterpretedOption_.Equals(other.uninterpretedOption_)) return false; + if (!Equals(_extensions, other._extensions)) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasMessageSetWireFormat) hash ^= MessageSetWireFormat.GetHashCode(); + if (HasNoStandardDescriptorAccessor) hash ^= NoStandardDescriptorAccessor.GetHashCode(); + if (HasDeprecated) hash ^= Deprecated.GetHashCode(); + if (HasMapEntry) hash ^= MapEntry.GetHashCode(); + hash ^= uninterpretedOption_.GetHashCode(); + if (_extensions != null) { + hash ^= _extensions.GetHashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasMessageSetWireFormat) { + output.WriteRawTag(8); + output.WriteBool(MessageSetWireFormat); + } + if (HasNoStandardDescriptorAccessor) { + output.WriteRawTag(16); + output.WriteBool(NoStandardDescriptorAccessor); + } + if (HasDeprecated) { + output.WriteRawTag(24); + output.WriteBool(Deprecated); + } + if (HasMapEntry) { + output.WriteRawTag(56); + output.WriteBool(MapEntry); + } + uninterpretedOption_.WriteTo(output, _repeated_uninterpretedOption_codec); + if (_extensions != null) { + _extensions.WriteTo(output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasMessageSetWireFormat) { + output.WriteRawTag(8); + output.WriteBool(MessageSetWireFormat); + } + if (HasNoStandardDescriptorAccessor) { + output.WriteRawTag(16); + output.WriteBool(NoStandardDescriptorAccessor); + } + if (HasDeprecated) { + output.WriteRawTag(24); + output.WriteBool(Deprecated); + } + if (HasMapEntry) { + output.WriteRawTag(56); + output.WriteBool(MapEntry); + } + uninterpretedOption_.WriteTo(ref output, _repeated_uninterpretedOption_codec); + if (_extensions != null) { + _extensions.WriteTo(ref output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasMessageSetWireFormat) { + size += 1 + 1; + } + if (HasNoStandardDescriptorAccessor) { + size += 1 + 1; + } + if (HasDeprecated) { + size += 1 + 1; + } + if (HasMapEntry) { + size += 1 + 1; + } + size += uninterpretedOption_.CalculateSize(_repeated_uninterpretedOption_codec); + if (_extensions != null) { + size += _extensions.CalculateSize(); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(MessageOptions other) { + if (other == null) { + return; + } + if (other.HasMessageSetWireFormat) { + MessageSetWireFormat = other.MessageSetWireFormat; + } + if (other.HasNoStandardDescriptorAccessor) { + NoStandardDescriptorAccessor = other.NoStandardDescriptorAccessor; + } + if (other.HasDeprecated) { + Deprecated = other.Deprecated; + } + if (other.HasMapEntry) { + MapEntry = other.MapEntry; + } + uninterpretedOption_.Add(other.uninterpretedOption_); + pb::ExtensionSet.MergeFrom(ref _extensions, other._extensions); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + } + break; + case 8: { + MessageSetWireFormat = input.ReadBool(); + break; + } + case 16: { + NoStandardDescriptorAccessor = input.ReadBool(); + break; + } + case 24: { + Deprecated = input.ReadBool(); + break; + } + case 56: { + MapEntry = input.ReadBool(); + break; + } + case 7994: { + uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + } + break; + case 8: { + MessageSetWireFormat = input.ReadBool(); + break; + } + case 16: { + NoStandardDescriptorAccessor = input.ReadBool(); + break; + } + case 24: { + Deprecated = input.ReadBool(); + break; + } + case 56: { + MapEntry = input.ReadBool(); + break; + } + case 7994: { + uninterpretedOption_.AddEntriesFrom(ref input, _repeated_uninterpretedOption_codec); + break; + } + } + } + } + #endif + + public TValue GetExtension(pb::Extension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetOrInitializeExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.GetOrInitialize(ref _extensions, extension); + } + public void SetExtension(pb::Extension extension, TValue value) { + pb::ExtensionSet.Set(ref _extensions, extension, value); + } + public bool HasExtension(pb::Extension extension) { + return pb::ExtensionSet.Has(ref _extensions, extension); + } + public void ClearExtension(pb::Extension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + public void ClearExtension(pb::RepeatedExtension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + + } + + public sealed partial class FieldOptions : pb::IExtendableMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new FieldOptions()); + private pb::UnknownFieldSet _unknownFields; + internal pb::ExtensionSet _extensions; + private pb::ExtensionSet _Extensions { get { return _extensions; } } + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[12]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FieldOptions() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FieldOptions(FieldOptions other) : this() { + _hasBits0 = other._hasBits0; + ctype_ = other.ctype_; + packed_ = other.packed_; + jstype_ = other.jstype_; + lazy_ = other.lazy_; + deprecated_ = other.deprecated_; + weak_ = other.weak_; + uninterpretedOption_ = other.uninterpretedOption_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + _extensions = pb::ExtensionSet.Clone(other._extensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FieldOptions Clone() { + return new FieldOptions(this); + } + + /// Field number for the "ctype" field. + public const int CtypeFieldNumber = 1; + private readonly static global::Google.Protobuf.Reflection.FieldOptions.Types.CType CtypeDefaultValue = global::Google.Protobuf.Reflection.FieldOptions.Types.CType.String; + + private global::Google.Protobuf.Reflection.FieldOptions.Types.CType ctype_; + /// + /// The ctype option instructs the C++ code generator to use a different + /// representation of the field than it normally would. See the specific + /// options below. This option is not yet implemented in the open source + /// release -- sorry, we'll try to include it in a future version! + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.Reflection.FieldOptions.Types.CType Ctype { + get { if ((_hasBits0 & 1) != 0) { return ctype_; } else { return CtypeDefaultValue; } } + set { + _hasBits0 |= 1; + ctype_ = value; + } + } + /// Gets whether the "ctype" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasCtype { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "ctype" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearCtype() { + _hasBits0 &= ~1; + } + + /// Field number for the "packed" field. + public const int PackedFieldNumber = 2; + private readonly static bool PackedDefaultValue = false; + + private bool packed_; + /// + /// The packed option can be enabled for repeated primitive fields to enable + /// a more efficient representation on the wire. Rather than repeatedly + /// writing the tag and type for each element, the entire array is encoded as + /// a single length-delimited blob. In proto3, only explicit setting it to + /// false will avoid using packed encoding. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Packed { + get { if ((_hasBits0 & 2) != 0) { return packed_; } else { return PackedDefaultValue; } } + set { + _hasBits0 |= 2; + packed_ = value; + } + } + /// Gets whether the "packed" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasPacked { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "packed" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearPacked() { + _hasBits0 &= ~2; + } + + /// Field number for the "jstype" field. + public const int JstypeFieldNumber = 6; + private readonly static global::Google.Protobuf.Reflection.FieldOptions.Types.JSType JstypeDefaultValue = global::Google.Protobuf.Reflection.FieldOptions.Types.JSType.JsNormal; + + private global::Google.Protobuf.Reflection.FieldOptions.Types.JSType jstype_; + /// + /// The jstype option determines the JavaScript type used for values of the + /// field. The option is permitted only for 64 bit integral and fixed types + /// (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING + /// is represented as JavaScript string, which avoids loss of precision that + /// can happen when a large value is converted to a floating point JavaScript. + /// Specifying JS_NUMBER for the jstype causes the generated JavaScript code to + /// use the JavaScript "number" type. The behavior of the default option + /// JS_NORMAL is implementation dependent. + /// + /// This option is an enum to permit additional types to be added, e.g. + /// goog.math.Integer. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.Reflection.FieldOptions.Types.JSType Jstype { + get { if ((_hasBits0 & 16) != 0) { return jstype_; } else { return JstypeDefaultValue; } } + set { + _hasBits0 |= 16; + jstype_ = value; + } + } + /// Gets whether the "jstype" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasJstype { + get { return (_hasBits0 & 16) != 0; } + } + /// Clears the value of the "jstype" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearJstype() { + _hasBits0 &= ~16; + } + + /// Field number for the "lazy" field. + public const int LazyFieldNumber = 5; + private readonly static bool LazyDefaultValue = false; + + private bool lazy_; + /// + /// Should this field be parsed lazily? Lazy applies only to message-type + /// fields. It means that when the outer message is initially parsed, the + /// inner message's contents will not be parsed but instead stored in encoded + /// form. The inner message will actually be parsed when it is first accessed. + /// + /// This is only a hint. Implementations are free to choose whether to use + /// eager or lazy parsing regardless of the value of this option. However, + /// setting this option true suggests that the protocol author believes that + /// using lazy parsing on this field is worth the additional bookkeeping + /// overhead typically needed to implement it. + /// + /// This option does not affect the public interface of any generated code; + /// all method signatures remain the same. Furthermore, thread-safety of the + /// interface is not affected by this option; const methods remain safe to + /// call from multiple threads concurrently, while non-const methods continue + /// to require exclusive access. + /// + /// Note that implementations may choose not to check required fields within + /// a lazy sub-message. That is, calling IsInitialized() on the outer message + /// may return true even if the inner message has missing required fields. + /// This is necessary because otherwise the inner message would have to be + /// parsed in order to perform the check, defeating the purpose of lazy + /// parsing. An implementation which chooses not to check required fields + /// must be consistent about it. That is, for any particular sub-message, the + /// implementation must either *always* check its required fields, or *never* + /// check its required fields, regardless of whether or not the message has + /// been parsed. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Lazy { + get { if ((_hasBits0 & 8) != 0) { return lazy_; } else { return LazyDefaultValue; } } + set { + _hasBits0 |= 8; + lazy_ = value; + } + } + /// Gets whether the "lazy" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasLazy { + get { return (_hasBits0 & 8) != 0; } + } + /// Clears the value of the "lazy" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearLazy() { + _hasBits0 &= ~8; + } + + /// Field number for the "deprecated" field. + public const int DeprecatedFieldNumber = 3; + private readonly static bool DeprecatedDefaultValue = false; + + private bool deprecated_; + /// + /// Is this field deprecated? + /// Depending on the target platform, this can emit Deprecated annotations + /// for accessors, or it will be completely ignored; in the very least, this + /// is a formalization for deprecating fields. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Deprecated { + get { if ((_hasBits0 & 4) != 0) { return deprecated_; } else { return DeprecatedDefaultValue; } } + set { + _hasBits0 |= 4; + deprecated_ = value; + } + } + /// Gets whether the "deprecated" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDeprecated { + get { return (_hasBits0 & 4) != 0; } + } + /// Clears the value of the "deprecated" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDeprecated() { + _hasBits0 &= ~4; + } + + /// Field number for the "weak" field. + public const int WeakFieldNumber = 10; + private readonly static bool WeakDefaultValue = false; + + private bool weak_; + /// + /// For Google-internal migration only. Do not use. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Weak { + get { if ((_hasBits0 & 32) != 0) { return weak_; } else { return WeakDefaultValue; } } + set { + _hasBits0 |= 32; + weak_ = value; + } + } + /// Gets whether the "weak" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasWeak { + get { return (_hasBits0 & 32) != 0; } + } + /// Clears the value of the "weak" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearWeak() { + _hasBits0 &= ~32; + } + + /// Field number for the "uninterpreted_option" field. + public const int UninterpretedOptionFieldNumber = 999; + private static readonly pb::FieldCodec _repeated_uninterpretedOption_codec + = pb::FieldCodec.ForMessage(7994, global::Google.Protobuf.Reflection.UninterpretedOption.Parser); + private readonly pbc::RepeatedField uninterpretedOption_ = new pbc::RepeatedField(); + /// + /// The parser stores options it doesn't recognize here. See above. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField UninterpretedOption { + get { return uninterpretedOption_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as FieldOptions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(FieldOptions other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Ctype != other.Ctype) return false; + if (Packed != other.Packed) return false; + if (Jstype != other.Jstype) return false; + if (Lazy != other.Lazy) return false; + if (Deprecated != other.Deprecated) return false; + if (Weak != other.Weak) return false; + if(!uninterpretedOption_.Equals(other.uninterpretedOption_)) return false; + if (!Equals(_extensions, other._extensions)) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasCtype) hash ^= Ctype.GetHashCode(); + if (HasPacked) hash ^= Packed.GetHashCode(); + if (HasJstype) hash ^= Jstype.GetHashCode(); + if (HasLazy) hash ^= Lazy.GetHashCode(); + if (HasDeprecated) hash ^= Deprecated.GetHashCode(); + if (HasWeak) hash ^= Weak.GetHashCode(); + hash ^= uninterpretedOption_.GetHashCode(); + if (_extensions != null) { + hash ^= _extensions.GetHashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasCtype) { + output.WriteRawTag(8); + output.WriteEnum((int) Ctype); + } + if (HasPacked) { + output.WriteRawTag(16); + output.WriteBool(Packed); + } + if (HasDeprecated) { + output.WriteRawTag(24); + output.WriteBool(Deprecated); + } + if (HasLazy) { + output.WriteRawTag(40); + output.WriteBool(Lazy); + } + if (HasJstype) { + output.WriteRawTag(48); + output.WriteEnum((int) Jstype); + } + if (HasWeak) { + output.WriteRawTag(80); + output.WriteBool(Weak); + } + uninterpretedOption_.WriteTo(output, _repeated_uninterpretedOption_codec); + if (_extensions != null) { + _extensions.WriteTo(output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasCtype) { + output.WriteRawTag(8); + output.WriteEnum((int) Ctype); + } + if (HasPacked) { + output.WriteRawTag(16); + output.WriteBool(Packed); + } + if (HasDeprecated) { + output.WriteRawTag(24); + output.WriteBool(Deprecated); + } + if (HasLazy) { + output.WriteRawTag(40); + output.WriteBool(Lazy); + } + if (HasJstype) { + output.WriteRawTag(48); + output.WriteEnum((int) Jstype); + } + if (HasWeak) { + output.WriteRawTag(80); + output.WriteBool(Weak); + } + uninterpretedOption_.WriteTo(ref output, _repeated_uninterpretedOption_codec); + if (_extensions != null) { + _extensions.WriteTo(ref output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasCtype) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Ctype); + } + if (HasPacked) { + size += 1 + 1; + } + if (HasJstype) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Jstype); + } + if (HasLazy) { + size += 1 + 1; + } + if (HasDeprecated) { + size += 1 + 1; + } + if (HasWeak) { + size += 1 + 1; + } + size += uninterpretedOption_.CalculateSize(_repeated_uninterpretedOption_codec); + if (_extensions != null) { + size += _extensions.CalculateSize(); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(FieldOptions other) { + if (other == null) { + return; + } + if (other.HasCtype) { + Ctype = other.Ctype; + } + if (other.HasPacked) { + Packed = other.Packed; + } + if (other.HasJstype) { + Jstype = other.Jstype; + } + if (other.HasLazy) { + Lazy = other.Lazy; + } + if (other.HasDeprecated) { + Deprecated = other.Deprecated; + } + if (other.HasWeak) { + Weak = other.Weak; + } + uninterpretedOption_.Add(other.uninterpretedOption_); + pb::ExtensionSet.MergeFrom(ref _extensions, other._extensions); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + } + break; + case 8: { + Ctype = (global::Google.Protobuf.Reflection.FieldOptions.Types.CType) input.ReadEnum(); + break; + } + case 16: { + Packed = input.ReadBool(); + break; + } + case 24: { + Deprecated = input.ReadBool(); + break; + } + case 40: { + Lazy = input.ReadBool(); + break; + } + case 48: { + Jstype = (global::Google.Protobuf.Reflection.FieldOptions.Types.JSType) input.ReadEnum(); + break; + } + case 80: { + Weak = input.ReadBool(); + break; + } + case 7994: { + uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + } + break; + case 8: { + Ctype = (global::Google.Protobuf.Reflection.FieldOptions.Types.CType) input.ReadEnum(); + break; + } + case 16: { + Packed = input.ReadBool(); + break; + } + case 24: { + Deprecated = input.ReadBool(); + break; + } + case 40: { + Lazy = input.ReadBool(); + break; + } + case 48: { + Jstype = (global::Google.Protobuf.Reflection.FieldOptions.Types.JSType) input.ReadEnum(); + break; + } + case 80: { + Weak = input.ReadBool(); + break; + } + case 7994: { + uninterpretedOption_.AddEntriesFrom(ref input, _repeated_uninterpretedOption_codec); + break; + } + } + } + } + #endif + + public TValue GetExtension(pb::Extension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetOrInitializeExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.GetOrInitialize(ref _extensions, extension); + } + public void SetExtension(pb::Extension extension, TValue value) { + pb::ExtensionSet.Set(ref _extensions, extension, value); + } + public bool HasExtension(pb::Extension extension) { + return pb::ExtensionSet.Has(ref _extensions, extension); + } + public void ClearExtension(pb::Extension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + public void ClearExtension(pb::RepeatedExtension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + + #region Nested types + /// Container for nested types declared in the FieldOptions message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public enum CType { + /// + /// Default mode. + /// + [pbr::OriginalName("STRING")] String = 0, + [pbr::OriginalName("CORD")] Cord = 1, + [pbr::OriginalName("STRING_PIECE")] StringPiece = 2, + } + + public enum JSType { + /// + /// Use the default type. + /// + [pbr::OriginalName("JS_NORMAL")] JsNormal = 0, + /// + /// Use JavaScript strings. + /// + [pbr::OriginalName("JS_STRING")] JsString = 1, + /// + /// Use JavaScript numbers. + /// + [pbr::OriginalName("JS_NUMBER")] JsNumber = 2, + } + + } + #endregion + + } + + public sealed partial class OneofOptions : pb::IExtendableMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new OneofOptions()); + private pb::UnknownFieldSet _unknownFields; + internal pb::ExtensionSet _extensions; + private pb::ExtensionSet _Extensions { get { return _extensions; } } + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[13]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneofOptions() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneofOptions(OneofOptions other) : this() { + uninterpretedOption_ = other.uninterpretedOption_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + _extensions = pb::ExtensionSet.Clone(other._extensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneofOptions Clone() { + return new OneofOptions(this); + } + + /// Field number for the "uninterpreted_option" field. + public const int UninterpretedOptionFieldNumber = 999; + private static readonly pb::FieldCodec _repeated_uninterpretedOption_codec + = pb::FieldCodec.ForMessage(7994, global::Google.Protobuf.Reflection.UninterpretedOption.Parser); + private readonly pbc::RepeatedField uninterpretedOption_ = new pbc::RepeatedField(); + /// + /// The parser stores options it doesn't recognize here. See above. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField UninterpretedOption { + get { return uninterpretedOption_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as OneofOptions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(OneofOptions other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!uninterpretedOption_.Equals(other.uninterpretedOption_)) return false; + if (!Equals(_extensions, other._extensions)) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + hash ^= uninterpretedOption_.GetHashCode(); + if (_extensions != null) { + hash ^= _extensions.GetHashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + uninterpretedOption_.WriteTo(output, _repeated_uninterpretedOption_codec); + if (_extensions != null) { + _extensions.WriteTo(output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + uninterpretedOption_.WriteTo(ref output, _repeated_uninterpretedOption_codec); + if (_extensions != null) { + _extensions.WriteTo(ref output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + size += uninterpretedOption_.CalculateSize(_repeated_uninterpretedOption_codec); + if (_extensions != null) { + size += _extensions.CalculateSize(); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(OneofOptions other) { + if (other == null) { + return; + } + uninterpretedOption_.Add(other.uninterpretedOption_); + pb::ExtensionSet.MergeFrom(ref _extensions, other._extensions); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + } + break; + case 7994: { + uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + } + break; + case 7994: { + uninterpretedOption_.AddEntriesFrom(ref input, _repeated_uninterpretedOption_codec); + break; + } + } + } + } + #endif + + public TValue GetExtension(pb::Extension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetOrInitializeExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.GetOrInitialize(ref _extensions, extension); + } + public void SetExtension(pb::Extension extension, TValue value) { + pb::ExtensionSet.Set(ref _extensions, extension, value); + } + public bool HasExtension(pb::Extension extension) { + return pb::ExtensionSet.Has(ref _extensions, extension); + } + public void ClearExtension(pb::Extension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + public void ClearExtension(pb::RepeatedExtension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + + } + + public sealed partial class EnumOptions : pb::IExtendableMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new EnumOptions()); + private pb::UnknownFieldSet _unknownFields; + internal pb::ExtensionSet _extensions; + private pb::ExtensionSet _Extensions { get { return _extensions; } } + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[14]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public EnumOptions() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public EnumOptions(EnumOptions other) : this() { + _hasBits0 = other._hasBits0; + allowAlias_ = other.allowAlias_; + deprecated_ = other.deprecated_; + uninterpretedOption_ = other.uninterpretedOption_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + _extensions = pb::ExtensionSet.Clone(other._extensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public EnumOptions Clone() { + return new EnumOptions(this); + } + + /// Field number for the "allow_alias" field. + public const int AllowAliasFieldNumber = 2; + private readonly static bool AllowAliasDefaultValue = false; + + private bool allowAlias_; + /// + /// Set this option to true to allow mapping different tag names to the same + /// value. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool AllowAlias { + get { if ((_hasBits0 & 1) != 0) { return allowAlias_; } else { return AllowAliasDefaultValue; } } + set { + _hasBits0 |= 1; + allowAlias_ = value; + } + } + /// Gets whether the "allow_alias" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasAllowAlias { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "allow_alias" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearAllowAlias() { + _hasBits0 &= ~1; + } + + /// Field number for the "deprecated" field. + public const int DeprecatedFieldNumber = 3; + private readonly static bool DeprecatedDefaultValue = false; + + private bool deprecated_; + /// + /// Is this enum deprecated? + /// Depending on the target platform, this can emit Deprecated annotations + /// for the enum, or it will be completely ignored; in the very least, this + /// is a formalization for deprecating enums. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Deprecated { + get { if ((_hasBits0 & 2) != 0) { return deprecated_; } else { return DeprecatedDefaultValue; } } + set { + _hasBits0 |= 2; + deprecated_ = value; + } + } + /// Gets whether the "deprecated" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDeprecated { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "deprecated" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDeprecated() { + _hasBits0 &= ~2; + } + + /// Field number for the "uninterpreted_option" field. + public const int UninterpretedOptionFieldNumber = 999; + private static readonly pb::FieldCodec _repeated_uninterpretedOption_codec + = pb::FieldCodec.ForMessage(7994, global::Google.Protobuf.Reflection.UninterpretedOption.Parser); + private readonly pbc::RepeatedField uninterpretedOption_ = new pbc::RepeatedField(); + /// + /// The parser stores options it doesn't recognize here. See above. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField UninterpretedOption { + get { return uninterpretedOption_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as EnumOptions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(EnumOptions other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (AllowAlias != other.AllowAlias) return false; + if (Deprecated != other.Deprecated) return false; + if(!uninterpretedOption_.Equals(other.uninterpretedOption_)) return false; + if (!Equals(_extensions, other._extensions)) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasAllowAlias) hash ^= AllowAlias.GetHashCode(); + if (HasDeprecated) hash ^= Deprecated.GetHashCode(); + hash ^= uninterpretedOption_.GetHashCode(); + if (_extensions != null) { + hash ^= _extensions.GetHashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasAllowAlias) { + output.WriteRawTag(16); + output.WriteBool(AllowAlias); + } + if (HasDeprecated) { + output.WriteRawTag(24); + output.WriteBool(Deprecated); + } + uninterpretedOption_.WriteTo(output, _repeated_uninterpretedOption_codec); + if (_extensions != null) { + _extensions.WriteTo(output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasAllowAlias) { + output.WriteRawTag(16); + output.WriteBool(AllowAlias); + } + if (HasDeprecated) { + output.WriteRawTag(24); + output.WriteBool(Deprecated); + } + uninterpretedOption_.WriteTo(ref output, _repeated_uninterpretedOption_codec); + if (_extensions != null) { + _extensions.WriteTo(ref output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasAllowAlias) { + size += 1 + 1; + } + if (HasDeprecated) { + size += 1 + 1; + } + size += uninterpretedOption_.CalculateSize(_repeated_uninterpretedOption_codec); + if (_extensions != null) { + size += _extensions.CalculateSize(); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(EnumOptions other) { + if (other == null) { + return; + } + if (other.HasAllowAlias) { + AllowAlias = other.AllowAlias; + } + if (other.HasDeprecated) { + Deprecated = other.Deprecated; + } + uninterpretedOption_.Add(other.uninterpretedOption_); + pb::ExtensionSet.MergeFrom(ref _extensions, other._extensions); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + } + break; + case 16: { + AllowAlias = input.ReadBool(); + break; + } + case 24: { + Deprecated = input.ReadBool(); + break; + } + case 7994: { + uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + } + break; + case 16: { + AllowAlias = input.ReadBool(); + break; + } + case 24: { + Deprecated = input.ReadBool(); + break; + } + case 7994: { + uninterpretedOption_.AddEntriesFrom(ref input, _repeated_uninterpretedOption_codec); + break; + } + } + } + } + #endif + + public TValue GetExtension(pb::Extension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetOrInitializeExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.GetOrInitialize(ref _extensions, extension); + } + public void SetExtension(pb::Extension extension, TValue value) { + pb::ExtensionSet.Set(ref _extensions, extension, value); + } + public bool HasExtension(pb::Extension extension) { + return pb::ExtensionSet.Has(ref _extensions, extension); + } + public void ClearExtension(pb::Extension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + public void ClearExtension(pb::RepeatedExtension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + + } + + public sealed partial class EnumValueOptions : pb::IExtendableMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new EnumValueOptions()); + private pb::UnknownFieldSet _unknownFields; + internal pb::ExtensionSet _extensions; + private pb::ExtensionSet _Extensions { get { return _extensions; } } + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[15]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public EnumValueOptions() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public EnumValueOptions(EnumValueOptions other) : this() { + _hasBits0 = other._hasBits0; + deprecated_ = other.deprecated_; + uninterpretedOption_ = other.uninterpretedOption_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + _extensions = pb::ExtensionSet.Clone(other._extensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public EnumValueOptions Clone() { + return new EnumValueOptions(this); + } + + /// Field number for the "deprecated" field. + public const int DeprecatedFieldNumber = 1; + private readonly static bool DeprecatedDefaultValue = false; + + private bool deprecated_; + /// + /// Is this enum value deprecated? + /// Depending on the target platform, this can emit Deprecated annotations + /// for the enum value, or it will be completely ignored; in the very least, + /// this is a formalization for deprecating enum values. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Deprecated { + get { if ((_hasBits0 & 1) != 0) { return deprecated_; } else { return DeprecatedDefaultValue; } } + set { + _hasBits0 |= 1; + deprecated_ = value; + } + } + /// Gets whether the "deprecated" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDeprecated { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "deprecated" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDeprecated() { + _hasBits0 &= ~1; + } + + /// Field number for the "uninterpreted_option" field. + public const int UninterpretedOptionFieldNumber = 999; + private static readonly pb::FieldCodec _repeated_uninterpretedOption_codec + = pb::FieldCodec.ForMessage(7994, global::Google.Protobuf.Reflection.UninterpretedOption.Parser); + private readonly pbc::RepeatedField uninterpretedOption_ = new pbc::RepeatedField(); + /// + /// The parser stores options it doesn't recognize here. See above. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField UninterpretedOption { + get { return uninterpretedOption_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as EnumValueOptions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(EnumValueOptions other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Deprecated != other.Deprecated) return false; + if(!uninterpretedOption_.Equals(other.uninterpretedOption_)) return false; + if (!Equals(_extensions, other._extensions)) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasDeprecated) hash ^= Deprecated.GetHashCode(); + hash ^= uninterpretedOption_.GetHashCode(); + if (_extensions != null) { + hash ^= _extensions.GetHashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasDeprecated) { + output.WriteRawTag(8); + output.WriteBool(Deprecated); + } + uninterpretedOption_.WriteTo(output, _repeated_uninterpretedOption_codec); + if (_extensions != null) { + _extensions.WriteTo(output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasDeprecated) { + output.WriteRawTag(8); + output.WriteBool(Deprecated); + } + uninterpretedOption_.WriteTo(ref output, _repeated_uninterpretedOption_codec); + if (_extensions != null) { + _extensions.WriteTo(ref output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasDeprecated) { + size += 1 + 1; + } + size += uninterpretedOption_.CalculateSize(_repeated_uninterpretedOption_codec); + if (_extensions != null) { + size += _extensions.CalculateSize(); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(EnumValueOptions other) { + if (other == null) { + return; + } + if (other.HasDeprecated) { + Deprecated = other.Deprecated; + } + uninterpretedOption_.Add(other.uninterpretedOption_); + pb::ExtensionSet.MergeFrom(ref _extensions, other._extensions); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + } + break; + case 8: { + Deprecated = input.ReadBool(); + break; + } + case 7994: { + uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + } + break; + case 8: { + Deprecated = input.ReadBool(); + break; + } + case 7994: { + uninterpretedOption_.AddEntriesFrom(ref input, _repeated_uninterpretedOption_codec); + break; + } + } + } + } + #endif + + public TValue GetExtension(pb::Extension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetOrInitializeExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.GetOrInitialize(ref _extensions, extension); + } + public void SetExtension(pb::Extension extension, TValue value) { + pb::ExtensionSet.Set(ref _extensions, extension, value); + } + public bool HasExtension(pb::Extension extension) { + return pb::ExtensionSet.Has(ref _extensions, extension); + } + public void ClearExtension(pb::Extension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + public void ClearExtension(pb::RepeatedExtension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + + } + + public sealed partial class ServiceOptions : pb::IExtendableMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ServiceOptions()); + private pb::UnknownFieldSet _unknownFields; + internal pb::ExtensionSet _extensions; + private pb::ExtensionSet _Extensions { get { return _extensions; } } + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[16]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ServiceOptions() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ServiceOptions(ServiceOptions other) : this() { + _hasBits0 = other._hasBits0; + deprecated_ = other.deprecated_; + uninterpretedOption_ = other.uninterpretedOption_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + _extensions = pb::ExtensionSet.Clone(other._extensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ServiceOptions Clone() { + return new ServiceOptions(this); + } + + /// Field number for the "deprecated" field. + public const int DeprecatedFieldNumber = 33; + private readonly static bool DeprecatedDefaultValue = false; + + private bool deprecated_; + /// + /// Is this service deprecated? + /// Depending on the target platform, this can emit Deprecated annotations + /// for the service, or it will be completely ignored; in the very least, + /// this is a formalization for deprecating services. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Deprecated { + get { if ((_hasBits0 & 1) != 0) { return deprecated_; } else { return DeprecatedDefaultValue; } } + set { + _hasBits0 |= 1; + deprecated_ = value; + } + } + /// Gets whether the "deprecated" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDeprecated { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "deprecated" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDeprecated() { + _hasBits0 &= ~1; + } + + /// Field number for the "uninterpreted_option" field. + public const int UninterpretedOptionFieldNumber = 999; + private static readonly pb::FieldCodec _repeated_uninterpretedOption_codec + = pb::FieldCodec.ForMessage(7994, global::Google.Protobuf.Reflection.UninterpretedOption.Parser); + private readonly pbc::RepeatedField uninterpretedOption_ = new pbc::RepeatedField(); + /// + /// The parser stores options it doesn't recognize here. See above. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField UninterpretedOption { + get { return uninterpretedOption_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as ServiceOptions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(ServiceOptions other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Deprecated != other.Deprecated) return false; + if(!uninterpretedOption_.Equals(other.uninterpretedOption_)) return false; + if (!Equals(_extensions, other._extensions)) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasDeprecated) hash ^= Deprecated.GetHashCode(); + hash ^= uninterpretedOption_.GetHashCode(); + if (_extensions != null) { + hash ^= _extensions.GetHashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasDeprecated) { + output.WriteRawTag(136, 2); + output.WriteBool(Deprecated); + } + uninterpretedOption_.WriteTo(output, _repeated_uninterpretedOption_codec); + if (_extensions != null) { + _extensions.WriteTo(output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasDeprecated) { + output.WriteRawTag(136, 2); + output.WriteBool(Deprecated); + } + uninterpretedOption_.WriteTo(ref output, _repeated_uninterpretedOption_codec); + if (_extensions != null) { + _extensions.WriteTo(ref output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasDeprecated) { + size += 2 + 1; + } + size += uninterpretedOption_.CalculateSize(_repeated_uninterpretedOption_codec); + if (_extensions != null) { + size += _extensions.CalculateSize(); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(ServiceOptions other) { + if (other == null) { + return; + } + if (other.HasDeprecated) { + Deprecated = other.Deprecated; + } + uninterpretedOption_.Add(other.uninterpretedOption_); + pb::ExtensionSet.MergeFrom(ref _extensions, other._extensions); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + } + break; + case 264: { + Deprecated = input.ReadBool(); + break; + } + case 7994: { + uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + } + break; + case 264: { + Deprecated = input.ReadBool(); + break; + } + case 7994: { + uninterpretedOption_.AddEntriesFrom(ref input, _repeated_uninterpretedOption_codec); + break; + } + } + } + } + #endif + + public TValue GetExtension(pb::Extension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetOrInitializeExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.GetOrInitialize(ref _extensions, extension); + } + public void SetExtension(pb::Extension extension, TValue value) { + pb::ExtensionSet.Set(ref _extensions, extension, value); + } + public bool HasExtension(pb::Extension extension) { + return pb::ExtensionSet.Has(ref _extensions, extension); + } + public void ClearExtension(pb::Extension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + public void ClearExtension(pb::RepeatedExtension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + + } + + public sealed partial class MethodOptions : pb::IExtendableMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new MethodOptions()); + private pb::UnknownFieldSet _unknownFields; + internal pb::ExtensionSet _extensions; + private pb::ExtensionSet _Extensions { get { return _extensions; } } + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[17]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MethodOptions() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MethodOptions(MethodOptions other) : this() { + _hasBits0 = other._hasBits0; + deprecated_ = other.deprecated_; + idempotencyLevel_ = other.idempotencyLevel_; + uninterpretedOption_ = other.uninterpretedOption_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + _extensions = pb::ExtensionSet.Clone(other._extensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MethodOptions Clone() { + return new MethodOptions(this); + } + + /// Field number for the "deprecated" field. + public const int DeprecatedFieldNumber = 33; + private readonly static bool DeprecatedDefaultValue = false; + + private bool deprecated_; + /// + /// Is this method deprecated? + /// Depending on the target platform, this can emit Deprecated annotations + /// for the method, or it will be completely ignored; in the very least, + /// this is a formalization for deprecating methods. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Deprecated { + get { if ((_hasBits0 & 1) != 0) { return deprecated_; } else { return DeprecatedDefaultValue; } } + set { + _hasBits0 |= 1; + deprecated_ = value; + } + } + /// Gets whether the "deprecated" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDeprecated { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "deprecated" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDeprecated() { + _hasBits0 &= ~1; + } + + /// Field number for the "idempotency_level" field. + public const int IdempotencyLevelFieldNumber = 34; + private readonly static global::Google.Protobuf.Reflection.MethodOptions.Types.IdempotencyLevel IdempotencyLevelDefaultValue = global::Google.Protobuf.Reflection.MethodOptions.Types.IdempotencyLevel.IdempotencyUnknown; + + private global::Google.Protobuf.Reflection.MethodOptions.Types.IdempotencyLevel idempotencyLevel_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.Reflection.MethodOptions.Types.IdempotencyLevel IdempotencyLevel { + get { if ((_hasBits0 & 2) != 0) { return idempotencyLevel_; } else { return IdempotencyLevelDefaultValue; } } + set { + _hasBits0 |= 2; + idempotencyLevel_ = value; + } + } + /// Gets whether the "idempotency_level" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasIdempotencyLevel { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "idempotency_level" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearIdempotencyLevel() { + _hasBits0 &= ~2; + } + + /// Field number for the "uninterpreted_option" field. + public const int UninterpretedOptionFieldNumber = 999; + private static readonly pb::FieldCodec _repeated_uninterpretedOption_codec + = pb::FieldCodec.ForMessage(7994, global::Google.Protobuf.Reflection.UninterpretedOption.Parser); + private readonly pbc::RepeatedField uninterpretedOption_ = new pbc::RepeatedField(); + /// + /// The parser stores options it doesn't recognize here. See above. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField UninterpretedOption { + get { return uninterpretedOption_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as MethodOptions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(MethodOptions other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Deprecated != other.Deprecated) return false; + if (IdempotencyLevel != other.IdempotencyLevel) return false; + if(!uninterpretedOption_.Equals(other.uninterpretedOption_)) return false; + if (!Equals(_extensions, other._extensions)) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasDeprecated) hash ^= Deprecated.GetHashCode(); + if (HasIdempotencyLevel) hash ^= IdempotencyLevel.GetHashCode(); + hash ^= uninterpretedOption_.GetHashCode(); + if (_extensions != null) { + hash ^= _extensions.GetHashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasDeprecated) { + output.WriteRawTag(136, 2); + output.WriteBool(Deprecated); + } + if (HasIdempotencyLevel) { + output.WriteRawTag(144, 2); + output.WriteEnum((int) IdempotencyLevel); + } + uninterpretedOption_.WriteTo(output, _repeated_uninterpretedOption_codec); + if (_extensions != null) { + _extensions.WriteTo(output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasDeprecated) { + output.WriteRawTag(136, 2); + output.WriteBool(Deprecated); + } + if (HasIdempotencyLevel) { + output.WriteRawTag(144, 2); + output.WriteEnum((int) IdempotencyLevel); + } + uninterpretedOption_.WriteTo(ref output, _repeated_uninterpretedOption_codec); + if (_extensions != null) { + _extensions.WriteTo(ref output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasDeprecated) { + size += 2 + 1; + } + if (HasIdempotencyLevel) { + size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) IdempotencyLevel); + } + size += uninterpretedOption_.CalculateSize(_repeated_uninterpretedOption_codec); + if (_extensions != null) { + size += _extensions.CalculateSize(); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(MethodOptions other) { + if (other == null) { + return; + } + if (other.HasDeprecated) { + Deprecated = other.Deprecated; + } + if (other.HasIdempotencyLevel) { + IdempotencyLevel = other.IdempotencyLevel; + } + uninterpretedOption_.Add(other.uninterpretedOption_); + pb::ExtensionSet.MergeFrom(ref _extensions, other._extensions); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + } + break; + case 264: { + Deprecated = input.ReadBool(); + break; + } + case 272: { + IdempotencyLevel = (global::Google.Protobuf.Reflection.MethodOptions.Types.IdempotencyLevel) input.ReadEnum(); + break; + } + case 7994: { + uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + } + break; + case 264: { + Deprecated = input.ReadBool(); + break; + } + case 272: { + IdempotencyLevel = (global::Google.Protobuf.Reflection.MethodOptions.Types.IdempotencyLevel) input.ReadEnum(); + break; + } + case 7994: { + uninterpretedOption_.AddEntriesFrom(ref input, _repeated_uninterpretedOption_codec); + break; + } + } + } + } + #endif + + public TValue GetExtension(pb::Extension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetOrInitializeExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.GetOrInitialize(ref _extensions, extension); + } + public void SetExtension(pb::Extension extension, TValue value) { + pb::ExtensionSet.Set(ref _extensions, extension, value); + } + public bool HasExtension(pb::Extension extension) { + return pb::ExtensionSet.Has(ref _extensions, extension); + } + public void ClearExtension(pb::Extension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + public void ClearExtension(pb::RepeatedExtension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + + #region Nested types + /// Container for nested types declared in the MethodOptions message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + /// + /// Is this method side-effect-free (or safe in HTTP parlance), or idempotent, + /// or neither? HTTP based RPC implementation may choose GET verb for safe + /// methods, and PUT verb for idempotent methods instead of the default POST. + /// + public enum IdempotencyLevel { + [pbr::OriginalName("IDEMPOTENCY_UNKNOWN")] IdempotencyUnknown = 0, + /// + /// implies idempotent + /// + [pbr::OriginalName("NO_SIDE_EFFECTS")] NoSideEffects = 1, + /// + /// idempotent, but may have side effects + /// + [pbr::OriginalName("IDEMPOTENT")] Idempotent = 2, + } + + } + #endregion + + } + + /// + /// A message representing a option the parser does not recognize. This only + /// appears in options protos created by the compiler::Parser class. + /// DescriptorPool resolves these when building Descriptor objects. Therefore, + /// options protos in descriptor objects (e.g. returned by Descriptor::options(), + /// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions + /// in them. + /// + public sealed partial class UninterpretedOption : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new UninterpretedOption()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[18]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public UninterpretedOption() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public UninterpretedOption(UninterpretedOption other) : this() { + _hasBits0 = other._hasBits0; + name_ = other.name_.Clone(); + identifierValue_ = other.identifierValue_; + positiveIntValue_ = other.positiveIntValue_; + negativeIntValue_ = other.negativeIntValue_; + doubleValue_ = other.doubleValue_; + stringValue_ = other.stringValue_; + aggregateValue_ = other.aggregateValue_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public UninterpretedOption Clone() { + return new UninterpretedOption(this); + } + + /// Field number for the "name" field. + public const int NameFieldNumber = 2; + private static readonly pb::FieldCodec _repeated_name_codec + = pb::FieldCodec.ForMessage(18, global::Google.Protobuf.Reflection.UninterpretedOption.Types.NamePart.Parser); + private readonly pbc::RepeatedField name_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Name { + get { return name_; } + } + + /// Field number for the "identifier_value" field. + public const int IdentifierValueFieldNumber = 3; + private readonly static string IdentifierValueDefaultValue = ""; + + private string identifierValue_; + /// + /// The value of the uninterpreted option, in whatever type the tokenizer + /// identified it as during parsing. Exactly one of these should be set. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string IdentifierValue { + get { return identifierValue_ ?? IdentifierValueDefaultValue; } + set { + identifierValue_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "identifier_value" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasIdentifierValue { + get { return identifierValue_ != null; } + } + /// Clears the value of the "identifier_value" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearIdentifierValue() { + identifierValue_ = null; + } + + /// Field number for the "positive_int_value" field. + public const int PositiveIntValueFieldNumber = 4; + private readonly static ulong PositiveIntValueDefaultValue = 0UL; + + private ulong positiveIntValue_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ulong PositiveIntValue { + get { if ((_hasBits0 & 1) != 0) { return positiveIntValue_; } else { return PositiveIntValueDefaultValue; } } + set { + _hasBits0 |= 1; + positiveIntValue_ = value; + } + } + /// Gets whether the "positive_int_value" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasPositiveIntValue { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "positive_int_value" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearPositiveIntValue() { + _hasBits0 &= ~1; + } + + /// Field number for the "negative_int_value" field. + public const int NegativeIntValueFieldNumber = 5; + private readonly static long NegativeIntValueDefaultValue = 0L; + + private long negativeIntValue_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public long NegativeIntValue { + get { if ((_hasBits0 & 2) != 0) { return negativeIntValue_; } else { return NegativeIntValueDefaultValue; } } + set { + _hasBits0 |= 2; + negativeIntValue_ = value; + } + } + /// Gets whether the "negative_int_value" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasNegativeIntValue { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "negative_int_value" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearNegativeIntValue() { + _hasBits0 &= ~2; + } + + /// Field number for the "double_value" field. + public const int DoubleValueFieldNumber = 6; + private readonly static double DoubleValueDefaultValue = 0D; + + private double doubleValue_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public double DoubleValue { + get { if ((_hasBits0 & 4) != 0) { return doubleValue_; } else { return DoubleValueDefaultValue; } } + set { + _hasBits0 |= 4; + doubleValue_ = value; + } + } + /// Gets whether the "double_value" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasDoubleValue { + get { return (_hasBits0 & 4) != 0; } + } + /// Clears the value of the "double_value" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearDoubleValue() { + _hasBits0 &= ~4; + } + + /// Field number for the "string_value" field. + public const int StringValueFieldNumber = 7; + private readonly static pb::ByteString StringValueDefaultValue = pb::ByteString.Empty; + + private pb::ByteString stringValue_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pb::ByteString StringValue { + get { return stringValue_ ?? StringValueDefaultValue; } + set { + stringValue_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "string_value" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasStringValue { + get { return stringValue_ != null; } + } + /// Clears the value of the "string_value" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearStringValue() { + stringValue_ = null; + } + + /// Field number for the "aggregate_value" field. + public const int AggregateValueFieldNumber = 8; + private readonly static string AggregateValueDefaultValue = ""; + + private string aggregateValue_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string AggregateValue { + get { return aggregateValue_ ?? AggregateValueDefaultValue; } + set { + aggregateValue_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "aggregate_value" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasAggregateValue { + get { return aggregateValue_ != null; } + } + /// Clears the value of the "aggregate_value" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearAggregateValue() { + aggregateValue_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as UninterpretedOption); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(UninterpretedOption other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!name_.Equals(other.name_)) return false; + if (IdentifierValue != other.IdentifierValue) return false; + if (PositiveIntValue != other.PositiveIntValue) return false; + if (NegativeIntValue != other.NegativeIntValue) return false; + if (!pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.Equals(DoubleValue, other.DoubleValue)) return false; + if (StringValue != other.StringValue) return false; + if (AggregateValue != other.AggregateValue) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + hash ^= name_.GetHashCode(); + if (HasIdentifierValue) hash ^= IdentifierValue.GetHashCode(); + if (HasPositiveIntValue) hash ^= PositiveIntValue.GetHashCode(); + if (HasNegativeIntValue) hash ^= NegativeIntValue.GetHashCode(); + if (HasDoubleValue) hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(DoubleValue); + if (HasStringValue) hash ^= StringValue.GetHashCode(); + if (HasAggregateValue) hash ^= AggregateValue.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + name_.WriteTo(output, _repeated_name_codec); + if (HasIdentifierValue) { + output.WriteRawTag(26); + output.WriteString(IdentifierValue); + } + if (HasPositiveIntValue) { + output.WriteRawTag(32); + output.WriteUInt64(PositiveIntValue); + } + if (HasNegativeIntValue) { + output.WriteRawTag(40); + output.WriteInt64(NegativeIntValue); + } + if (HasDoubleValue) { + output.WriteRawTag(49); + output.WriteDouble(DoubleValue); + } + if (HasStringValue) { + output.WriteRawTag(58); + output.WriteBytes(StringValue); + } + if (HasAggregateValue) { + output.WriteRawTag(66); + output.WriteString(AggregateValue); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + name_.WriteTo(ref output, _repeated_name_codec); + if (HasIdentifierValue) { + output.WriteRawTag(26); + output.WriteString(IdentifierValue); + } + if (HasPositiveIntValue) { + output.WriteRawTag(32); + output.WriteUInt64(PositiveIntValue); + } + if (HasNegativeIntValue) { + output.WriteRawTag(40); + output.WriteInt64(NegativeIntValue); + } + if (HasDoubleValue) { + output.WriteRawTag(49); + output.WriteDouble(DoubleValue); + } + if (HasStringValue) { + output.WriteRawTag(58); + output.WriteBytes(StringValue); + } + if (HasAggregateValue) { + output.WriteRawTag(66); + output.WriteString(AggregateValue); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + size += name_.CalculateSize(_repeated_name_codec); + if (HasIdentifierValue) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(IdentifierValue); + } + if (HasPositiveIntValue) { + size += 1 + pb::CodedOutputStream.ComputeUInt64Size(PositiveIntValue); + } + if (HasNegativeIntValue) { + size += 1 + pb::CodedOutputStream.ComputeInt64Size(NegativeIntValue); + } + if (HasDoubleValue) { + size += 1 + 8; + } + if (HasStringValue) { + size += 1 + pb::CodedOutputStream.ComputeBytesSize(StringValue); + } + if (HasAggregateValue) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(AggregateValue); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(UninterpretedOption other) { + if (other == null) { + return; + } + name_.Add(other.name_); + if (other.HasIdentifierValue) { + IdentifierValue = other.IdentifierValue; + } + if (other.HasPositiveIntValue) { + PositiveIntValue = other.PositiveIntValue; + } + if (other.HasNegativeIntValue) { + NegativeIntValue = other.NegativeIntValue; + } + if (other.HasDoubleValue) { + DoubleValue = other.DoubleValue; + } + if (other.HasStringValue) { + StringValue = other.StringValue; + } + if (other.HasAggregateValue) { + AggregateValue = other.AggregateValue; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 18: { + name_.AddEntriesFrom(input, _repeated_name_codec); + break; + } + case 26: { + IdentifierValue = input.ReadString(); + break; + } + case 32: { + PositiveIntValue = input.ReadUInt64(); + break; + } + case 40: { + NegativeIntValue = input.ReadInt64(); + break; + } + case 49: { + DoubleValue = input.ReadDouble(); + break; + } + case 58: { + StringValue = input.ReadBytes(); + break; + } + case 66: { + AggregateValue = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 18: { + name_.AddEntriesFrom(ref input, _repeated_name_codec); + break; + } + case 26: { + IdentifierValue = input.ReadString(); + break; + } + case 32: { + PositiveIntValue = input.ReadUInt64(); + break; + } + case 40: { + NegativeIntValue = input.ReadInt64(); + break; + } + case 49: { + DoubleValue = input.ReadDouble(); + break; + } + case 58: { + StringValue = input.ReadBytes(); + break; + } + case 66: { + AggregateValue = input.ReadString(); + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the UninterpretedOption message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + /// + /// The name of the uninterpreted option. Each string represents a segment in + /// a dot-separated name. is_extension is true iff a segment represents an + /// extension (denoted with parentheses in options specs in .proto files). + /// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents + /// "foo.(bar.baz).qux". + /// + public sealed partial class NamePart : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new NamePart()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.UninterpretedOption.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NamePart() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NamePart(NamePart other) : this() { + _hasBits0 = other._hasBits0; + namePart_ = other.namePart_; + isExtension_ = other.isExtension_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NamePart Clone() { + return new NamePart(this); + } + + /// Field number for the "name_part" field. + public const int NamePart_FieldNumber = 1; + private readonly static string NamePart_DefaultValue = ""; + + private string namePart_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string NamePart_ { + get { return namePart_ ?? NamePart_DefaultValue; } + set { + namePart_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "name_part" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasNamePart_ { + get { return namePart_ != null; } + } + /// Clears the value of the "name_part" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearNamePart_() { + namePart_ = null; + } + + /// Field number for the "is_extension" field. + public const int IsExtensionFieldNumber = 2; + private readonly static bool IsExtensionDefaultValue = false; + + private bool isExtension_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool IsExtension { + get { if ((_hasBits0 & 1) != 0) { return isExtension_; } else { return IsExtensionDefaultValue; } } + set { + _hasBits0 |= 1; + isExtension_ = value; + } + } + /// Gets whether the "is_extension" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasIsExtension { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "is_extension" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearIsExtension() { + _hasBits0 &= ~1; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as NamePart); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(NamePart other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (NamePart_ != other.NamePart_) return false; + if (IsExtension != other.IsExtension) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasNamePart_) hash ^= NamePart_.GetHashCode(); + if (HasIsExtension) hash ^= IsExtension.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasNamePart_) { + output.WriteRawTag(10); + output.WriteString(NamePart_); + } + if (HasIsExtension) { + output.WriteRawTag(16); + output.WriteBool(IsExtension); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasNamePart_) { + output.WriteRawTag(10); + output.WriteString(NamePart_); + } + if (HasIsExtension) { + output.WriteRawTag(16); + output.WriteBool(IsExtension); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasNamePart_) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(NamePart_); + } + if (HasIsExtension) { + size += 1 + 1; + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(NamePart other) { + if (other == null) { + return; + } + if (other.HasNamePart_) { + NamePart_ = other.NamePart_; + } + if (other.HasIsExtension) { + IsExtension = other.IsExtension; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + NamePart_ = input.ReadString(); + break; + } + case 16: { + IsExtension = input.ReadBool(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + NamePart_ = input.ReadString(); + break; + } + case 16: { + IsExtension = input.ReadBool(); + break; + } + } + } + } + #endif + + } + + } + #endregion + + } + + /// + /// Encapsulates information about the original source file from which a + /// FileDescriptorProto was generated. + /// + public sealed partial class SourceCodeInfo : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new SourceCodeInfo()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[19]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public SourceCodeInfo() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public SourceCodeInfo(SourceCodeInfo other) : this() { + location_ = other.location_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public SourceCodeInfo Clone() { + return new SourceCodeInfo(this); + } + + /// Field number for the "location" field. + public const int LocationFieldNumber = 1; + private static readonly pb::FieldCodec _repeated_location_codec + = pb::FieldCodec.ForMessage(10, global::Google.Protobuf.Reflection.SourceCodeInfo.Types.Location.Parser); + private readonly pbc::RepeatedField location_ = new pbc::RepeatedField(); + /// + /// A Location identifies a piece of source code in a .proto file which + /// corresponds to a particular definition. This information is intended + /// to be useful to IDEs, code indexers, documentation generators, and similar + /// tools. + /// + /// For example, say we have a file like: + /// message Foo { + /// optional string foo = 1; + /// } + /// Let's look at just the field definition: + /// optional string foo = 1; + /// ^ ^^ ^^ ^ ^^^ + /// a bc de f ghi + /// We have the following locations: + /// span path represents + /// [a,i) [ 4, 0, 2, 0 ] The whole field definition. + /// [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). + /// [c,d) [ 4, 0, 2, 0, 5 ] The type (string). + /// [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). + /// [g,h) [ 4, 0, 2, 0, 3 ] The number (1). + /// + /// Notes: + /// - A location may refer to a repeated field itself (i.e. not to any + /// particular index within it). This is used whenever a set of elements are + /// logically enclosed in a single code segment. For example, an entire + /// extend block (possibly containing multiple extension definitions) will + /// have an outer location whose path refers to the "extensions" repeated + /// field without an index. + /// - Multiple locations may have the same path. This happens when a single + /// logical declaration is spread out across multiple places. The most + /// obvious example is the "extend" block again -- there may be multiple + /// extend blocks in the same scope, each of which will have the same path. + /// - A location's span is not always a subset of its parent's span. For + /// example, the "extendee" of an extension declaration appears at the + /// beginning of the "extend" block and is shared by all extensions within + /// the block. + /// - Just because a location's span is a subset of some other location's span + /// does not mean that it is a descendant. For example, a "group" defines + /// both a type and a field in a single declaration. Thus, the locations + /// corresponding to the type and field and their components will overlap. + /// - Code which tries to interpret locations should probably be designed to + /// ignore those that it doesn't understand, as more types of locations could + /// be recorded in the future. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Location { + get { return location_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as SourceCodeInfo); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(SourceCodeInfo other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!location_.Equals(other.location_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + hash ^= location_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + location_.WriteTo(output, _repeated_location_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + location_.WriteTo(ref output, _repeated_location_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + size += location_.CalculateSize(_repeated_location_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(SourceCodeInfo other) { + if (other == null) { + return; + } + location_.Add(other.location_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + location_.AddEntriesFrom(input, _repeated_location_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + location_.AddEntriesFrom(ref input, _repeated_location_codec); + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the SourceCodeInfo message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public sealed partial class Location : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Location()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.SourceCodeInfo.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Location() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Location(Location other) : this() { + path_ = other.path_.Clone(); + span_ = other.span_.Clone(); + leadingComments_ = other.leadingComments_; + trailingComments_ = other.trailingComments_; + leadingDetachedComments_ = other.leadingDetachedComments_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Location Clone() { + return new Location(this); + } + + /// Field number for the "path" field. + public const int PathFieldNumber = 1; + private static readonly pb::FieldCodec _repeated_path_codec + = pb::FieldCodec.ForInt32(10); + private readonly pbc::RepeatedField path_ = new pbc::RepeatedField(); + /// + /// Identifies which part of the FileDescriptorProto was defined at this + /// location. + /// + /// Each element is a field number or an index. They form a path from + /// the root FileDescriptorProto to the place where the definition occurs. For + /// example, this path: + /// [ 4, 3, 2, 7, 1 ] + /// refers to: + /// file.message_type(3) // 4, 3 + /// .field(7) // 2, 7 + /// .name() // 1 + /// This is because FileDescriptorProto.message_type has field number 4: + /// repeated DescriptorProto message_type = 4; + /// and DescriptorProto.field has field number 2: + /// repeated FieldDescriptorProto field = 2; + /// and FieldDescriptorProto.name has field number 1: + /// optional string name = 1; + /// + /// Thus, the above path gives the location of a field name. If we removed + /// the last element: + /// [ 4, 3, 2, 7 ] + /// this path refers to the whole field declaration (from the beginning + /// of the label to the terminating semicolon). + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Path { + get { return path_; } + } + + /// Field number for the "span" field. + public const int SpanFieldNumber = 2; + private static readonly pb::FieldCodec _repeated_span_codec + = pb::FieldCodec.ForInt32(18); + private readonly pbc::RepeatedField span_ = new pbc::RepeatedField(); + /// + /// Always has exactly three or four elements: start line, start column, + /// end line (optional, otherwise assumed same as start line), end column. + /// These are packed into a single field for efficiency. Note that line + /// and column numbers are zero-based -- typically you will want to add + /// 1 to each before displaying to a user. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Span { + get { return span_; } + } + + /// Field number for the "leading_comments" field. + public const int LeadingCommentsFieldNumber = 3; + private readonly static string LeadingCommentsDefaultValue = ""; + + private string leadingComments_; + /// + /// If this SourceCodeInfo represents a complete declaration, these are any + /// comments appearing before and after the declaration which appear to be + /// attached to the declaration. + /// + /// A series of line comments appearing on consecutive lines, with no other + /// tokens appearing on those lines, will be treated as a single comment. + /// + /// leading_detached_comments will keep paragraphs of comments that appear + /// before (but not connected to) the current element. Each paragraph, + /// separated by empty lines, will be one comment element in the repeated + /// field. + /// + /// Only the comment content is provided; comment markers (e.g. //) are + /// stripped out. For block comments, leading whitespace and an asterisk + /// will be stripped from the beginning of each line other than the first. + /// Newlines are included in the output. + /// + /// Examples: + /// + /// optional int32 foo = 1; // Comment attached to foo. + /// // Comment attached to bar. + /// optional int32 bar = 2; + /// + /// optional string baz = 3; + /// // Comment attached to baz. + /// // Another line attached to baz. + /// + /// // Comment attached to qux. + /// // + /// // Another line attached to qux. + /// optional double qux = 4; + /// + /// // Detached comment for corge. This is not leading or trailing comments + /// // to qux or corge because there are blank lines separating it from + /// // both. + /// + /// // Detached comment for corge paragraph 2. + /// + /// optional string corge = 5; + /// /* Block comment attached + /// * to corge. Leading asterisks + /// * will be removed. */ + /// /* Block comment attached to + /// * grault. */ + /// optional int32 grault = 6; + /// + /// // ignored detached comments. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string LeadingComments { + get { return leadingComments_ ?? LeadingCommentsDefaultValue; } + set { + leadingComments_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "leading_comments" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasLeadingComments { + get { return leadingComments_ != null; } + } + /// Clears the value of the "leading_comments" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearLeadingComments() { + leadingComments_ = null; + } + + /// Field number for the "trailing_comments" field. + public const int TrailingCommentsFieldNumber = 4; + private readonly static string TrailingCommentsDefaultValue = ""; + + private string trailingComments_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string TrailingComments { + get { return trailingComments_ ?? TrailingCommentsDefaultValue; } + set { + trailingComments_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "trailing_comments" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasTrailingComments { + get { return trailingComments_ != null; } + } + /// Clears the value of the "trailing_comments" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearTrailingComments() { + trailingComments_ = null; + } + + /// Field number for the "leading_detached_comments" field. + public const int LeadingDetachedCommentsFieldNumber = 6; + private static readonly pb::FieldCodec _repeated_leadingDetachedComments_codec + = pb::FieldCodec.ForString(50); + private readonly pbc::RepeatedField leadingDetachedComments_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField LeadingDetachedComments { + get { return leadingDetachedComments_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as Location); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(Location other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!path_.Equals(other.path_)) return false; + if(!span_.Equals(other.span_)) return false; + if (LeadingComments != other.LeadingComments) return false; + if (TrailingComments != other.TrailingComments) return false; + if(!leadingDetachedComments_.Equals(other.leadingDetachedComments_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + hash ^= path_.GetHashCode(); + hash ^= span_.GetHashCode(); + if (HasLeadingComments) hash ^= LeadingComments.GetHashCode(); + if (HasTrailingComments) hash ^= TrailingComments.GetHashCode(); + hash ^= leadingDetachedComments_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + path_.WriteTo(output, _repeated_path_codec); + span_.WriteTo(output, _repeated_span_codec); + if (HasLeadingComments) { + output.WriteRawTag(26); + output.WriteString(LeadingComments); + } + if (HasTrailingComments) { + output.WriteRawTag(34); + output.WriteString(TrailingComments); + } + leadingDetachedComments_.WriteTo(output, _repeated_leadingDetachedComments_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + path_.WriteTo(ref output, _repeated_path_codec); + span_.WriteTo(ref output, _repeated_span_codec); + if (HasLeadingComments) { + output.WriteRawTag(26); + output.WriteString(LeadingComments); + } + if (HasTrailingComments) { + output.WriteRawTag(34); + output.WriteString(TrailingComments); + } + leadingDetachedComments_.WriteTo(ref output, _repeated_leadingDetachedComments_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + size += path_.CalculateSize(_repeated_path_codec); + size += span_.CalculateSize(_repeated_span_codec); + if (HasLeadingComments) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(LeadingComments); + } + if (HasTrailingComments) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(TrailingComments); + } + size += leadingDetachedComments_.CalculateSize(_repeated_leadingDetachedComments_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(Location other) { + if (other == null) { + return; + } + path_.Add(other.path_); + span_.Add(other.span_); + if (other.HasLeadingComments) { + LeadingComments = other.LeadingComments; + } + if (other.HasTrailingComments) { + TrailingComments = other.TrailingComments; + } + leadingDetachedComments_.Add(other.leadingDetachedComments_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: + case 8: { + path_.AddEntriesFrom(input, _repeated_path_codec); + break; + } + case 18: + case 16: { + span_.AddEntriesFrom(input, _repeated_span_codec); + break; + } + case 26: { + LeadingComments = input.ReadString(); + break; + } + case 34: { + TrailingComments = input.ReadString(); + break; + } + case 50: { + leadingDetachedComments_.AddEntriesFrom(input, _repeated_leadingDetachedComments_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: + case 8: { + path_.AddEntriesFrom(ref input, _repeated_path_codec); + break; + } + case 18: + case 16: { + span_.AddEntriesFrom(ref input, _repeated_span_codec); + break; + } + case 26: { + LeadingComments = input.ReadString(); + break; + } + case 34: { + TrailingComments = input.ReadString(); + break; + } + case 50: { + leadingDetachedComments_.AddEntriesFrom(ref input, _repeated_leadingDetachedComments_codec); + break; + } + } + } + } + #endif + + } + + } + #endregion + + } + + /// + /// Describes the relationship between generated code and its original source + /// file. A GeneratedCodeInfo message is associated with only one generated + /// source file, but may contain references to different source .proto files. + /// + public sealed partial class GeneratedCodeInfo : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new GeneratedCodeInfo()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor.MessageTypes[20]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public GeneratedCodeInfo() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public GeneratedCodeInfo(GeneratedCodeInfo other) : this() { + annotation_ = other.annotation_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public GeneratedCodeInfo Clone() { + return new GeneratedCodeInfo(this); + } + + /// Field number for the "annotation" field. + public const int AnnotationFieldNumber = 1; + private static readonly pb::FieldCodec _repeated_annotation_codec + = pb::FieldCodec.ForMessage(10, global::Google.Protobuf.Reflection.GeneratedCodeInfo.Types.Annotation.Parser); + private readonly pbc::RepeatedField annotation_ = new pbc::RepeatedField(); + /// + /// An Annotation connects some span of text in generated code to an element + /// of its generating .proto file. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Annotation { + get { return annotation_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as GeneratedCodeInfo); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(GeneratedCodeInfo other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!annotation_.Equals(other.annotation_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + hash ^= annotation_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + annotation_.WriteTo(output, _repeated_annotation_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + annotation_.WriteTo(ref output, _repeated_annotation_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + size += annotation_.CalculateSize(_repeated_annotation_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(GeneratedCodeInfo other) { + if (other == null) { + return; + } + annotation_.Add(other.annotation_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + annotation_.AddEntriesFrom(input, _repeated_annotation_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + annotation_.AddEntriesFrom(ref input, _repeated_annotation_codec); + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the GeneratedCodeInfo message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public sealed partial class Annotation : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Annotation()); + private pb::UnknownFieldSet _unknownFields; + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.GeneratedCodeInfo.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Annotation() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Annotation(Annotation other) : this() { + _hasBits0 = other._hasBits0; + path_ = other.path_.Clone(); + sourceFile_ = other.sourceFile_; + begin_ = other.begin_; + end_ = other.end_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Annotation Clone() { + return new Annotation(this); + } + + /// Field number for the "path" field. + public const int PathFieldNumber = 1; + private static readonly pb::FieldCodec _repeated_path_codec + = pb::FieldCodec.ForInt32(10); + private readonly pbc::RepeatedField path_ = new pbc::RepeatedField(); + /// + /// Identifies the element in the original source .proto file. This field + /// is formatted the same as SourceCodeInfo.Location.path. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Path { + get { return path_; } + } + + /// Field number for the "source_file" field. + public const int SourceFileFieldNumber = 2; + private readonly static string SourceFileDefaultValue = ""; + + private string sourceFile_; + /// + /// Identifies the filesystem path to the original source .proto. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string SourceFile { + get { return sourceFile_ ?? SourceFileDefaultValue; } + set { + sourceFile_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "source_file" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasSourceFile { + get { return sourceFile_ != null; } + } + /// Clears the value of the "source_file" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearSourceFile() { + sourceFile_ = null; + } + + /// Field number for the "begin" field. + public const int BeginFieldNumber = 3; + private readonly static int BeginDefaultValue = 0; + + private int begin_; + /// + /// Identifies the starting offset in bytes in the generated code + /// that relates to the identified object. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Begin { + get { if ((_hasBits0 & 1) != 0) { return begin_; } else { return BeginDefaultValue; } } + set { + _hasBits0 |= 1; + begin_ = value; + } + } + /// Gets whether the "begin" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasBegin { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "begin" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearBegin() { + _hasBits0 &= ~1; + } + + /// Field number for the "end" field. + public const int EndFieldNumber = 4; + private readonly static int EndDefaultValue = 0; + + private int end_; + /// + /// Identifies the ending offset in bytes in the generated code that + /// relates to the identified offset. The end offset should be one past + /// the last relevant byte (so the length of the text = end - begin). + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int End { + get { if ((_hasBits0 & 2) != 0) { return end_; } else { return EndDefaultValue; } } + set { + _hasBits0 |= 2; + end_ = value; + } + } + /// Gets whether the "end" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasEnd { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "end" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearEnd() { + _hasBits0 &= ~2; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as Annotation); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(Annotation other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!path_.Equals(other.path_)) return false; + if (SourceFile != other.SourceFile) return false; + if (Begin != other.Begin) return false; + if (End != other.End) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + hash ^= path_.GetHashCode(); + if (HasSourceFile) hash ^= SourceFile.GetHashCode(); + if (HasBegin) hash ^= Begin.GetHashCode(); + if (HasEnd) hash ^= End.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + path_.WriteTo(output, _repeated_path_codec); + if (HasSourceFile) { + output.WriteRawTag(18); + output.WriteString(SourceFile); + } + if (HasBegin) { + output.WriteRawTag(24); + output.WriteInt32(Begin); + } + if (HasEnd) { + output.WriteRawTag(32); + output.WriteInt32(End); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + path_.WriteTo(ref output, _repeated_path_codec); + if (HasSourceFile) { + output.WriteRawTag(18); + output.WriteString(SourceFile); + } + if (HasBegin) { + output.WriteRawTag(24); + output.WriteInt32(Begin); + } + if (HasEnd) { + output.WriteRawTag(32); + output.WriteInt32(End); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + size += path_.CalculateSize(_repeated_path_codec); + if (HasSourceFile) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(SourceFile); + } + if (HasBegin) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Begin); + } + if (HasEnd) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(End); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(Annotation other) { + if (other == null) { + return; + } + path_.Add(other.path_); + if (other.HasSourceFile) { + SourceFile = other.SourceFile; + } + if (other.HasBegin) { + Begin = other.Begin; + } + if (other.HasEnd) { + End = other.End; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: + case 8: { + path_.AddEntriesFrom(input, _repeated_path_codec); + break; + } + case 18: { + SourceFile = input.ReadString(); + break; + } + case 24: { + Begin = input.ReadInt32(); + break; + } + case 32: { + End = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: + case 8: { + path_.AddEntriesFrom(ref input, _repeated_path_codec); + break; + } + case 18: { + SourceFile = input.ReadString(); + break; + } + case 24: { + Begin = input.ReadInt32(); + break; + } + case 32: { + End = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + } + #endregion + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/DescriptorPool.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/DescriptorPool.cs new file mode 100644 index 0000000..93f2fa9 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/DescriptorPool.cs @@ -0,0 +1,334 @@ +#region Copyright notice and license +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Text; +using System.Text.RegularExpressions; + +namespace Google.Protobuf.Reflection +{ + /// + /// Contains lookup tables containing all the descriptors defined in a particular file. + /// + internal sealed class DescriptorPool + { + private readonly IDictionary descriptorsByName = + new Dictionary(); + + private readonly IDictionary, FieldDescriptor> fieldsByNumber = + new Dictionary, FieldDescriptor>(); + + private readonly IDictionary, EnumValueDescriptor> enumValuesByNumber = + new Dictionary, EnumValueDescriptor>(); + + private readonly HashSet dependencies; + + internal DescriptorPool(IEnumerable dependencyFiles) + { + dependencies = new HashSet(); + foreach (var dependencyFile in dependencyFiles) + { + dependencies.Add(dependencyFile); + ImportPublicDependencies(dependencyFile); + } + + foreach (FileDescriptor dependency in dependencyFiles) + { + AddPackage(dependency.Package, dependency); + } + } + + private void ImportPublicDependencies(FileDescriptor file) + { + foreach (FileDescriptor dependency in file.PublicDependencies) + { + if (dependencies.Add(dependency)) + { + ImportPublicDependencies(dependency); + } + } + } + + /// + /// Finds a symbol of the given name within the pool. + /// + /// The type of symbol to look for + /// Fully-qualified name to look up + /// The symbol with the given name and type, + /// or null if the symbol doesn't exist or has the wrong type + internal T FindSymbol(string fullName) where T : class + { + IDescriptor result; + descriptorsByName.TryGetValue(fullName, out result); + T descriptor = result as T; + if (descriptor != null) + { + return descriptor; + } + + // dependencies contains direct dependencies and any *public* dependencies + // of those dependencies (transitively)... so we don't need to recurse here. + foreach (FileDescriptor dependency in dependencies) + { + dependency.DescriptorPool.descriptorsByName.TryGetValue(fullName, out result); + descriptor = result as T; + if (descriptor != null) + { + return descriptor; + } + } + + return null; + } + + /// + /// Adds a package to the symbol tables. If a package by the same name + /// already exists, that is fine, but if some other kind of symbol + /// exists under the same name, an exception is thrown. If the package + /// has multiple components, this also adds the parent package(s). + /// + internal void AddPackage(string fullName, FileDescriptor file) + { + int dotpos = fullName.LastIndexOf('.'); + String name; + if (dotpos != -1) + { + AddPackage(fullName.Substring(0, dotpos), file); + name = fullName.Substring(dotpos + 1); + } + else + { + name = fullName; + } + + IDescriptor old; + if (descriptorsByName.TryGetValue(fullName, out old)) + { + if (!(old is PackageDescriptor)) + { + throw new DescriptorValidationException(file, + "\"" + name + + "\" is already defined (as something other than a " + + "package) in file \"" + old.File.Name + "\"."); + } + } + descriptorsByName[fullName] = new PackageDescriptor(name, fullName, file); + } + + /// + /// Adds a symbol to the symbol table. + /// + /// The symbol already existed + /// in the symbol table. + internal void AddSymbol(IDescriptor descriptor) + { + ValidateSymbolName(descriptor); + String fullName = descriptor.FullName; + + IDescriptor old; + if (descriptorsByName.TryGetValue(fullName, out old)) + { + int dotPos = fullName.LastIndexOf('.'); + string message; + if (descriptor.File == old.File) + { + if (dotPos == -1) + { + message = "\"" + fullName + "\" is already defined."; + } + else + { + message = "\"" + fullName.Substring(dotPos + 1) + "\" is already defined in \"" + + fullName.Substring(0, dotPos) + "\"."; + } + } + else + { + message = "\"" + fullName + "\" is already defined in file \"" + old.File.Name + "\"."; + } + throw new DescriptorValidationException(descriptor, message); + } + descriptorsByName[fullName] = descriptor; + } + + private static readonly Regex ValidationRegex = new Regex("^[_A-Za-z][_A-Za-z0-9]*$", + FrameworkPortability.CompiledRegexWhereAvailable); + + /// + /// Verifies that the descriptor's name is valid (i.e. it contains + /// only letters, digits and underscores, and does not start with a digit). + /// + /// + private static void ValidateSymbolName(IDescriptor descriptor) + { + if (descriptor.Name == "") + { + throw new DescriptorValidationException(descriptor, "Missing name."); + } + if (!ValidationRegex.IsMatch(descriptor.Name)) + { + throw new DescriptorValidationException(descriptor, + "\"" + descriptor.Name + "\" is not a valid identifier."); + } + } + + /// + /// Returns the field with the given number in the given descriptor, + /// or null if it can't be found. + /// + internal FieldDescriptor FindFieldByNumber(MessageDescriptor messageDescriptor, int number) + { + FieldDescriptor ret; + fieldsByNumber.TryGetValue(new ObjectIntPair(messageDescriptor, number), out ret); + return ret; + } + + internal EnumValueDescriptor FindEnumValueByNumber(EnumDescriptor enumDescriptor, int number) + { + EnumValueDescriptor ret; + enumValuesByNumber.TryGetValue(new ObjectIntPair(enumDescriptor, number), out ret); + return ret; + } + + /// + /// Adds a field to the fieldsByNumber table. + /// + /// A field with the same + /// containing type and number already exists. + internal void AddFieldByNumber(FieldDescriptor field) + { + // for extensions, we use the extended type, otherwise we use the containing type + ObjectIntPair key = new ObjectIntPair(field.Proto.HasExtendee ? field.ExtendeeType : field.ContainingType, field.FieldNumber); + FieldDescriptor old; + if (fieldsByNumber.TryGetValue(key, out old)) + { + throw new DescriptorValidationException(field, "Field number " + field.FieldNumber + + "has already been used in \"" + + field.ContainingType.FullName + + "\" by field \"" + old.Name + "\"."); + } + fieldsByNumber[key] = field; + } + + /// + /// Adds an enum value to the enumValuesByNumber table. If an enum value + /// with the same type and number already exists, this method does nothing. + /// (This is allowed; the first value defined with the number takes precedence.) + /// + internal void AddEnumValueByNumber(EnumValueDescriptor enumValue) + { + ObjectIntPair key = new ObjectIntPair(enumValue.EnumDescriptor, enumValue.Number); + if (!enumValuesByNumber.ContainsKey(key)) + { + enumValuesByNumber[key] = enumValue; + } + } + + /// + /// Looks up a descriptor by name, relative to some other descriptor. + /// The name may be fully-qualified (with a leading '.'), partially-qualified, + /// or unqualified. C++-like name lookup semantics are used to search for the + /// matching descriptor. + /// + /// + /// This isn't heavily optimized, but it's only used during cross linking anyway. + /// If it starts being used more widely, we should look at performance more carefully. + /// + internal IDescriptor LookupSymbol(string name, IDescriptor relativeTo) + { + IDescriptor result; + if (name.StartsWith(".")) + { + // Fully-qualified name. + result = FindSymbol(name.Substring(1)); + } + else + { + // If "name" is a compound identifier, we want to search for the + // first component of it, then search within it for the rest. + int firstPartLength = name.IndexOf('.'); + string firstPart = firstPartLength == -1 ? name : name.Substring(0, firstPartLength); + + // We will search each parent scope of "relativeTo" looking for the + // symbol. + StringBuilder scopeToTry = new StringBuilder(relativeTo.FullName); + + while (true) + { + // Chop off the last component of the scope. + + int dotpos = scopeToTry.ToString().LastIndexOf("."); + if (dotpos == -1) + { + result = FindSymbol(name); + break; + } + else + { + scopeToTry.Length = dotpos + 1; + + // Append firstPart and try to find. + scopeToTry.Append(firstPart); + result = FindSymbol(scopeToTry.ToString()); + + if (result != null) + { + if (firstPartLength != -1) + { + // We only found the first part of the symbol. Now look for + // the whole thing. If this fails, we *don't* want to keep + // searching parent scopes. + scopeToTry.Length = dotpos + 1; + scopeToTry.Append(name); + result = FindSymbol(scopeToTry.ToString()); + } + break; + } + + // Not found. Remove the name so we can try again. + scopeToTry.Length = dotpos; + } + } + } + + if (result == null) + { + throw new DescriptorValidationException(relativeTo, "\"" + name + "\" is not defined."); + } + else + { + return result; + } + } + } +} \ No newline at end of file diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/ExtensionAccessor.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/ExtensionAccessor.cs new file mode 100644 index 0000000..81d6e35 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/ExtensionAccessor.cs @@ -0,0 +1,69 @@ +#region Copyright notice and license +// 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. +#endregion + +namespace Google.Protobuf.Reflection +{ + internal sealed class ExtensionAccessor : IFieldAccessor + { + private readonly Extension extension; + private readonly ReflectionUtil.IExtensionReflectionHelper helper; + + internal ExtensionAccessor(FieldDescriptor descriptor) + { + Descriptor = descriptor; + extension = descriptor.Extension; + helper = ReflectionUtil.CreateExtensionHelper(extension); + } + + public FieldDescriptor Descriptor { get; } + + public void Clear(IMessage message) + { + helper.ClearExtension(message); + } + + public bool HasValue(IMessage message) + { + return helper.HasExtension(message); + } + + public object GetValue(IMessage message) + { + return helper.GetExtension(message); + } + + public void SetValue(IMessage message, object value) + { + helper.SetExtension(message, value); + } + } +} diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/IDescriptor.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/IDescriptor.cs new file mode 100644 index 0000000..1c1ef38 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/IDescriptor.cs @@ -0,0 +1,55 @@ +#region Copyright notice and license +// 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. +#endregion + +namespace Google.Protobuf.Reflection +{ + /// + /// Interface implemented by all descriptor types. + /// + public interface IDescriptor + { + /// + /// Returns the name of the entity (message, field etc) being described. + /// + string Name { get; } + + /// + /// Returns the fully-qualified name of the entity being described. + /// + string FullName { get; } + + /// + /// Returns the descriptor for the .proto file that this entity is part of. + /// + FileDescriptor File { get; } + } +} \ No newline at end of file diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/IFieldAccessor.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/IFieldAccessor.cs new file mode 100644 index 0000000..d73427b --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/IFieldAccessor.cs @@ -0,0 +1,77 @@ +#region Copyright notice and license +// 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. +#endregion + +using System; +using System.Collections; + +namespace Google.Protobuf.Reflection +{ + /// + /// Allows fields to be reflectively accessed. + /// + public interface IFieldAccessor + { + /// + /// Returns the descriptor associated with this field. + /// + FieldDescriptor Descriptor { get; } + + /// + /// Clears the field in the specified message. (For repeated fields, + /// this clears the list.) + /// + void Clear(IMessage message); + + /// + /// Fetches the field value. For repeated values, this will be an + /// implementation. For map values, this will be an + /// implementation. + /// + object GetValue(IMessage message); + + /// + /// Indicates whether the field in the specified message is set. + /// For proto3 fields that aren't explicitly optional, this throws an + /// + bool HasValue(IMessage message); + + /// + /// Mutator for single "simple" fields only. + /// + /// + /// Repeated fields are mutated by fetching the value and manipulating it as a list. + /// Map fields are mutated by fetching the value and manipulating it as a dictionary. + /// + /// The field is not a "simple" field. + void SetValue(IMessage message, object value); + } +} \ No newline at end of file diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs new file mode 100644 index 0000000..40a6ff8 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs @@ -0,0 +1,430 @@ +#region Copyright notice and license +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Reflection; +#if NET35 +// Needed for ReadOnlyDictionary, which does not exist in .NET 3.5 +using Google.Protobuf.Collections; +#endif + +namespace Google.Protobuf.Reflection +{ + /// + /// Describes a message type. + /// + public sealed class MessageDescriptor : DescriptorBase + { + private static readonly HashSet WellKnownTypeNames = new HashSet + { + "google/protobuf/any.proto", + "google/protobuf/api.proto", + "google/protobuf/duration.proto", + "google/protobuf/empty.proto", + "google/protobuf/wrappers.proto", + "google/protobuf/timestamp.proto", + "google/protobuf/field_mask.proto", + "google/protobuf/source_context.proto", + "google/protobuf/struct.proto", + "google/protobuf/type.proto", + }; + + private readonly IList fieldsInDeclarationOrder; + private readonly IList fieldsInNumberOrder; + private readonly IDictionary jsonFieldMap; + private Func extensionSetIsInitialized; + + internal MessageDescriptor(DescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int typeIndex, GeneratedClrTypeInfo generatedCodeInfo) + : base(file, file.ComputeFullName(parent, proto.Name), typeIndex) + { + Proto = proto; + Parser = generatedCodeInfo?.Parser; + ClrType = generatedCodeInfo?.ClrType; + ContainingType = parent; + + // If generatedCodeInfo is null, we just won't generate an accessor for any fields. + Oneofs = DescriptorUtil.ConvertAndMakeReadOnly( + proto.OneofDecl, + (oneof, index) => + new OneofDescriptor(oneof, file, this, index, generatedCodeInfo?.OneofNames[index])); + + int syntheticOneofCount = 0; + foreach (var oneof in Oneofs) + { + if (oneof.IsSynthetic) + { + syntheticOneofCount++; + } + else if (syntheticOneofCount != 0) + { + throw new ArgumentException("All synthetic oneofs should come after real oneofs"); + } + } + RealOneofCount = Oneofs.Count - syntheticOneofCount; + + NestedTypes = DescriptorUtil.ConvertAndMakeReadOnly( + proto.NestedType, + (type, index) => + new MessageDescriptor(type, file, this, index, generatedCodeInfo?.NestedTypes[index])); + + EnumTypes = DescriptorUtil.ConvertAndMakeReadOnly( + proto.EnumType, + (type, index) => + new EnumDescriptor(type, file, this, index, generatedCodeInfo?.NestedEnums[index])); + + Extensions = new ExtensionCollection(this, generatedCodeInfo?.Extensions); + + fieldsInDeclarationOrder = DescriptorUtil.ConvertAndMakeReadOnly( + proto.Field, + (field, index) => + new FieldDescriptor(field, file, this, index, generatedCodeInfo?.PropertyNames[index], null)); + fieldsInNumberOrder = new ReadOnlyCollection(fieldsInDeclarationOrder.OrderBy(field => field.FieldNumber).ToArray()); + // TODO: Use field => field.Proto.JsonName when we're confident it's appropriate. (And then use it in the formatter, too.) + jsonFieldMap = CreateJsonFieldMap(fieldsInNumberOrder); + file.DescriptorPool.AddSymbol(this); + Fields = new FieldCollection(this); + } + + private static ReadOnlyDictionary CreateJsonFieldMap(IList fields) + { + var map = new Dictionary(); + foreach (var field in fields) + { + map[field.Name] = field; + map[field.JsonName] = field; + } + return new ReadOnlyDictionary(map); + } + + /// + /// The brief name of the descriptor's target. + /// + public override string Name => Proto.Name; + + internal override IReadOnlyList GetNestedDescriptorListForField(int fieldNumber) + { + switch (fieldNumber) + { + case DescriptorProto.FieldFieldNumber: + return (IReadOnlyList) fieldsInDeclarationOrder; + case DescriptorProto.NestedTypeFieldNumber: + return (IReadOnlyList) NestedTypes; + case DescriptorProto.EnumTypeFieldNumber: + return (IReadOnlyList) EnumTypes; + default: + return null; + } + } + + internal DescriptorProto Proto { get; } + + /// + /// Returns a clone of the underlying describing this message. + /// Note that a copy is taken every time this method is called, so clients using it frequently + /// (and not modifying it) may want to cache the returned value. + /// + /// A protobuf representation of this message descriptor. + public DescriptorProto ToProto() => Proto.Clone(); + + internal bool IsExtensionsInitialized(IMessage message) + { + if (Proto.ExtensionRange.Count == 0) + { + return true; + } + + if (extensionSetIsInitialized == null) + { + extensionSetIsInitialized = ReflectionUtil.CreateIsInitializedCaller(ClrType); + } + + return extensionSetIsInitialized(message); + } + + /// + /// The CLR type used to represent message instances from this descriptor. + /// + /// + /// + /// The value returned by this property will be non-null for all regular fields. However, + /// if a message containing a map field is introspected, the list of nested messages will include + /// an auto-generated nested key/value pair message for the field. This is not represented in any + /// generated type, so this property will return null in such cases. + /// + /// + /// For wrapper types ( and the like), the type returned here + /// will be the generated message type, not the native type used by reflection for fields of those types. Code + /// using reflection should call to determine whether a message descriptor represents + /// a wrapper type, and handle the result appropriately. + /// + /// + [DynamicallyAccessedMembers(GeneratedClrTypeInfo.MessageAccessibility)] + public Type ClrType { get; } + + /// + /// A parser for this message type. + /// + /// + /// + /// As is not generic, this cannot be statically + /// typed to the relevant type, but it should produce objects of a type compatible with . + /// + /// + /// The value returned by this property will be non-null for all regular fields. However, + /// if a message containing a map field is introspected, the list of nested messages will include + /// an auto-generated nested key/value pair message for the field. No message parser object is created for + /// such messages, so this property will return null in such cases. + /// + /// + /// For wrapper types ( and the like), the parser returned here + /// will be the generated message type, not the native type used by reflection for fields of those types. Code + /// using reflection should call to determine whether a message descriptor represents + /// a wrapper type, and handle the result appropriately. + /// + /// + public MessageParser Parser { get; } + + /// + /// Returns whether this message is one of the "well known types" which may have runtime/protoc support. + /// + internal bool IsWellKnownType => File.Package == "google.protobuf" && WellKnownTypeNames.Contains(File.Name); + + /// + /// Returns whether this message is one of the "wrapper types" used for fields which represent primitive values + /// with the addition of presence. + /// + internal bool IsWrapperType => File.Package == "google.protobuf" && File.Name == "google/protobuf/wrappers.proto"; + + /// + /// If this is a nested type, get the outer descriptor, otherwise null. + /// + public MessageDescriptor ContainingType { get; } + + /// + /// A collection of fields, which can be retrieved by name or field number. + /// + public FieldCollection Fields { get; } + + /// + /// An unmodifiable list of extensions defined in this message's scope. + /// Note that some extensions may be incomplete (FieldDescriptor.Extension may be null) + /// if they are declared in a file generated using a version of protoc that did not fully + /// support extensions in C#. + /// + public ExtensionCollection Extensions { get; } + + /// + /// An unmodifiable list of this message type's nested types. + /// + public IList NestedTypes { get; } + + /// + /// An unmodifiable list of this message type's enum types. + /// + public IList EnumTypes { get; } + + /// + /// An unmodifiable list of the "oneof" field collections in this message type. + /// All "real" oneofs (where returns false) + /// come before synthetic ones. + /// + public IList Oneofs { get; } + + /// + /// The number of real "oneof" descriptors in this message type. Every element in + /// with an index less than this will have a property value + /// of false; every element with an index greater than or equal to this will have a + /// property value of true. + /// + public int RealOneofCount { get; } + + /// + /// Finds a field by field name. + /// + /// The unqualified name of the field (e.g. "foo"). + /// The field's descriptor, or null if not found. + public FieldDescriptor FindFieldByName(String name) => File.DescriptorPool.FindSymbol(FullName + "." + name); + + /// + /// Finds a field by field number. + /// + /// The field number within this message type. + /// The field's descriptor, or null if not found. + public FieldDescriptor FindFieldByNumber(int number) => File.DescriptorPool.FindFieldByNumber(this, number); + + /// + /// Finds a nested descriptor by name. The is valid for fields, nested + /// message types, oneofs and enums. + /// + /// The unqualified name of the descriptor, e.g. "Foo" + /// The descriptor, or null if not found. + public T FindDescriptor(string name) where T : class, IDescriptor => + File.DescriptorPool.FindSymbol(FullName + "." + name); + + /// + /// The (possibly empty) set of custom options for this message. + /// + [Obsolete("CustomOptions are obsolete. Use the GetOptions() method.")] + public CustomOptions CustomOptions => new CustomOptions(Proto.Options?._extensions?.ValuesByNumber); + + /// + /// The MessageOptions, defined in descriptor.proto. + /// If the options message is not present (i.e. there are no options), null is returned. + /// Custom options can be retrieved as extensions of the returned message. + /// NOTE: A defensive copy is created each time this property is retrieved. + /// + public MessageOptions GetOptions() => Proto.Options?.Clone(); + + /// + /// Gets a single value message option for this descriptor + /// + [Obsolete("GetOption is obsolete. Use the GetOptions() method.")] + public T GetOption(Extension extension) + { + var value = Proto.Options.GetExtension(extension); + return value is IDeepCloneable ? (value as IDeepCloneable).Clone() : value; + } + + /// + /// Gets a repeated value message option for this descriptor + /// + [Obsolete("GetOption is obsolete. Use the GetOptions() method.")] + public Collections.RepeatedField GetOption(RepeatedExtension extension) + { + return Proto.Options.GetExtension(extension).Clone(); + } + + /// + /// Looks up and cross-links all fields and nested types. + /// + internal void CrossLink() + { + foreach (MessageDescriptor message in NestedTypes) + { + message.CrossLink(); + } + + foreach (FieldDescriptor field in fieldsInDeclarationOrder) + { + field.CrossLink(); + } + + foreach (OneofDescriptor oneof in Oneofs) + { + oneof.CrossLink(); + } + + Extensions.CrossLink(); + } + + /// + /// A collection to simplify retrieving the field accessor for a particular field. + /// + public sealed class FieldCollection + { + private readonly MessageDescriptor messageDescriptor; + + internal FieldCollection(MessageDescriptor messageDescriptor) + { + this.messageDescriptor = messageDescriptor; + } + + /// + /// Returns the fields in the message as an immutable list, in the order in which they + /// are declared in the source .proto file. + /// + public IList InDeclarationOrder() => messageDescriptor.fieldsInDeclarationOrder; + + /// + /// Returns the fields in the message as an immutable list, in ascending field number + /// order. Field numbers need not be contiguous, so there is no direct mapping from the + /// index in the list to the field number; to retrieve a field by field number, it is better + /// to use the indexer. + /// + public IList InFieldNumberOrder() => messageDescriptor.fieldsInNumberOrder; + + // TODO: consider making this public in the future. (Being conservative for now...) + + /// + /// Returns a read-only dictionary mapping the field names in this message as they're available + /// in the JSON representation to the field descriptors. For example, a field foo_bar + /// in the message would result two entries, one with a key fooBar and one with a key + /// foo_bar, both referring to the same field. + /// + internal IDictionary ByJsonName() => messageDescriptor.jsonFieldMap; + + /// + /// Retrieves the descriptor for the field with the given number. + /// + /// Number of the field to retrieve the descriptor for + /// The accessor for the given field + /// The message descriptor does not contain a field + /// with the given number + public FieldDescriptor this[int number] + { + get + { + var fieldDescriptor = messageDescriptor.FindFieldByNumber(number); + if (fieldDescriptor == null) + { + throw new KeyNotFoundException("No such field number"); + } + return fieldDescriptor; + } + } + + /// + /// Retrieves the descriptor for the field with the given name. + /// + /// Name of the field to retrieve the descriptor for + /// The descriptor for the given field + /// The message descriptor does not contain a field + /// with the given name + public FieldDescriptor this[string name] + { + get + { + var fieldDescriptor = messageDescriptor.FindFieldByName(name); + if (fieldDescriptor == null) + { + throw new KeyNotFoundException("No such field name"); + } + return fieldDescriptor; + } + } + } + } +} diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/SegmentedBufferHelper.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/SegmentedBufferHelper.cs new file mode 100644 index 0000000..b5441d3 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/SegmentedBufferHelper.cs @@ -0,0 +1,296 @@ +#region Copyright notice and license +// 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. +#endregion + +using System; +using System.Buffers; +using System.IO; +using System.Runtime.CompilerServices; +using System.Security; + +namespace Google.Protobuf +{ + /// + /// Abstraction for reading from a stream / read only sequence. + /// Parsing from the buffer is a loop of reading from current buffer / refreshing the buffer once done. + /// + [SecuritySafeCritical] + internal struct SegmentedBufferHelper + { + private int? totalLength; + private ReadOnlySequence.Enumerator readOnlySequenceEnumerator; + private CodedInputStream codedInputStream; + + /// + /// Initialize an instance with a coded input stream. + /// This approach is faster than using a constructor because the instance to initialize is passed by reference + /// and we can write directly into it without copying. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Initialize(CodedInputStream codedInputStream, out SegmentedBufferHelper instance) + { + instance.totalLength = codedInputStream.InternalInputStream == null ? (int?)codedInputStream.InternalBuffer.Length : null; + instance.readOnlySequenceEnumerator = default; + instance.codedInputStream = codedInputStream; + } + + /// + /// Initialize an instance with a read only sequence. + /// This approach is faster than using a constructor because the instance to initialize is passed by reference + /// and we can write directly into it without copying. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Initialize(ReadOnlySequence sequence, out SegmentedBufferHelper instance, out ReadOnlySpan firstSpan) + { + instance.codedInputStream = null; + if (sequence.IsSingleSegment) + { + firstSpan = sequence.First.Span; + instance.totalLength = firstSpan.Length; + instance.readOnlySequenceEnumerator = default; + } + else + { + instance.readOnlySequenceEnumerator = sequence.GetEnumerator(); + instance.totalLength = (int) sequence.Length; + + // set firstSpan to the first segment + instance.readOnlySequenceEnumerator.MoveNext(); + firstSpan = instance.readOnlySequenceEnumerator.Current.Span; + } + } + + public bool RefillBuffer(ref ReadOnlySpan buffer, ref ParserInternalState state, bool mustSucceed) + { + if (codedInputStream != null) + { + return RefillFromCodedInputStream(ref buffer, ref state, mustSucceed); + } + else + { + return RefillFromReadOnlySequence(ref buffer, ref state, mustSucceed); + } + } + + public int? TotalLength => totalLength; + + public CodedInputStream CodedInputStream => codedInputStream; + + /// + /// Sets currentLimit to (current position) + byteLimit. This is called + /// when descending into a length-delimited embedded message. The previous + /// limit is returned. + /// + /// The old limit. + public static int PushLimit(ref ParserInternalState state, int byteLimit) + { + if (byteLimit < 0) + { + throw InvalidProtocolBufferException.NegativeSize(); + } + byteLimit += state.totalBytesRetired + state.bufferPos; + int oldLimit = state.currentLimit; + if (byteLimit > oldLimit) + { + throw InvalidProtocolBufferException.TruncatedMessage(); + } + state.currentLimit = byteLimit; + + RecomputeBufferSizeAfterLimit(ref state); + + return oldLimit; + } + + /// + /// Discards the current limit, returning the previous limit. + /// + public static void PopLimit(ref ParserInternalState state, int oldLimit) + { + state.currentLimit = oldLimit; + RecomputeBufferSizeAfterLimit(ref state); + } + + /// + /// Returns whether or not all the data before the limit has been read. + /// + /// + public static bool IsReachedLimit(ref ParserInternalState state) + { + if (state.currentLimit == int.MaxValue) + { + return false; + } + int currentAbsolutePosition = state.totalBytesRetired + state.bufferPos; + return currentAbsolutePosition >= state.currentLimit; + } + + /// + /// Returns true if the stream has reached the end of the input. This is the + /// case if either the end of the underlying input source has been reached or + /// the stream has reached a limit created using PushLimit. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsAtEnd(ref ReadOnlySpan buffer, ref ParserInternalState state) + { + return state.bufferPos == state.bufferSize && !state.segmentedBufferHelper.RefillBuffer(ref buffer, ref state, false); + } + + private bool RefillFromReadOnlySequence(ref ReadOnlySpan buffer, ref ParserInternalState state, bool mustSucceed) + { + CheckCurrentBufferIsEmpty(ref state); + + if (state.totalBytesRetired + state.bufferSize == state.currentLimit) + { + // Oops, we hit a limit. + if (mustSucceed) + { + throw InvalidProtocolBufferException.TruncatedMessage(); + } + else + { + return false; + } + } + + state.totalBytesRetired += state.bufferSize; + + state.bufferPos = 0; + state.bufferSize = 0; + while (readOnlySequenceEnumerator.MoveNext()) + { + buffer = readOnlySequenceEnumerator.Current.Span; + state.bufferSize = buffer.Length; + if (buffer.Length != 0) + { + break; + } + } + + if (state.bufferSize == 0) + { + if (mustSucceed) + { + throw InvalidProtocolBufferException.TruncatedMessage(); + } + else + { + return false; + } + } + else + { + RecomputeBufferSizeAfterLimit(ref state); + int totalBytesRead = + state.totalBytesRetired + state.bufferSize + state.bufferSizeAfterLimit; + if (totalBytesRead < 0 || totalBytesRead > state.sizeLimit) + { + throw InvalidProtocolBufferException.SizeLimitExceeded(); + } + return true; + } + } + + private bool RefillFromCodedInputStream(ref ReadOnlySpan buffer, ref ParserInternalState state, bool mustSucceed) + { + CheckCurrentBufferIsEmpty(ref state); + + if (state.totalBytesRetired + state.bufferSize == state.currentLimit) + { + // Oops, we hit a limit. + if (mustSucceed) + { + throw InvalidProtocolBufferException.TruncatedMessage(); + } + else + { + return false; + } + } + + Stream input = codedInputStream.InternalInputStream; + + state.totalBytesRetired += state.bufferSize; + + state.bufferPos = 0; + state.bufferSize = (input == null) ? 0 : input.Read(codedInputStream.InternalBuffer, 0, buffer.Length); + if (state.bufferSize < 0) + { + throw new InvalidOperationException("Stream.Read returned a negative count"); + } + if (state.bufferSize == 0) + { + if (mustSucceed) + { + throw InvalidProtocolBufferException.TruncatedMessage(); + } + else + { + return false; + } + } + else + { + RecomputeBufferSizeAfterLimit(ref state); + int totalBytesRead = + state.totalBytesRetired + state.bufferSize + state.bufferSizeAfterLimit; + if (totalBytesRead < 0 || totalBytesRead > state.sizeLimit) + { + throw InvalidProtocolBufferException.SizeLimitExceeded(); + } + return true; + } + } + + private static void RecomputeBufferSizeAfterLimit(ref ParserInternalState state) + { + state.bufferSize += state.bufferSizeAfterLimit; + int bufferEnd = state.totalBytesRetired + state.bufferSize; + if (bufferEnd > state.currentLimit) + { + // Limit is in current buffer. + state.bufferSizeAfterLimit = bufferEnd - state.currentLimit; + state.bufferSize -= state.bufferSizeAfterLimit; + } + else + { + state.bufferSizeAfterLimit = 0; + } + } + + private static void CheckCurrentBufferIsEmpty(ref ParserInternalState state) + { + if (state.bufferPos < state.bufferSize) + { + throw new InvalidOperationException("RefillBuffer() called when buffer wasn't empty."); + } + } + } +} \ No newline at end of file diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/UnknownField.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/UnknownField.cs new file mode 100644 index 0000000..4793a64 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/UnknownField.cs @@ -0,0 +1,290 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2017 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using Google.Protobuf.Collections; + +namespace Google.Protobuf +{ + /// + /// Represents a single field in an UnknownFieldSet. + /// + /// An UnknownField consists of four lists of values. The lists correspond + /// to the four "wire types" used in the protocol buffer binary format. + /// Normally, only one of the four lists will contain any values, since it + /// is impossible to define a valid message type that declares two different + /// types for the same field number. However, the code is designed to allow + /// for the case where the same unknown field number is encountered using + /// multiple different wire types. + /// + /// + internal sealed class UnknownField + { + private List varintList; + private List fixed32List; + private List fixed64List; + private List lengthDelimitedList; + private List groupList; + + /// + /// Creates a new UnknownField. + /// + public UnknownField() + { + } + + /// + /// Checks if two unknown field are equal. + /// + public override bool Equals(object other) + { + if (ReferenceEquals(this, other)) + { + return true; + } + UnknownField otherField = other as UnknownField; + return otherField != null + && Lists.Equals(varintList, otherField.varintList) + && Lists.Equals(fixed32List, otherField.fixed32List) + && Lists.Equals(fixed64List, otherField.fixed64List) + && Lists.Equals(lengthDelimitedList, otherField.lengthDelimitedList) + && Lists.Equals(groupList, otherField.groupList); + } + + /// + /// Get the hash code of the unknown field. + /// + public override int GetHashCode() + { + int hash = 43; + hash = hash * 47 + Lists.GetHashCode(varintList); + hash = hash * 47 + Lists.GetHashCode(fixed32List); + hash = hash * 47 + Lists.GetHashCode(fixed64List); + hash = hash * 47 + Lists.GetHashCode(lengthDelimitedList); + hash = hash * 47 + Lists.GetHashCode(groupList); + return hash; + } + + /// + /// Serializes the field, including the field number, and writes it to + /// + /// + /// The unknown field number. + /// The write context to write to. + internal void WriteTo(int fieldNumber, ref WriteContext output) + { + if (varintList != null) + { + foreach (ulong value in varintList) + { + output.WriteTag(fieldNumber, WireFormat.WireType.Varint); + output.WriteUInt64(value); + } + } + if (fixed32List != null) + { + foreach (uint value in fixed32List) + { + output.WriteTag(fieldNumber, WireFormat.WireType.Fixed32); + output.WriteFixed32(value); + } + } + if (fixed64List != null) + { + foreach (ulong value in fixed64List) + { + output.WriteTag(fieldNumber, WireFormat.WireType.Fixed64); + output.WriteFixed64(value); + } + } + if (lengthDelimitedList != null) + { + foreach (ByteString value in lengthDelimitedList) + { + output.WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteBytes(value); + } + } + if (groupList != null) + { + foreach (UnknownFieldSet value in groupList) + { + output.WriteTag(fieldNumber, WireFormat.WireType.StartGroup); + value.WriteTo(ref output); + output.WriteTag(fieldNumber, WireFormat.WireType.EndGroup); + } + } + } + + /// + /// Computes the number of bytes required to encode this field, including field + /// number. + /// + internal int GetSerializedSize(int fieldNumber) + { + int result = 0; + if (varintList != null) + { + result += CodedOutputStream.ComputeTagSize(fieldNumber) * varintList.Count; + foreach (ulong value in varintList) + { + result += CodedOutputStream.ComputeUInt64Size(value); + } + } + if (fixed32List != null) + { + result += CodedOutputStream.ComputeTagSize(fieldNumber) * fixed32List.Count; + result += CodedOutputStream.ComputeFixed32Size(1) * fixed32List.Count; + } + if (fixed64List != null) + { + result += CodedOutputStream.ComputeTagSize(fieldNumber) * fixed64List.Count; + result += CodedOutputStream.ComputeFixed64Size(1) * fixed64List.Count; + } + if (lengthDelimitedList != null) + { + result += CodedOutputStream.ComputeTagSize(fieldNumber) * lengthDelimitedList.Count; + foreach (ByteString value in lengthDelimitedList) + { + result += CodedOutputStream.ComputeBytesSize(value); + } + } + if (groupList != null) + { + result += CodedOutputStream.ComputeTagSize(fieldNumber) * 2 * groupList.Count; + foreach (UnknownFieldSet value in groupList) + { + result += value.CalculateSize(); + } + } + return result; + } + + /// + /// Merge the values in into this field. For each list + /// of values, 's values are append to the ones in this + /// field. + /// + internal UnknownField MergeFrom(UnknownField other) + { + varintList = AddAll(varintList, other.varintList); + fixed32List = AddAll(fixed32List, other.fixed32List); + fixed64List = AddAll(fixed64List, other.fixed64List); + lengthDelimitedList = AddAll(lengthDelimitedList, other.lengthDelimitedList); + groupList = AddAll(groupList, other.groupList); + return this; + } + + /// + /// Returns a new list containing all of the given specified values from + /// both the and lists. + /// If is null and is null or empty, + /// null is returned. Otherwise, either a new list is created (if + /// is null) or the elements of are added to . + /// + private static List AddAll(List current, IList extras) + { + if (extras == null || extras.Count == 0) + { + return current; + } + if (current == null) + { + current = new List(extras); + } + else + { + current.AddRange(extras); + } + return current; + } + + /// + /// Adds a varint value. + /// + internal UnknownField AddVarint(ulong value) + { + varintList = Add(varintList, value); + return this; + } + + /// + /// Adds a fixed32 value. + /// + internal UnknownField AddFixed32(uint value) + { + fixed32List = Add(fixed32List, value); + return this; + } + + /// + /// Adds a fixed64 value. + /// + internal UnknownField AddFixed64(ulong value) + { + fixed64List = Add(fixed64List, value); + return this; + } + + /// + /// Adds a length-delimited value. + /// + internal UnknownField AddLengthDelimited(ByteString value) + { + lengthDelimitedList = Add(lengthDelimitedList, value); + return this; + } + + internal UnknownField AddGroup(UnknownFieldSet value) + { + groupList = Add(groupList, value); + return this; + } + + /// + /// Adds to the , creating + /// a new list if is null. The list is returned - either + /// the original reference or the new list. + /// + private static List Add(List list, T value) + { + if (list == null) + { + list = new List(); + } + list.Add(value); + return list; + } + } +} diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs new file mode 100644 index 0000000..13066da --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs @@ -0,0 +1,387 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/any.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Google.Protobuf.WellKnownTypes { + + /// Holder for reflection information generated from google/protobuf/any.proto + public static partial class AnyReflection { + + #region Descriptor + /// File descriptor for google/protobuf/any.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static AnyReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Chlnb29nbGUvcHJvdG9idWYvYW55LnByb3RvEg9nb29nbGUucHJvdG9idWYi", + "JgoDQW55EhAKCHR5cGVfdXJsGAEgASgJEg0KBXZhbHVlGAIgASgMQnYKE2Nv", + "bS5nb29nbGUucHJvdG9idWZCCEFueVByb3RvUAFaLGdvb2dsZS5nb2xhbmcu", + "b3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL2FueXBiogIDR1BCqgIeR29vZ2xl", + "LlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM=")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Any), global::Google.Protobuf.WellKnownTypes.Any.Parser, new[]{ "TypeUrl", "Value" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + /// + /// `Any` contains an arbitrary serialized protocol buffer message along with a + /// URL that describes the type of the serialized message. + /// + /// Protobuf library provides support to pack/unpack Any values in the form + /// of utility functions or additional generated methods of the Any type. + /// + /// Example 1: Pack and unpack a message in C++. + /// + /// Foo foo = ...; + /// Any any; + /// any.PackFrom(foo); + /// ... + /// if (any.UnpackTo(&foo)) { + /// ... + /// } + /// + /// Example 2: Pack and unpack a message in Java. + /// + /// Foo foo = ...; + /// Any any = Any.pack(foo); + /// ... + /// if (any.is(Foo.class)) { + /// foo = any.unpack(Foo.class); + /// } + /// + /// Example 3: Pack and unpack a message in Python. + /// + /// foo = Foo(...) + /// any = Any() + /// any.Pack(foo) + /// ... + /// if any.Is(Foo.DESCRIPTOR): + /// any.Unpack(foo) + /// ... + /// + /// Example 4: Pack and unpack a message in Go + /// + /// foo := &pb.Foo{...} + /// any, err := anypb.New(foo) + /// if err != nil { + /// ... + /// } + /// ... + /// foo := &pb.Foo{} + /// if err := any.UnmarshalTo(foo); err != nil { + /// ... + /// } + /// + /// The pack methods provided by protobuf library will by default use + /// 'type.googleapis.com/full.type.name' as the type URL and the unpack + /// methods only use the fully qualified type name after the last '/' + /// in the type URL, for example "foo.bar.com/x/y.z" will yield type + /// name "y.z". + /// + /// JSON + /// + /// The JSON representation of an `Any` value uses the regular + /// representation of the deserialized, embedded message, with an + /// additional field `@type` which contains the type URL. Example: + /// + /// package google.profile; + /// message Person { + /// string first_name = 1; + /// string last_name = 2; + /// } + /// + /// { + /// "@type": "type.googleapis.com/google.profile.Person", + /// "firstName": <string>, + /// "lastName": <string> + /// } + /// + /// If the embedded message type is well-known and has a custom JSON + /// representation, that representation will be embedded adding a field + /// `value` which holds the custom JSON in addition to the `@type` + /// field. Example (for message [google.protobuf.Duration][]): + /// + /// { + /// "@type": "type.googleapis.com/google.protobuf.Duration", + /// "value": "1.212s" + /// } + /// + public sealed partial class Any : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Any()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.WellKnownTypes.AnyReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Any() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Any(Any other) : this() { + typeUrl_ = other.typeUrl_; + value_ = other.value_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Any Clone() { + return new Any(this); + } + + /// Field number for the "type_url" field. + public const int TypeUrlFieldNumber = 1; + private string typeUrl_ = ""; + /// + /// A URL/resource name that uniquely identifies the type of the serialized + /// protocol buffer message. This string must contain at least + /// one "/" character. The last segment of the URL's path must represent + /// the fully qualified name of the type (as in + /// `path/google.protobuf.Duration`). The name should be in a canonical form + /// (e.g., leading "." is not accepted). + /// + /// In practice, teams usually precompile into the binary all types that they + /// expect it to use in the context of Any. However, for URLs which use the + /// scheme `http`, `https`, or no scheme, one can optionally set up a type + /// server that maps type URLs to message definitions as follows: + /// + /// * If no scheme is provided, `https` is assumed. + /// * An HTTP GET on the URL must yield a [google.protobuf.Type][] + /// value in binary format, or produce an error. + /// * Applications are allowed to cache lookup results based on the + /// URL, or have them precompiled into a binary to avoid any + /// lookup. Therefore, binary compatibility needs to be preserved + /// on changes to types. (Use versioned type names to manage + /// breaking changes.) + /// + /// Note: this functionality is not currently available in the official + /// protobuf release, and it is not used for type URLs beginning with + /// type.googleapis.com. + /// + /// Schemes other than `http`, `https` (or the empty scheme) might be + /// used with implementation specific semantics. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string TypeUrl { + get { return typeUrl_; } + set { + typeUrl_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "value" field. + public const int ValueFieldNumber = 2; + private pb::ByteString value_ = pb::ByteString.Empty; + /// + /// Must be a valid serialized protocol buffer of the above specified type. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pb::ByteString Value { + get { return value_; } + set { + value_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as Any); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(Any other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (TypeUrl != other.TypeUrl) return false; + if (Value != other.Value) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (TypeUrl.Length != 0) hash ^= TypeUrl.GetHashCode(); + if (Value.Length != 0) hash ^= Value.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (TypeUrl.Length != 0) { + output.WriteRawTag(10); + output.WriteString(TypeUrl); + } + if (Value.Length != 0) { + output.WriteRawTag(18); + output.WriteBytes(Value); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (TypeUrl.Length != 0) { + output.WriteRawTag(10); + output.WriteString(TypeUrl); + } + if (Value.Length != 0) { + output.WriteRawTag(18); + output.WriteBytes(Value); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (TypeUrl.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(TypeUrl); + } + if (Value.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeBytesSize(Value); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(Any other) { + if (other == null) { + return; + } + if (other.TypeUrl.Length != 0) { + TypeUrl = other.TypeUrl; + } + if (other.Value.Length != 0) { + Value = other.Value; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + TypeUrl = input.ReadString(); + break; + } + case 18: { + Value = input.ReadBytes(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + TypeUrl = input.ReadString(); + break; + } + case 18: { + Value = input.ReadBytes(); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/WellKnownTypes/AnyPartial.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/WellKnownTypes/AnyPartial.cs new file mode 100644 index 0000000..49f2599 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/WellKnownTypes/AnyPartial.cs @@ -0,0 +1,147 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using Google.Protobuf.Reflection; + +namespace Google.Protobuf.WellKnownTypes +{ + public partial class Any + { + private const string DefaultPrefix = "type.googleapis.com"; + + // This could be moved to MessageDescriptor if we wanted to, but keeping it here means + // all the Any-specific code is in the same place. + private static string GetTypeUrl(MessageDescriptor descriptor, string prefix) => + prefix.EndsWith("/") ? prefix + descriptor.FullName : prefix + "/" + descriptor.FullName; + + /// + /// Retrieves the type name for a type URL, matching the + /// of the packed message type. + /// + /// + /// + /// This is always just the last part of the URL, after the final slash. No validation of + /// anything before the trailing slash is performed. If the type URL does not include a slash, + /// an empty string is returned rather than an exception being thrown; this won't match any types, + /// and the calling code is probably in a better position to give a meaningful error. + /// + /// + /// There is no handling of fragments or queries at the moment. + /// + /// + /// The URL to extract the type name from + /// The type name + public static string GetTypeName(string typeUrl) + { + ProtoPreconditions.CheckNotNull(typeUrl, nameof(typeUrl)); + int lastSlash = typeUrl.LastIndexOf('/'); + return lastSlash == -1 ? "" : typeUrl.Substring(lastSlash + 1); + } + + /// + /// Returns a bool indictating whether this Any message is of the target message type + /// + /// The descriptor of the message type + /// true if the type name matches the descriptor's full name or false otherwise + public bool Is(MessageDescriptor descriptor) + { + ProtoPreconditions.CheckNotNull(descriptor, nameof(descriptor)); + return GetTypeName(TypeUrl) == descriptor.FullName; + } + + /// + /// Unpacks the content of this Any message into the target message type, + /// which must match the type URL within this Any message. + /// + /// The type of message to unpack the content into. + /// The unpacked message. + /// The target message type doesn't match the type URL in this message + public T Unpack() where T : IMessage, new() + { + // Note: this doesn't perform as well is it might. We could take a MessageParser in an alternative overload, + // which would be expected to perform slightly better... although the difference is likely to be negligible. + T target = new T(); + if (GetTypeName(TypeUrl) != target.Descriptor.FullName) + { + throw new InvalidProtocolBufferException( + $"Full type name for {target.Descriptor.Name} is {target.Descriptor.FullName}; Any message's type url is {TypeUrl}"); + } + target.MergeFrom(Value); + return target; + } + + /// + /// Attempts to unpack the content of this Any message into the target message type, + /// if it matches the type URL within this Any message. + /// + /// The type of message to attempt to unpack the content into. + /// true if the message was successfully unpacked; false if the type name didn't match + public bool TryUnpack(out T result) where T : IMessage, new() + { + // Note: deliberately avoid writing anything to result until the end, in case it's being + // monitored by other threads. (That would be a bug in the calling code, but let's not make it worse.) + T target = new T(); + if (GetTypeName(TypeUrl) != target.Descriptor.FullName) + { + result = default(T); // Can't use null as there's no class constraint, but this always *will* be null in real usage. + return false; + } + target.MergeFrom(Value); + result = target; + return true; + } + + /// + /// Packs the specified message into an Any message using a type URL prefix of "type.googleapis.com". + /// + /// The message to pack. + /// An Any message with the content and type URL of . + public static Any Pack(IMessage message) => Pack(message, DefaultPrefix); + + /// + /// Packs the specified message into an Any message using the specified type URL prefix. + /// + /// The message to pack. + /// The prefix for the type URL. + /// An Any message with the content and type URL of . + public static Any Pack(IMessage message, string typeUrlPrefix) + { + ProtoPreconditions.CheckNotNull(message, nameof(message)); + ProtoPreconditions.CheckNotNull(typeUrlPrefix, nameof(typeUrlPrefix)); + return new Any + { + TypeUrl = GetTypeUrl(message.Descriptor, typeUrlPrefix), + Value = message.ToByteString() + }; + } + } +} diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs new file mode 100644 index 0000000..b46f4d2 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs @@ -0,0 +1,346 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/duration.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Google.Protobuf.WellKnownTypes { + + /// Holder for reflection information generated from google/protobuf/duration.proto + public static partial class DurationReflection { + + #region Descriptor + /// File descriptor for google/protobuf/duration.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static DurationReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Ch5nb29nbGUvcHJvdG9idWYvZHVyYXRpb24ucHJvdG8SD2dvb2dsZS5wcm90", + "b2J1ZiIqCghEdXJhdGlvbhIPCgdzZWNvbmRzGAEgASgDEg0KBW5hbm9zGAIg", + "ASgFQoMBChNjb20uZ29vZ2xlLnByb3RvYnVmQg1EdXJhdGlvblByb3RvUAFa", + "MWdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL2R1cmF0", + "aW9ucGL4AQGiAgNHUEKqAh5Hb29nbGUuUHJvdG9idWYuV2VsbEtub3duVHlw", + "ZXNiBnByb3RvMw==")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Duration), global::Google.Protobuf.WellKnownTypes.Duration.Parser, new[]{ "Seconds", "Nanos" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + /// + /// A Duration represents a signed, fixed-length span of time represented + /// as a count of seconds and fractions of seconds at nanosecond + /// resolution. It is independent of any calendar and concepts like "day" + /// or "month". It is related to Timestamp in that the difference between + /// two Timestamp values is a Duration and it can be added or subtracted + /// from a Timestamp. Range is approximately +-10,000 years. + /// + /// # Examples + /// + /// Example 1: Compute Duration from two Timestamps in pseudo code. + /// + /// Timestamp start = ...; + /// Timestamp end = ...; + /// Duration duration = ...; + /// + /// duration.seconds = end.seconds - start.seconds; + /// duration.nanos = end.nanos - start.nanos; + /// + /// if (duration.seconds < 0 && duration.nanos > 0) { + /// duration.seconds += 1; + /// duration.nanos -= 1000000000; + /// } else if (duration.seconds > 0 && duration.nanos < 0) { + /// duration.seconds -= 1; + /// duration.nanos += 1000000000; + /// } + /// + /// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. + /// + /// Timestamp start = ...; + /// Duration duration = ...; + /// Timestamp end = ...; + /// + /// end.seconds = start.seconds + duration.seconds; + /// end.nanos = start.nanos + duration.nanos; + /// + /// if (end.nanos < 0) { + /// end.seconds -= 1; + /// end.nanos += 1000000000; + /// } else if (end.nanos >= 1000000000) { + /// end.seconds += 1; + /// end.nanos -= 1000000000; + /// } + /// + /// Example 3: Compute Duration from datetime.timedelta in Python. + /// + /// td = datetime.timedelta(days=3, minutes=10) + /// duration = Duration() + /// duration.FromTimedelta(td) + /// + /// # JSON Mapping + /// + /// In JSON format, the Duration type is encoded as a string rather than an + /// object, where the string ends in the suffix "s" (indicating seconds) and + /// is preceded by the number of seconds, with nanoseconds expressed as + /// fractional seconds. For example, 3 seconds with 0 nanoseconds should be + /// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should + /// be expressed in JSON format as "3.000000001s", and 3 seconds and 1 + /// microsecond should be expressed in JSON format as "3.000001s". + /// + public sealed partial class Duration : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Duration()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.WellKnownTypes.DurationReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Duration() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Duration(Duration other) : this() { + seconds_ = other.seconds_; + nanos_ = other.nanos_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Duration Clone() { + return new Duration(this); + } + + /// Field number for the "seconds" field. + public const int SecondsFieldNumber = 1; + private long seconds_; + /// + /// Signed seconds of the span of time. Must be from -315,576,000,000 + /// to +315,576,000,000 inclusive. Note: these bounds are computed from: + /// 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public long Seconds { + get { return seconds_; } + set { + seconds_ = value; + } + } + + /// Field number for the "nanos" field. + public const int NanosFieldNumber = 2; + private int nanos_; + /// + /// Signed fractions of a second at nanosecond resolution of the span + /// of time. Durations less than one second are represented with a 0 + /// `seconds` field and a positive or negative `nanos` field. For durations + /// of one second or more, a non-zero value for the `nanos` field must be + /// of the same sign as the `seconds` field. Must be from -999,999,999 + /// to +999,999,999 inclusive. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Nanos { + get { return nanos_; } + set { + nanos_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as Duration); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(Duration other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Seconds != other.Seconds) return false; + if (Nanos != other.Nanos) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (Seconds != 0L) hash ^= Seconds.GetHashCode(); + if (Nanos != 0) hash ^= Nanos.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Seconds != 0L) { + output.WriteRawTag(8); + output.WriteInt64(Seconds); + } + if (Nanos != 0) { + output.WriteRawTag(16); + output.WriteInt32(Nanos); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Seconds != 0L) { + output.WriteRawTag(8); + output.WriteInt64(Seconds); + } + if (Nanos != 0) { + output.WriteRawTag(16); + output.WriteInt32(Nanos); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (Seconds != 0L) { + size += 1 + pb::CodedOutputStream.ComputeInt64Size(Seconds); + } + if (Nanos != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Nanos); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(Duration other) { + if (other == null) { + return; + } + if (other.Seconds != 0L) { + Seconds = other.Seconds; + } + if (other.Nanos != 0) { + Nanos = other.Nanos; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Seconds = input.ReadInt64(); + break; + } + case 16: { + Nanos = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Seconds = input.ReadInt64(); + break; + } + case 16: { + Nanos = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs new file mode 100644 index 0000000..e90c3d5 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs @@ -0,0 +1,427 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/field_mask.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Google.Protobuf.WellKnownTypes { + + /// Holder for reflection information generated from google/protobuf/field_mask.proto + public static partial class FieldMaskReflection { + + #region Descriptor + /// File descriptor for google/protobuf/field_mask.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static FieldMaskReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "CiBnb29nbGUvcHJvdG9idWYvZmllbGRfbWFzay5wcm90bxIPZ29vZ2xlLnBy", + "b3RvYnVmIhoKCUZpZWxkTWFzaxINCgVwYXRocxgBIAMoCUKFAQoTY29tLmdv", + "b2dsZS5wcm90b2J1ZkIORmllbGRNYXNrUHJvdG9QAVoyZ29vZ2xlLmdvbGFu", + "Zy5vcmcvcHJvdG9idWYvdHlwZXMva25vd24vZmllbGRtYXNrcGL4AQGiAgNH", + "UEKqAh5Hb29nbGUuUHJvdG9idWYuV2VsbEtub3duVHlwZXNiBnByb3RvMw==")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.FieldMask), global::Google.Protobuf.WellKnownTypes.FieldMask.Parser, new[]{ "Paths" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + /// + /// `FieldMask` represents a set of symbolic field paths, for example: + /// + /// paths: "f.a" + /// paths: "f.b.d" + /// + /// Here `f` represents a field in some root message, `a` and `b` + /// fields in the message found in `f`, and `d` a field found in the + /// message in `f.b`. + /// + /// Field masks are used to specify a subset of fields that should be + /// returned by a get operation or modified by an update operation. + /// Field masks also have a custom JSON encoding (see below). + /// + /// # Field Masks in Projections + /// + /// When used in the context of a projection, a response message or + /// sub-message is filtered by the API to only contain those fields as + /// specified in the mask. For example, if the mask in the previous + /// example is applied to a response message as follows: + /// + /// f { + /// a : 22 + /// b { + /// d : 1 + /// x : 2 + /// } + /// y : 13 + /// } + /// z: 8 + /// + /// The result will not contain specific values for fields x,y and z + /// (their value will be set to the default, and omitted in proto text + /// output): + /// + /// f { + /// a : 22 + /// b { + /// d : 1 + /// } + /// } + /// + /// A repeated field is not allowed except at the last position of a + /// paths string. + /// + /// If a FieldMask object is not present in a get operation, the + /// operation applies to all fields (as if a FieldMask of all fields + /// had been specified). + /// + /// Note that a field mask does not necessarily apply to the + /// top-level response message. In case of a REST get operation, the + /// field mask applies directly to the response, but in case of a REST + /// list operation, the mask instead applies to each individual message + /// in the returned resource list. In case of a REST custom method, + /// other definitions may be used. Where the mask applies will be + /// clearly documented together with its declaration in the API. In + /// any case, the effect on the returned resource/resources is required + /// behavior for APIs. + /// + /// # Field Masks in Update Operations + /// + /// A field mask in update operations specifies which fields of the + /// targeted resource are going to be updated. The API is required + /// to only change the values of the fields as specified in the mask + /// and leave the others untouched. If a resource is passed in to + /// describe the updated values, the API ignores the values of all + /// fields not covered by the mask. + /// + /// If a repeated field is specified for an update operation, new values will + /// be appended to the existing repeated field in the target resource. Note that + /// a repeated field is only allowed in the last position of a `paths` string. + /// + /// If a sub-message is specified in the last position of the field mask for an + /// update operation, then new value will be merged into the existing sub-message + /// in the target resource. + /// + /// For example, given the target message: + /// + /// f { + /// b { + /// d: 1 + /// x: 2 + /// } + /// c: [1] + /// } + /// + /// And an update message: + /// + /// f { + /// b { + /// d: 10 + /// } + /// c: [2] + /// } + /// + /// then if the field mask is: + /// + /// paths: ["f.b", "f.c"] + /// + /// then the result will be: + /// + /// f { + /// b { + /// d: 10 + /// x: 2 + /// } + /// c: [1, 2] + /// } + /// + /// An implementation may provide options to override this default behavior for + /// repeated and message fields. + /// + /// In order to reset a field's value to the default, the field must + /// be in the mask and set to the default value in the provided resource. + /// Hence, in order to reset all fields of a resource, provide a default + /// instance of the resource and set all fields in the mask, or do + /// not provide a mask as described below. + /// + /// If a field mask is not present on update, the operation applies to + /// all fields (as if a field mask of all fields has been specified). + /// Note that in the presence of schema evolution, this may mean that + /// fields the client does not know and has therefore not filled into + /// the request will be reset to their default. If this is unwanted + /// behavior, a specific service may require a client to always specify + /// a field mask, producing an error if not. + /// + /// As with get operations, the location of the resource which + /// describes the updated values in the request message depends on the + /// operation kind. In any case, the effect of the field mask is + /// required to be honored by the API. + /// + /// ## Considerations for HTTP REST + /// + /// The HTTP kind of an update operation which uses a field mask must + /// be set to PATCH instead of PUT in order to satisfy HTTP semantics + /// (PUT must only be used for full updates). + /// + /// # JSON Encoding of Field Masks + /// + /// In JSON, a field mask is encoded as a single string where paths are + /// separated by a comma. Fields name in each path are converted + /// to/from lower-camel naming conventions. + /// + /// As an example, consider the following message declarations: + /// + /// message Profile { + /// User user = 1; + /// Photo photo = 2; + /// } + /// message User { + /// string display_name = 1; + /// string address = 2; + /// } + /// + /// In proto a field mask for `Profile` may look as such: + /// + /// mask { + /// paths: "user.display_name" + /// paths: "photo" + /// } + /// + /// In JSON, the same mask is represented as below: + /// + /// { + /// mask: "user.displayName,photo" + /// } + /// + /// # Field Masks and Oneof Fields + /// + /// Field masks treat fields in oneofs just as regular fields. Consider the + /// following message: + /// + /// message SampleMessage { + /// oneof test_oneof { + /// string name = 4; + /// SubMessage sub_message = 9; + /// } + /// } + /// + /// The field mask can be: + /// + /// mask { + /// paths: "name" + /// } + /// + /// Or: + /// + /// mask { + /// paths: "sub_message" + /// } + /// + /// Note that oneof type names ("test_oneof" in this case) cannot be used in + /// paths. + /// + /// ## Field Mask Verification + /// + /// 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 unmappable. + /// + public sealed partial class FieldMask : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new FieldMask()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.WellKnownTypes.FieldMaskReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FieldMask() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FieldMask(FieldMask other) : this() { + paths_ = other.paths_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FieldMask Clone() { + return new FieldMask(this); + } + + /// Field number for the "paths" field. + public const int PathsFieldNumber = 1; + private static readonly pb::FieldCodec _repeated_paths_codec + = pb::FieldCodec.ForString(10); + private readonly pbc::RepeatedField paths_ = new pbc::RepeatedField(); + /// + /// The set of field mask paths. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Paths { + get { return paths_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as FieldMask); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(FieldMask other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!paths_.Equals(other.paths_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + hash ^= paths_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + paths_.WriteTo(output, _repeated_paths_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + paths_.WriteTo(ref output, _repeated_paths_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + size += paths_.CalculateSize(_repeated_paths_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(FieldMask other) { + if (other == null) { + return; + } + paths_.Add(other.paths_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + paths_.AddEntriesFrom(input, _repeated_paths_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + paths_.AddEntriesFrom(ref input, _repeated_paths_codec); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/WellKnownTypes/TimeExtensions.cs b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/WellKnownTypes/TimeExtensions.cs new file mode 100644 index 0000000..8b63d63 --- /dev/null +++ b/tools/env-vars-generator/protobuf/csharp/src/Google.Protobuf/WellKnownTypes/TimeExtensions.cs @@ -0,0 +1,76 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; + +namespace Google.Protobuf.WellKnownTypes +{ + /// + /// Extension methods on BCL time-related types, converting to protobuf types. + /// + public static class TimeExtensions + { + /// + /// Converts the given to a . + /// + /// The date and time to convert to a timestamp. + /// The value has a other than Utc. + /// The converted timestamp. + public static Timestamp ToTimestamp(this DateTime dateTime) + { + return Timestamp.FromDateTime(dateTime); + } + + /// + /// Converts the given to a + /// + /// The offset is taken into consideration when converting the value (so the same instant in time + /// is represented) but is not a separate part of the resulting value. In other words, there is no + /// roundtrip operation to retrieve the original DateTimeOffset. + /// The date and time (with UTC offset) to convert to a timestamp. + /// The converted timestamp. + public static Timestamp ToTimestamp(this DateTimeOffset dateTimeOffset) + { + return Timestamp.FromDateTimeOffset(dateTimeOffset); + } + + /// + /// Converts the given to a . + /// + /// The time span to convert. + /// The converted duration. + public static Duration ToDuration(this TimeSpan timeSpan) + { + return Duration.FromTimeSpan(timeSpan); + } + } +} diff --git a/tools/env-vars-generator/protobuf/examples/ListPeople.java b/tools/env-vars-generator/protobuf/examples/ListPeople.java new file mode 100644 index 0000000..ab07b79 --- /dev/null +++ b/tools/env-vars-generator/protobuf/examples/ListPeople.java @@ -0,0 +1,53 @@ +// See README.txt for information and build instructions. + +import com.example.tutorial.protos.AddressBook; +import com.example.tutorial.protos.Person; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.PrintStream; + +class ListPeople { + // Iterates though all people in the AddressBook and prints info about them. + static void Print(AddressBook addressBook) { + for (Person person: addressBook.getPeopleList()) { + System.out.println("Person ID: " + person.getId()); + System.out.println(" Name: " + person.getName()); + if (!person.getEmail().isEmpty()) { + System.out.println(" E-mail address: " + person.getEmail()); + } + + for (Person.PhoneNumber phoneNumber : person.getPhonesList()) { + switch (phoneNumber.getType()) { + case MOBILE: + System.out.print(" Mobile phone #: "); + break; + case HOME: + System.out.print(" Home phone #: "); + break; + case WORK: + System.out.print(" Work phone #: "); + break; + default: + System.out.println(" Unknown phone #: "); + break; + } + System.out.println(phoneNumber.getNumber()); + } + } + } + + // Main function: Reads the entire address book from a file and prints all + // the information inside. + public static void main(String[] args) throws Exception { + if (args.length != 1) { + System.err.println("Usage: ListPeople ADDRESS_BOOK_FILE"); + System.exit(-1); + } + + // Read the existing address book. + AddressBook addressBook = + AddressBook.parseFrom(new FileInputStream(args[0])); + + Print(addressBook); + } +} diff --git a/tools/env-vars-generator/protobuf/examples/list_people.cc b/tools/env-vars-generator/protobuf/examples/list_people.cc new file mode 100644 index 0000000..b309c59 --- /dev/null +++ b/tools/env-vars-generator/protobuf/examples/list_people.cc @@ -0,0 +1,79 @@ +// See README.txt for information and build instructions. + +#include +#include +#include +#include + +#include "addressbook.pb.h" + +using namespace std; + +using google::protobuf::util::TimeUtil; + +// Iterates though all people in the AddressBook and prints info about them. +void ListPeople(const tutorial::AddressBook& address_book) { + for (int i = 0; i < address_book.people_size(); i++) { + const tutorial::Person& person = address_book.people(i); + + cout << "Person ID: " << person.id() << endl; + cout << " Name: " << person.name() << endl; + if (person.email() != "") { + cout << " E-mail address: " << person.email() << endl; + } + + for (int j = 0; j < person.phones_size(); j++) { + const tutorial::Person::PhoneNumber& phone_number = person.phones(j); + + switch (phone_number.type()) { + case tutorial::Person::MOBILE: + cout << " Mobile phone #: "; + break; + case tutorial::Person::HOME: + cout << " Home phone #: "; + break; + case tutorial::Person::WORK: + cout << " Work phone #: "; + break; + default: + cout << " Unknown phone #: "; + break; + } + cout << phone_number.number() << endl; + } + if (person.has_last_updated()) { + cout << " Updated: " << TimeUtil::ToString(person.last_updated()) << endl; + } + } +} + +// Main function: Reads the entire address book from a file and prints all +// the information inside. +int main(int argc, char* argv[]) { + // Verify that the version of the library that we linked against is + // compatible with the version of the headers we compiled against. + GOOGLE_PROTOBUF_VERIFY_VERSION; + + if (argc != 2) { + cerr << "Usage: " << argv[0] << " ADDRESS_BOOK_FILE" << endl; + return -1; + } + + tutorial::AddressBook address_book; + + { + // Read the existing address book. + fstream input(argv[1], ios::in | ios::binary); + if (!address_book.ParseFromIstream(&input)) { + cerr << "Failed to parse address book." << endl; + return -1; + } + } + + ListPeople(address_book); + + // Optional: Delete all global objects allocated by libprotobuf. + google::protobuf::ShutdownProtobufLibrary(); + + return 0; +} diff --git a/tools/env-vars-generator/protobuf/fix_permissions.sh b/tools/env-vars-generator/protobuf/fix_permissions.sh new file mode 100755 index 0000000..f33c25c --- /dev/null +++ b/tools/env-vars-generator/protobuf/fix_permissions.sh @@ -0,0 +1,8 @@ +#!/bin/bash +for file in $(find . -type f); do + if [ "$(head -c 2 $file)" == "#!" ]; then + chmod u+x $file + else + chmod a-x $file + fi +done diff --git a/tools/env-vars-generator/protobuf/global.json b/tools/env-vars-generator/protobuf/global.json new file mode 100644 index 0000000..ade0252 --- /dev/null +++ b/tools/env-vars-generator/protobuf/global.json @@ -0,0 +1,6 @@ +{ + "sdk": { + "version": "6.0.100", + "rollForward": "latestMinor" + } +} diff --git a/tools/env-vars-generator/protobuf/java/core/pom.xml b/tools/env-vars-generator/protobuf/java/core/pom.xml new file mode 100644 index 0000000..ce068ee --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/pom.xml @@ -0,0 +1,158 @@ + + + 4.0.0 + + com.google.protobuf + protobuf-parent + 3.19.4 + + + protobuf-java + bundle + + Protocol Buffers [Core] + + Core Protocol Buffers library. Protocol Buffers are a way of encoding structured data in an + efficient yet extensible format. + + + + + junit + junit + test + + + org.easymock + easymock + test + + + com.google.guava + guava + test + + + com.google.truth + truth + test + + + + + + + + ${protobuf.source.dir} + + google/protobuf/any.proto + google/protobuf/api.proto + google/protobuf/descriptor.proto + google/protobuf/duration.proto + google/protobuf/empty.proto + google/protobuf/field_mask.proto + google/protobuf/source_context.proto + google/protobuf/struct.proto + google/protobuf/timestamp.proto + google/protobuf/type.proto + google/protobuf/wrappers.proto + google/protobuf/compiler/plugin.proto + + + + + + ${protobuf.source.dir} + + google/protobuf/testdata/golden_message_oneof_implemented + google/protobuf/testdata/golden_packed_fields_message + + + + + + + + maven-antrun-plugin + + + + generate-sources + generate-sources + + + + + + + run + + + + + + generate-test-sources + generate-test-sources + + + + + + + run + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add-generated-sources + generate-sources + + add-source + + + + ${generated.sources.dir} + + + + + add-generated-test-sources + generate-test-sources + + add-test-source + + + + ${generated.testsources.dir} + + + + + + + + + org.apache.felix + maven-bundle-plugin + true + + + com.google.protobuf + https://developers.google.com/protocol-buffers/ + com.google.protobuf + com.google.protobuf;version=${project.version} + sun.misc;resolution:=optional,* + + + + + + + diff --git a/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/BinaryReader.java b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/BinaryReader.java new file mode 100644 index 0000000..d64574c --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/BinaryReader.java @@ -0,0 +1,1729 @@ +// 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. + +package com.google.protobuf; + +import static com.google.protobuf.WireFormat.FIXED32_SIZE; +import static com.google.protobuf.WireFormat.FIXED64_SIZE; +import static com.google.protobuf.WireFormat.WIRETYPE_END_GROUP; +import static com.google.protobuf.WireFormat.WIRETYPE_FIXED32; +import static com.google.protobuf.WireFormat.WIRETYPE_FIXED64; +import static com.google.protobuf.WireFormat.WIRETYPE_LENGTH_DELIMITED; +import static com.google.protobuf.WireFormat.WIRETYPE_START_GROUP; +import static com.google.protobuf.WireFormat.WIRETYPE_VARINT; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.List; +import java.util.Map; + +/** + * A {@link Reader} that reads from a buffer containing a message serialized with the binary + * protocol. + */ +@ExperimentalApi +abstract class BinaryReader implements Reader { + private static final int FIXED32_MULTIPLE_MASK = FIXED32_SIZE - 1; + private static final int FIXED64_MULTIPLE_MASK = FIXED64_SIZE - 1; + + /** + * Creates a new reader using the given {@code buffer} as input. + * + * @param buffer the input buffer. The buffer (including position, limit, etc.) will not be + * modified. To increment the buffer position after the read completes, use the value returned + * by {@link #getTotalBytesRead()}. + * @param bufferIsImmutable if {@code true} the reader assumes that the content of {@code buffer} + * will never change and any allocated {@link ByteString} instances will by directly wrap + * slices of {@code buffer}. + * @return the reader + */ + public static BinaryReader newInstance(ByteBuffer buffer, boolean bufferIsImmutable) { + if (buffer.hasArray()) { + // TODO(nathanmittler): Add support for unsafe operations. + return new SafeHeapReader(buffer, bufferIsImmutable); + } + // TODO(nathanmittler): Add support for direct buffers + throw new IllegalArgumentException("Direct buffers not yet supported"); + } + + /** Only allow subclassing for inner classes. */ + private BinaryReader() {} + + /** Returns the total number of bytes read so far from the input buffer. */ + public abstract int getTotalBytesRead(); + + @Override + public boolean shouldDiscardUnknownFields() { + return false; + } + + /** + * A {@link BinaryReader} implementation that operates on a heap {@link ByteBuffer}. Uses only + * safe operations on the underlying array. + */ + private static final class SafeHeapReader extends BinaryReader { + private final boolean bufferIsImmutable; + private final byte[] buffer; + private int pos; + private final int initialPos; + private int limit; + private int tag; + private int endGroupTag; + + public SafeHeapReader(ByteBuffer bytebuf, boolean bufferIsImmutable) { + this.bufferIsImmutable = bufferIsImmutable; + buffer = bytebuf.array(); + initialPos = pos = bytebuf.arrayOffset() + bytebuf.position(); + limit = bytebuf.arrayOffset() + bytebuf.limit(); + } + + private boolean isAtEnd() { + return pos == limit; + } + + @Override + public int getTotalBytesRead() { + return pos - initialPos; + } + + @Override + public int getFieldNumber() throws IOException { + if (isAtEnd()) { + return Reader.READ_DONE; + } + tag = readVarint32(); + if (tag == endGroupTag) { + return Reader.READ_DONE; + } + return WireFormat.getTagFieldNumber(tag); + } + + @Override + public int getTag() { + return tag; + } + + @Override + public boolean skipField() throws IOException { + if (isAtEnd() || tag == endGroupTag) { + return false; + } + + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_VARINT: + skipVarint(); + return true; + case WIRETYPE_FIXED64: + skipBytes(FIXED64_SIZE); + return true; + case WIRETYPE_LENGTH_DELIMITED: + skipBytes(readVarint32()); + return true; + case WIRETYPE_FIXED32: + skipBytes(FIXED32_SIZE); + return true; + case WIRETYPE_START_GROUP: + skipGroup(); + return true; + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + + @Override + public double readDouble() throws IOException { + requireWireType(WIRETYPE_FIXED64); + return Double.longBitsToDouble(readLittleEndian64()); + } + + @Override + public float readFloat() throws IOException { + requireWireType(WIRETYPE_FIXED32); + return Float.intBitsToFloat(readLittleEndian32()); + } + + @Override + public long readUInt64() throws IOException { + requireWireType(WIRETYPE_VARINT); + return readVarint64(); + } + + @Override + public long readInt64() throws IOException { + requireWireType(WIRETYPE_VARINT); + return readVarint64(); + } + + @Override + public int readInt32() throws IOException { + requireWireType(WIRETYPE_VARINT); + return readVarint32(); + } + + @Override + public long readFixed64() throws IOException { + requireWireType(WIRETYPE_FIXED64); + return readLittleEndian64(); + } + + @Override + public int readFixed32() throws IOException { + requireWireType(WIRETYPE_FIXED32); + return readLittleEndian32(); + } + + @Override + public boolean readBool() throws IOException { + requireWireType(WIRETYPE_VARINT); + return readVarint32() != 0; + } + + @Override + public String readString() throws IOException { + return readStringInternal(false); + } + + @Override + public String readStringRequireUtf8() throws IOException { + return readStringInternal(true); + } + + public String readStringInternal(boolean requireUtf8) throws IOException { + requireWireType(WIRETYPE_LENGTH_DELIMITED); + final int size = readVarint32(); + if (size == 0) { + return ""; + } + + requireBytes(size); + if (requireUtf8 && !Utf8.isValidUtf8(buffer, pos, pos + size)) { + throw InvalidProtocolBufferException.invalidUtf8(); + } + String result = new String(buffer, pos, size, Internal.UTF_8); + pos += size; + return result; + } + + @Override + public T readMessage(Class clazz, ExtensionRegistryLite extensionRegistry) + throws IOException { + requireWireType(WIRETYPE_LENGTH_DELIMITED); + return readMessage(Protobuf.getInstance().schemaFor(clazz), extensionRegistry); + } + + @Override + public T readMessageBySchemaWithCheck( + Schema schema, ExtensionRegistryLite extensionRegistry) throws IOException { + requireWireType(WIRETYPE_LENGTH_DELIMITED); + return readMessage(schema, extensionRegistry); + } + + private T readMessage(Schema schema, ExtensionRegistryLite extensionRegistry) + throws IOException { + int size = readVarint32(); + requireBytes(size); + + // Update the limit. + int prevLimit = limit; + int newLimit = pos + size; + limit = newLimit; + + try { + // Allocate and read the message. + T message = schema.newInstance(); + schema.mergeFrom(message, this, extensionRegistry); + schema.makeImmutable(message); + + if (pos != newLimit) { + throw InvalidProtocolBufferException.parseFailure(); + } + return message; + } finally { + // Restore the limit. + limit = prevLimit; + } + } + + @Override + public T readGroup(Class clazz, ExtensionRegistryLite extensionRegistry) + throws IOException { + requireWireType(WIRETYPE_START_GROUP); + return readGroup(Protobuf.getInstance().schemaFor(clazz), extensionRegistry); + } + + @Override + public T readGroupBySchemaWithCheck( + Schema schema, ExtensionRegistryLite extensionRegistry) throws IOException { + requireWireType(WIRETYPE_START_GROUP); + return readGroup(schema, extensionRegistry); + } + + private T readGroup(Schema schema, ExtensionRegistryLite extensionRegistry) + throws IOException { + int prevEndGroupTag = endGroupTag; + endGroupTag = WireFormat.makeTag(WireFormat.getTagFieldNumber(tag), WIRETYPE_END_GROUP); + + try { + // Allocate and read the message. + T message = schema.newInstance(); + schema.mergeFrom(message, this, extensionRegistry); + schema.makeImmutable(message); + + if (tag != endGroupTag) { + throw InvalidProtocolBufferException.parseFailure(); + } + return message; + } finally { + // Restore the old end group tag. + endGroupTag = prevEndGroupTag; + } + } + + @Override + public ByteString readBytes() throws IOException { + requireWireType(WIRETYPE_LENGTH_DELIMITED); + int size = readVarint32(); + if (size == 0) { + return ByteString.EMPTY; + } + + requireBytes(size); + ByteString bytes = + bufferIsImmutable + ? ByteString.wrap(buffer, pos, size) + : ByteString.copyFrom(buffer, pos, size); + pos += size; + return bytes; + } + + @Override + public int readUInt32() throws IOException { + requireWireType(WIRETYPE_VARINT); + return readVarint32(); + } + + @Override + public int readEnum() throws IOException { + requireWireType(WIRETYPE_VARINT); + return readVarint32(); + } + + @Override + public int readSFixed32() throws IOException { + requireWireType(WIRETYPE_FIXED32); + return readLittleEndian32(); + } + + @Override + public long readSFixed64() throws IOException { + requireWireType(WIRETYPE_FIXED64); + return readLittleEndian64(); + } + + @Override + public int readSInt32() throws IOException { + requireWireType(WIRETYPE_VARINT); + return CodedInputStream.decodeZigZag32(readVarint32()); + } + + @Override + public long readSInt64() throws IOException { + requireWireType(WIRETYPE_VARINT); + return CodedInputStream.decodeZigZag64(readVarint64()); + } + + @Override + public void readDoubleList(List target) throws IOException { + if (target instanceof DoubleArrayList) { + DoubleArrayList plist = (DoubleArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed64Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addDouble(Double.longBitsToDouble(readLittleEndian64_NoCheck())); + } + break; + case WIRETYPE_FIXED64: + while (true) { + plist.addDouble(readDouble()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed64Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(Double.longBitsToDouble(readLittleEndian64_NoCheck())); + } + break; + case WIRETYPE_FIXED64: + while (true) { + target.add(readDouble()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readFloatList(List target) throws IOException { + if (target instanceof FloatArrayList) { + FloatArrayList plist = (FloatArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed32Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addFloat(Float.intBitsToFloat(readLittleEndian32_NoCheck())); + } + break; + case WIRETYPE_FIXED32: + while (true) { + plist.addFloat(readFloat()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed32Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(Float.intBitsToFloat(readLittleEndian32_NoCheck())); + } + break; + case WIRETYPE_FIXED32: + while (true) { + target.add(readFloat()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readUInt64List(List target) throws IOException { + if (target instanceof LongArrayList) { + LongArrayList plist = (LongArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addLong(readVarint64()); + } + requirePosition(fieldEndPos); + break; + case WIRETYPE_VARINT: + while (true) { + plist.addLong(readUInt64()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(readVarint64()); + } + requirePosition(fieldEndPos); + break; + case WIRETYPE_VARINT: + while (true) { + target.add(readUInt64()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readInt64List(List target) throws IOException { + if (target instanceof LongArrayList) { + LongArrayList plist = (LongArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addLong(readVarint64()); + } + requirePosition(fieldEndPos); + break; + case WIRETYPE_VARINT: + while (true) { + plist.addLong(readInt64()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(readVarint64()); + } + requirePosition(fieldEndPos); + break; + case WIRETYPE_VARINT: + while (true) { + target.add(readInt64()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readInt32List(List target) throws IOException { + if (target instanceof IntArrayList) { + IntArrayList plist = (IntArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addInt(readVarint32()); + } + requirePosition(fieldEndPos); + break; + case WIRETYPE_VARINT: + while (true) { + plist.addInt(readInt32()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(readVarint32()); + } + requirePosition(fieldEndPos); + break; + case WIRETYPE_VARINT: + while (true) { + target.add(readInt32()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readFixed64List(List target) throws IOException { + if (target instanceof LongArrayList) { + LongArrayList plist = (LongArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed64Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addLong(readLittleEndian64_NoCheck()); + } + break; + case WIRETYPE_FIXED64: + while (true) { + plist.addLong(readFixed64()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed64Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(readLittleEndian64_NoCheck()); + } + break; + case WIRETYPE_FIXED64: + while (true) { + target.add(readFixed64()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readFixed32List(List target) throws IOException { + if (target instanceof IntArrayList) { + IntArrayList plist = (IntArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed32Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addInt(readLittleEndian32_NoCheck()); + } + break; + case WIRETYPE_FIXED32: + while (true) { + plist.addInt(readFixed32()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed32Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(readLittleEndian32_NoCheck()); + } + break; + case WIRETYPE_FIXED32: + while (true) { + target.add(readFixed32()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readBoolList(List target) throws IOException { + if (target instanceof BooleanArrayList) { + BooleanArrayList plist = (BooleanArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addBoolean(readVarint32() != 0); + } + requirePosition(fieldEndPos); + break; + case WIRETYPE_VARINT: + while (true) { + plist.addBoolean(readBool()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(readVarint32() != 0); + } + requirePosition(fieldEndPos); + break; + case WIRETYPE_VARINT: + while (true) { + target.add(readBool()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readStringList(List target) throws IOException { + readStringListInternal(target, false); + } + + @Override + public void readStringListRequireUtf8(List target) throws IOException { + readStringListInternal(target, true); + } + + public void readStringListInternal(List target, boolean requireUtf8) + throws IOException { + if (WireFormat.getTagWireType(tag) != WIRETYPE_LENGTH_DELIMITED) { + throw InvalidProtocolBufferException.invalidWireType(); + } + + if (target instanceof LazyStringList && !requireUtf8) { + LazyStringList lazyList = (LazyStringList) target; + while (true) { + lazyList.add(readBytes()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + } else { + while (true) { + target.add(readStringInternal(requireUtf8)); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + } + } + + @Override + public void readMessageList( + List target, Class targetType, ExtensionRegistryLite extensionRegistry) + throws IOException { + final Schema schema = Protobuf.getInstance().schemaFor(targetType); + readMessageList(target, schema, extensionRegistry); + } + + @Override + public void readMessageList( + List target, Schema schema, ExtensionRegistryLite extensionRegistry) + throws IOException { + if (WireFormat.getTagWireType(tag) != WIRETYPE_LENGTH_DELIMITED) { + throw InvalidProtocolBufferException.invalidWireType(); + } + final int listTag = tag; + while (true) { + target.add(readMessage(schema, extensionRegistry)); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != listTag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + } + + @Override + public void readGroupList( + List target, Class targetType, ExtensionRegistryLite extensionRegistry) + throws IOException { + final Schema schema = Protobuf.getInstance().schemaFor(targetType); + readGroupList(target, schema, extensionRegistry); + } + + @Override + public void readGroupList( + List target, Schema schema, ExtensionRegistryLite extensionRegistry) + throws IOException { + if (WireFormat.getTagWireType(tag) != WIRETYPE_START_GROUP) { + throw InvalidProtocolBufferException.invalidWireType(); + } + final int listTag = tag; + while (true) { + target.add(readGroup(schema, extensionRegistry)); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != listTag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + } + + @Override + public void readBytesList(List target) throws IOException { + if (WireFormat.getTagWireType(tag) != WIRETYPE_LENGTH_DELIMITED) { + throw InvalidProtocolBufferException.invalidWireType(); + } + + while (true) { + target.add(readBytes()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + } + + @Override + public void readUInt32List(List target) throws IOException { + if (target instanceof IntArrayList) { + IntArrayList plist = (IntArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addInt(readVarint32()); + } + break; + case WIRETYPE_VARINT: + while (true) { + plist.addInt(readUInt32()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(readVarint32()); + } + break; + case WIRETYPE_VARINT: + while (true) { + target.add(readUInt32()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readEnumList(List target) throws IOException { + if (target instanceof IntArrayList) { + IntArrayList plist = (IntArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addInt(readVarint32()); + } + break; + case WIRETYPE_VARINT: + while (true) { + plist.addInt(readEnum()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(readVarint32()); + } + break; + case WIRETYPE_VARINT: + while (true) { + target.add(readEnum()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readSFixed32List(List target) throws IOException { + if (target instanceof IntArrayList) { + IntArrayList plist = (IntArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed32Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addInt(readLittleEndian32_NoCheck()); + } + break; + case WIRETYPE_FIXED32: + while (true) { + plist.addInt(readSFixed32()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed32Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(readLittleEndian32_NoCheck()); + } + break; + case WIRETYPE_FIXED32: + while (true) { + target.add(readSFixed32()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readSFixed64List(List target) throws IOException { + if (target instanceof LongArrayList) { + LongArrayList plist = (LongArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed64Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addLong(readLittleEndian64_NoCheck()); + } + break; + case WIRETYPE_FIXED64: + while (true) { + plist.addLong(readSFixed64()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed64Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(readLittleEndian64_NoCheck()); + } + break; + case WIRETYPE_FIXED64: + while (true) { + target.add(readSFixed64()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readSInt32List(List target) throws IOException { + if (target instanceof IntArrayList) { + IntArrayList plist = (IntArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addInt(CodedInputStream.decodeZigZag32(readVarint32())); + } + break; + case WIRETYPE_VARINT: + while (true) { + plist.addInt(readSInt32()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(CodedInputStream.decodeZigZag32(readVarint32())); + } + break; + case WIRETYPE_VARINT: + while (true) { + target.add(readSInt32()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readSInt64List(List target) throws IOException { + if (target instanceof LongArrayList) { + LongArrayList plist = (LongArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addLong(CodedInputStream.decodeZigZag64(readVarint64())); + } + break; + case WIRETYPE_VARINT: + while (true) { + plist.addLong(readSInt64()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(CodedInputStream.decodeZigZag64(readVarint64())); + } + break; + case WIRETYPE_VARINT: + while (true) { + target.add(readSInt64()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @SuppressWarnings("unchecked") + @Override + public void readMap( + Map target, + MapEntryLite.Metadata metadata, + ExtensionRegistryLite extensionRegistry) + throws IOException { + requireWireType(WIRETYPE_LENGTH_DELIMITED); + int size = readVarint32(); + requireBytes(size); + + // Update the limit. + int prevLimit = limit; + int newLimit = pos + size; + limit = newLimit; + + try { + K key = metadata.defaultKey; + V value = metadata.defaultValue; + while (true) { + int number = getFieldNumber(); + if (number == READ_DONE) { + break; + } + try { + switch (number) { + case 1: + key = (K) readField(metadata.keyType, null, null); + break; + case 2: + value = + (V) + readField( + metadata.valueType, + metadata.defaultValue.getClass(), + extensionRegistry); + break; + default: + if (!skipField()) { + throw new InvalidProtocolBufferException("Unable to parse map entry."); + } + break; + } + } catch (InvalidProtocolBufferException.InvalidWireTypeException ignore) { + // the type doesn't match, skip the field. + if (!skipField()) { + throw new InvalidProtocolBufferException("Unable to parse map entry."); + } + } + } + target.put(key, value); + } finally { + // Restore the limit. + limit = prevLimit; + } + } + + private Object readField( + WireFormat.FieldType fieldType, + Class messageType, + ExtensionRegistryLite extensionRegistry) + throws IOException { + switch (fieldType) { + case BOOL: + return readBool(); + case BYTES: + return readBytes(); + case DOUBLE: + return readDouble(); + case ENUM: + return readEnum(); + case FIXED32: + return readFixed32(); + case FIXED64: + return readFixed64(); + case FLOAT: + return readFloat(); + case INT32: + return readInt32(); + case INT64: + return readInt64(); + case MESSAGE: + return readMessage(messageType, extensionRegistry); + case SFIXED32: + return readSFixed32(); + case SFIXED64: + return readSFixed64(); + case SINT32: + return readSInt32(); + case SINT64: + return readSInt64(); + case STRING: + return readStringRequireUtf8(); + case UINT32: + return readUInt32(); + case UINT64: + return readUInt64(); + default: + throw new RuntimeException("unsupported field type."); + } + } + + /** Read a raw Varint from the stream. If larger than 32 bits, discard the upper bits. */ + private int readVarint32() throws IOException { + // See implementation notes for readRawVarint64 + int i = pos; + + if (limit == pos) { + throw InvalidProtocolBufferException.truncatedMessage(); + } + + int x; + if ((x = buffer[i++]) >= 0) { + pos = i; + return x; + } else if (limit - i < 9) { + return (int) readVarint64SlowPath(); + } else if ((x ^= (buffer[i++] << 7)) < 0) { + x ^= (~0 << 7); + } else if ((x ^= (buffer[i++] << 14)) >= 0) { + x ^= (~0 << 7) ^ (~0 << 14); + } else if ((x ^= (buffer[i++] << 21)) < 0) { + x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21); + } else { + int y = buffer[i++]; + x ^= y << 28; + x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21) ^ (~0 << 28); + if (y < 0 + && buffer[i++] < 0 + && buffer[i++] < 0 + && buffer[i++] < 0 + && buffer[i++] < 0 + && buffer[i++] < 0) { + throw InvalidProtocolBufferException.malformedVarint(); + } + } + pos = i; + return x; + } + + public long readVarint64() throws IOException { + // Implementation notes: + // + // Optimized for one-byte values, expected to be common. + // The particular code below was selected from various candidates + // empirically, by winning VarintBenchmark. + // + // Sign extension of (signed) Java bytes is usually a nuisance, but + // we exploit it here to more easily obtain the sign of bytes read. + // Instead of cleaning up the sign extension bits by masking eagerly, + // we delay until we find the final (positive) byte, when we clear all + // accumulated bits with one xor. We depend on javac to constant fold. + int i = pos; + + if (limit == i) { + throw InvalidProtocolBufferException.truncatedMessage(); + } + + final byte[] buffer = this.buffer; + long x; + int y; + if ((y = buffer[i++]) >= 0) { + pos = i; + return y; + } else if (limit - i < 9) { + return readVarint64SlowPath(); + } else if ((y ^= (buffer[i++] << 7)) < 0) { + x = y ^ (~0 << 7); + } else if ((y ^= (buffer[i++] << 14)) >= 0) { + x = y ^ ((~0 << 7) ^ (~0 << 14)); + } else if ((y ^= (buffer[i++] << 21)) < 0) { + x = y ^ ((~0 << 7) ^ (~0 << 14) ^ (~0 << 21)); + } else if ((x = y ^ ((long) buffer[i++] << 28)) >= 0L) { + x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28); + } else if ((x ^= ((long) buffer[i++] << 35)) < 0L) { + x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35); + } else if ((x ^= ((long) buffer[i++] << 42)) >= 0L) { + x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42); + } else if ((x ^= ((long) buffer[i++] << 49)) < 0L) { + x ^= + (~0L << 7) + ^ (~0L << 14) + ^ (~0L << 21) + ^ (~0L << 28) + ^ (~0L << 35) + ^ (~0L << 42) + ^ (~0L << 49); + } else { + x ^= ((long) buffer[i++] << 56); + x ^= + (~0L << 7) + ^ (~0L << 14) + ^ (~0L << 21) + ^ (~0L << 28) + ^ (~0L << 35) + ^ (~0L << 42) + ^ (~0L << 49) + ^ (~0L << 56); + if (x < 0L) { + if (buffer[i++] < 0L) { + throw InvalidProtocolBufferException.malformedVarint(); + } + } + } + pos = i; + return x; + } + + private long readVarint64SlowPath() throws IOException { + long result = 0; + for (int shift = 0; shift < 64; shift += 7) { + final byte b = readByte(); + result |= (long) (b & 0x7F) << shift; + if ((b & 0x80) == 0) { + return result; + } + } + throw InvalidProtocolBufferException.malformedVarint(); + } + + private byte readByte() throws IOException { + if (pos == limit) { + throw InvalidProtocolBufferException.truncatedMessage(); + } + return buffer[pos++]; + } + + private int readLittleEndian32() throws IOException { + requireBytes(FIXED32_SIZE); + return readLittleEndian32_NoCheck(); + } + + private long readLittleEndian64() throws IOException { + requireBytes(FIXED64_SIZE); + return readLittleEndian64_NoCheck(); + } + + private int readLittleEndian32_NoCheck() { + int p = pos; + final byte[] buffer = this.buffer; + pos = p + FIXED32_SIZE; + return (((buffer[p] & 0xff)) + | ((buffer[p + 1] & 0xff) << 8) + | ((buffer[p + 2] & 0xff) << 16) + | ((buffer[p + 3] & 0xff) << 24)); + } + + private long readLittleEndian64_NoCheck() { + int p = pos; + final byte[] buffer = this.buffer; + pos = p + FIXED64_SIZE; + return (((buffer[p] & 0xffL)) + | ((buffer[p + 1] & 0xffL) << 8) + | ((buffer[p + 2] & 0xffL) << 16) + | ((buffer[p + 3] & 0xffL) << 24) + | ((buffer[p + 4] & 0xffL) << 32) + | ((buffer[p + 5] & 0xffL) << 40) + | ((buffer[p + 6] & 0xffL) << 48) + | ((buffer[p + 7] & 0xffL) << 56)); + } + + private void skipVarint() throws IOException { + if (limit - pos >= 10) { + final byte[] buffer = this.buffer; + int p = pos; + for (int i = 0; i < 10; i++) { + if (buffer[p++] >= 0) { + pos = p; + return; + } + } + } + skipVarintSlowPath(); + } + + private void skipVarintSlowPath() throws IOException { + for (int i = 0; i < 10; i++) { + if (readByte() >= 0) { + return; + } + } + throw InvalidProtocolBufferException.malformedVarint(); + } + + private void skipBytes(final int size) throws IOException { + requireBytes(size); + + pos += size; + } + + private void skipGroup() throws IOException { + int prevEndGroupTag = endGroupTag; + endGroupTag = WireFormat.makeTag(WireFormat.getTagFieldNumber(tag), WIRETYPE_END_GROUP); + while (true) { + if (getFieldNumber() == READ_DONE || !skipField()) { + break; + } + } + if (tag != endGroupTag) { + throw InvalidProtocolBufferException.parseFailure(); + } + endGroupTag = prevEndGroupTag; + } + + private void requireBytes(int size) throws IOException { + if (size < 0 || size > (limit - pos)) { + throw InvalidProtocolBufferException.truncatedMessage(); + } + } + + private void requireWireType(int requiredWireType) throws IOException { + if (WireFormat.getTagWireType(tag) != requiredWireType) { + throw InvalidProtocolBufferException.invalidWireType(); + } + } + + private void verifyPackedFixed64Length(int bytes) throws IOException { + requireBytes(bytes); + if ((bytes & FIXED64_MULTIPLE_MASK) != 0) { + // Require that the number of bytes be a multiple of 8. + throw InvalidProtocolBufferException.parseFailure(); + } + } + + private void verifyPackedFixed32Length(int bytes) throws IOException { + requireBytes(bytes); + if ((bytes & FIXED32_MULTIPLE_MASK) != 0) { + // Require that the number of bytes be a multiple of 4. + throw InvalidProtocolBufferException.parseFailure(); + } + } + + private void requirePosition(int expectedPosition) throws IOException { + if (pos != expectedPosition) { + throw InvalidProtocolBufferException.truncatedMessage(); + } + } + } +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/BlockingRpcChannel.java b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/BlockingRpcChannel.java new file mode 100644 index 0000000..8af8005 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/BlockingRpcChannel.java @@ -0,0 +1,51 @@ +// 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. + +package com.google.protobuf; + +/** + * Abstract interface for a blocking RPC channel. {@code BlockingRpcChannel} is the blocking + * equivalent to {@link RpcChannel}. + * + * @author kenton@google.com Kenton Varda + * @author cpovirk@google.com Chris Povirk + */ +public interface BlockingRpcChannel { + /** + * Call the given method of the remote service and blocks until it returns. {@code + * callBlockingMethod()} is the blocking equivalent to {@link RpcChannel#callMethod}. + */ + Message callBlockingMethod( + Descriptors.MethodDescriptor method, + RpcController controller, + Message request, + Message responsePrototype) + throws ServiceException; +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/CodedOutputStreamWriter.java b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/CodedOutputStreamWriter.java new file mode 100644 index 0000000..0d1983c --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/CodedOutputStreamWriter.java @@ -0,0 +1,691 @@ +// 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. + +package com.google.protobuf; + +import static com.google.protobuf.Internal.checkNotNull; +import static com.google.protobuf.WireFormat.WIRETYPE_LENGTH_DELIMITED; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +/** An adapter between the {@link Writer} interface and {@link CodedOutputStream}. */ +@ExperimentalApi +final class CodedOutputStreamWriter implements Writer { + private final CodedOutputStream output; + + public static CodedOutputStreamWriter forCodedOutput(CodedOutputStream output) { + if (output.wrapper != null) { + return output.wrapper; + } + return new CodedOutputStreamWriter(output); + } + + private CodedOutputStreamWriter(CodedOutputStream output) { + this.output = checkNotNull(output, "output"); + this.output.wrapper = this; + } + + @Override + public FieldOrder fieldOrder() { + return FieldOrder.ASCENDING; + } + + public int getTotalBytesWritten() { + return output.getTotalBytesWritten(); + } + + @Override + public void writeSFixed32(int fieldNumber, int value) throws IOException { + output.writeSFixed32(fieldNumber, value); + } + + @Override + public void writeInt64(int fieldNumber, long value) throws IOException { + output.writeInt64(fieldNumber, value); + } + + @Override + public void writeSFixed64(int fieldNumber, long value) throws IOException { + output.writeSFixed64(fieldNumber, value); + } + + @Override + public void writeFloat(int fieldNumber, float value) throws IOException { + output.writeFloat(fieldNumber, value); + } + + @Override + public void writeDouble(int fieldNumber, double value) throws IOException { + output.writeDouble(fieldNumber, value); + } + + @Override + public void writeEnum(int fieldNumber, int value) throws IOException { + output.writeEnum(fieldNumber, value); + } + + @Override + public void writeUInt64(int fieldNumber, long value) throws IOException { + output.writeUInt64(fieldNumber, value); + } + + @Override + public void writeInt32(int fieldNumber, int value) throws IOException { + output.writeInt32(fieldNumber, value); + } + + @Override + public void writeFixed64(int fieldNumber, long value) throws IOException { + output.writeFixed64(fieldNumber, value); + } + + @Override + public void writeFixed32(int fieldNumber, int value) throws IOException { + output.writeFixed32(fieldNumber, value); + } + + @Override + public void writeBool(int fieldNumber, boolean value) throws IOException { + output.writeBool(fieldNumber, value); + } + + @Override + public void writeString(int fieldNumber, String value) throws IOException { + output.writeString(fieldNumber, value); + } + + @Override + public void writeBytes(int fieldNumber, ByteString value) throws IOException { + output.writeBytes(fieldNumber, value); + } + + @Override + public void writeUInt32(int fieldNumber, int value) throws IOException { + output.writeUInt32(fieldNumber, value); + } + + @Override + public void writeSInt32(int fieldNumber, int value) throws IOException { + output.writeSInt32(fieldNumber, value); + } + + @Override + public void writeSInt64(int fieldNumber, long value) throws IOException { + output.writeSInt64(fieldNumber, value); + } + + @Override + public void writeMessage(int fieldNumber, Object value) throws IOException { + output.writeMessage(fieldNumber, (MessageLite) value); + } + + @Override + public void writeMessage(int fieldNumber, Object value, Schema schema) throws IOException { + output.writeMessage(fieldNumber, (MessageLite) value, schema); + } + + @Override + public void writeGroup(int fieldNumber, Object value) throws IOException { + output.writeGroup(fieldNumber, (MessageLite) value); + } + + @Override + public void writeGroup(int fieldNumber, Object value, Schema schema) throws IOException { + output.writeGroup(fieldNumber, (MessageLite) value, schema); + } + + @Override + public void writeStartGroup(int fieldNumber) throws IOException { + output.writeTag(fieldNumber, WireFormat.WIRETYPE_START_GROUP); + } + + @Override + public void writeEndGroup(int fieldNumber) throws IOException { + output.writeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP); + } + + @Override + public final void writeMessageSetItem(int fieldNumber, Object value) throws IOException { + if (value instanceof ByteString) { + output.writeRawMessageSetExtension(fieldNumber, (ByteString) value); + } else { + output.writeMessageSetExtension(fieldNumber, (MessageLite) value); + } + } + + @Override + public void writeInt32List(int fieldNumber, List value, boolean packed) + throws IOException { + if (packed) { + output.writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); + + // Compute and write the length of the data. + int dataSize = 0; + for (int i = 0; i < value.size(); ++i) { + dataSize += CodedOutputStream.computeInt32SizeNoTag(value.get(i)); + } + output.writeUInt32NoTag(dataSize); + + // Write the data itself, without any tags. + for (int i = 0; i < value.size(); ++i) { + output.writeInt32NoTag(value.get(i)); + } + } else { + for (int i = 0; i < value.size(); ++i) { + output.writeInt32(fieldNumber, value.get(i)); + } + } + } + + @Override + public void writeFixed32List(int fieldNumber, List value, boolean packed) + throws IOException { + if (packed) { + output.writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); + + // Compute and write the length of the data. + int dataSize = 0; + for (int i = 0; i < value.size(); ++i) { + dataSize += CodedOutputStream.computeFixed32SizeNoTag(value.get(i)); + } + output.writeUInt32NoTag(dataSize); + + // Write the data itself, without any tags. + for (int i = 0; i < value.size(); ++i) { + output.writeFixed32NoTag(value.get(i)); + } + } else { + for (int i = 0; i < value.size(); ++i) { + output.writeFixed32(fieldNumber, value.get(i)); + } + } + } + + @Override + public void writeInt64List(int fieldNumber, List value, boolean packed) throws IOException { + if (packed) { + output.writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); + + // Compute and write the length of the data. + int dataSize = 0; + for (int i = 0; i < value.size(); ++i) { + dataSize += CodedOutputStream.computeInt64SizeNoTag(value.get(i)); + } + output.writeUInt32NoTag(dataSize); + + // Write the data itself, without any tags. + for (int i = 0; i < value.size(); ++i) { + output.writeInt64NoTag(value.get(i)); + } + } else { + for (int i = 0; i < value.size(); ++i) { + output.writeInt64(fieldNumber, value.get(i)); + } + } + } + + @Override + public void writeUInt64List(int fieldNumber, List value, boolean packed) + throws IOException { + if (packed) { + output.writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); + + // Compute and write the length of the data. + int dataSize = 0; + for (int i = 0; i < value.size(); ++i) { + dataSize += CodedOutputStream.computeUInt64SizeNoTag(value.get(i)); + } + output.writeUInt32NoTag(dataSize); + + // Write the data itself, without any tags. + for (int i = 0; i < value.size(); ++i) { + output.writeUInt64NoTag(value.get(i)); + } + } else { + for (int i = 0; i < value.size(); ++i) { + output.writeUInt64(fieldNumber, value.get(i)); + } + } + } + + @Override + public void writeFixed64List(int fieldNumber, List value, boolean packed) + throws IOException { + if (packed) { + output.writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); + + // Compute and write the length of the data. + int dataSize = 0; + for (int i = 0; i < value.size(); ++i) { + dataSize += CodedOutputStream.computeFixed64SizeNoTag(value.get(i)); + } + output.writeUInt32NoTag(dataSize); + + // Write the data itself, without any tags. + for (int i = 0; i < value.size(); ++i) { + output.writeFixed64NoTag(value.get(i)); + } + } else { + for (int i = 0; i < value.size(); ++i) { + output.writeFixed64(fieldNumber, value.get(i)); + } + } + } + + @Override + public void writeFloatList(int fieldNumber, List value, boolean packed) + throws IOException { + if (packed) { + output.writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); + + // Compute and write the length of the data. + int dataSize = 0; + for (int i = 0; i < value.size(); ++i) { + dataSize += CodedOutputStream.computeFloatSizeNoTag(value.get(i)); + } + output.writeUInt32NoTag(dataSize); + + // Write the data itself, without any tags. + for (int i = 0; i < value.size(); ++i) { + output.writeFloatNoTag(value.get(i)); + } + } else { + for (int i = 0; i < value.size(); ++i) { + output.writeFloat(fieldNumber, value.get(i)); + } + } + } + + @Override + public void writeDoubleList(int fieldNumber, List value, boolean packed) + throws IOException { + if (packed) { + output.writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); + + // Compute and write the length of the data. + int dataSize = 0; + for (int i = 0; i < value.size(); ++i) { + dataSize += CodedOutputStream.computeDoubleSizeNoTag(value.get(i)); + } + output.writeUInt32NoTag(dataSize); + + // Write the data itself, without any tags. + for (int i = 0; i < value.size(); ++i) { + output.writeDoubleNoTag(value.get(i)); + } + } else { + for (int i = 0; i < value.size(); ++i) { + output.writeDouble(fieldNumber, value.get(i)); + } + } + } + + @Override + public void writeEnumList(int fieldNumber, List value, boolean packed) + throws IOException { + if (packed) { + output.writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); + + // Compute and write the length of the data. + int dataSize = 0; + for (int i = 0; i < value.size(); ++i) { + dataSize += CodedOutputStream.computeEnumSizeNoTag(value.get(i)); + } + output.writeUInt32NoTag(dataSize); + + // Write the data itself, without any tags. + for (int i = 0; i < value.size(); ++i) { + output.writeEnumNoTag(value.get(i)); + } + } else { + for (int i = 0; i < value.size(); ++i) { + output.writeEnum(fieldNumber, value.get(i)); + } + } + } + + @Override + public void writeBoolList(int fieldNumber, List value, boolean packed) + throws IOException { + if (packed) { + output.writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); + + // Compute and write the length of the data. + int dataSize = 0; + for (int i = 0; i < value.size(); ++i) { + dataSize += CodedOutputStream.computeBoolSizeNoTag(value.get(i)); + } + output.writeUInt32NoTag(dataSize); + + // Write the data itself, without any tags. + for (int i = 0; i < value.size(); ++i) { + output.writeBoolNoTag(value.get(i)); + } + } else { + for (int i = 0; i < value.size(); ++i) { + output.writeBool(fieldNumber, value.get(i)); + } + } + } + + @Override + public void writeStringList(int fieldNumber, List value) throws IOException { + if (value instanceof LazyStringList) { + final LazyStringList lazyList = (LazyStringList) value; + for (int i = 0; i < value.size(); ++i) { + writeLazyString(fieldNumber, lazyList.getRaw(i)); + } + } else { + for (int i = 0; i < value.size(); ++i) { + output.writeString(fieldNumber, value.get(i)); + } + } + } + + private void writeLazyString(int fieldNumber, Object value) throws IOException { + if (value instanceof String) { + output.writeString(fieldNumber, (String) value); + } else { + output.writeBytes(fieldNumber, (ByteString) value); + } + } + + @Override + public void writeBytesList(int fieldNumber, List value) throws IOException { + for (int i = 0; i < value.size(); ++i) { + output.writeBytes(fieldNumber, value.get(i)); + } + } + + @Override + public void writeUInt32List(int fieldNumber, List value, boolean packed) + throws IOException { + if (packed) { + output.writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); + + // Compute and write the length of the data. + int dataSize = 0; + for (int i = 0; i < value.size(); ++i) { + dataSize += CodedOutputStream.computeUInt32SizeNoTag(value.get(i)); + } + output.writeUInt32NoTag(dataSize); + + // Write the data itself, without any tags. + for (int i = 0; i < value.size(); ++i) { + output.writeUInt32NoTag(value.get(i)); + } + } else { + for (int i = 0; i < value.size(); ++i) { + output.writeUInt32(fieldNumber, value.get(i)); + } + } + } + + @Override + public void writeSFixed32List(int fieldNumber, List value, boolean packed) + throws IOException { + if (packed) { + output.writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); + + // Compute and write the length of the data. + int dataSize = 0; + for (int i = 0; i < value.size(); ++i) { + dataSize += CodedOutputStream.computeSFixed32SizeNoTag(value.get(i)); + } + output.writeUInt32NoTag(dataSize); + + // Write the data itself, without any tags. + for (int i = 0; i < value.size(); ++i) { + output.writeSFixed32NoTag(value.get(i)); + } + } else { + for (int i = 0; i < value.size(); ++i) { + output.writeSFixed32(fieldNumber, value.get(i)); + } + } + } + + @Override + public void writeSFixed64List(int fieldNumber, List value, boolean packed) + throws IOException { + if (packed) { + output.writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); + + // Compute and write the length of the data. + int dataSize = 0; + for (int i = 0; i < value.size(); ++i) { + dataSize += CodedOutputStream.computeSFixed64SizeNoTag(value.get(i)); + } + output.writeUInt32NoTag(dataSize); + + // Write the data itself, without any tags. + for (int i = 0; i < value.size(); ++i) { + output.writeSFixed64NoTag(value.get(i)); + } + } else { + for (int i = 0; i < value.size(); ++i) { + output.writeSFixed64(fieldNumber, value.get(i)); + } + } + } + + @Override + public void writeSInt32List(int fieldNumber, List value, boolean packed) + throws IOException { + if (packed) { + output.writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); + + // Compute and write the length of the data. + int dataSize = 0; + for (int i = 0; i < value.size(); ++i) { + dataSize += CodedOutputStream.computeSInt32SizeNoTag(value.get(i)); + } + output.writeUInt32NoTag(dataSize); + + // Write the data itself, without any tags. + for (int i = 0; i < value.size(); ++i) { + output.writeSInt32NoTag(value.get(i)); + } + } else { + for (int i = 0; i < value.size(); ++i) { + output.writeSInt32(fieldNumber, value.get(i)); + } + } + } + + @Override + public void writeSInt64List(int fieldNumber, List value, boolean packed) + throws IOException { + if (packed) { + output.writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); + + // Compute and write the length of the data. + int dataSize = 0; + for (int i = 0; i < value.size(); ++i) { + dataSize += CodedOutputStream.computeSInt64SizeNoTag(value.get(i)); + } + output.writeUInt32NoTag(dataSize); + + // Write the data itself, without any tags. + for (int i = 0; i < value.size(); ++i) { + output.writeSInt64NoTag(value.get(i)); + } + } else { + for (int i = 0; i < value.size(); ++i) { + output.writeSInt64(fieldNumber, value.get(i)); + } + } + } + + @Override + public void writeMessageList(int fieldNumber, List value) throws IOException { + for (int i = 0; i < value.size(); ++i) { + writeMessage(fieldNumber, value.get(i)); + } + } + + @Override + public void writeMessageList(int fieldNumber, List value, Schema schema) throws IOException { + for (int i = 0; i < value.size(); ++i) { + writeMessage(fieldNumber, value.get(i), schema); + } + } + + @Override + public void writeGroupList(int fieldNumber, List value) throws IOException { + for (int i = 0; i < value.size(); ++i) { + writeGroup(fieldNumber, value.get(i)); + } + } + + @Override + public void writeGroupList(int fieldNumber, List value, Schema schema) throws IOException { + for (int i = 0; i < value.size(); ++i) { + writeGroup(fieldNumber, value.get(i), schema); + } + } + + @Override + public void writeMap(int fieldNumber, MapEntryLite.Metadata metadata, Map map) + throws IOException { + if (output.isSerializationDeterministic()) { + writeDeterministicMap(fieldNumber, metadata, map); + return; + } + for (Map.Entry entry : map.entrySet()) { + output.writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); + output.writeUInt32NoTag( + MapEntryLite.computeSerializedSize(metadata, entry.getKey(), entry.getValue())); + MapEntryLite.writeTo(output, metadata, entry.getKey(), entry.getValue()); + } + } + + @SuppressWarnings("unchecked") + private void writeDeterministicMap( + int fieldNumber, MapEntryLite.Metadata metadata, Map map) throws IOException { + switch (metadata.keyType) { + case BOOL: + V value; + if ((value = map.get(Boolean.FALSE)) != null) { + writeDeterministicBooleanMapEntry( + fieldNumber, /* key= */ false, value, (MapEntryLite.Metadata) metadata); + } + if ((value = map.get(Boolean.TRUE)) != null) { + writeDeterministicBooleanMapEntry( + fieldNumber, /* key= */ true, value, (MapEntryLite.Metadata) metadata); + } + break; + case FIXED32: + case INT32: + case SFIXED32: + case SINT32: + case UINT32: + writeDeterministicIntegerMap( + fieldNumber, (MapEntryLite.Metadata) metadata, (Map) map); + break; + case FIXED64: + case INT64: + case SFIXED64: + case SINT64: + case UINT64: + writeDeterministicLongMap( + fieldNumber, (MapEntryLite.Metadata) metadata, (Map) map); + break; + case STRING: + writeDeterministicStringMap( + fieldNumber, (MapEntryLite.Metadata) metadata, (Map) map); + break; + default: + throw new IllegalArgumentException("does not support key type: " + metadata.keyType); + } + } + + private void writeDeterministicBooleanMapEntry( + int fieldNumber, boolean key, V value, MapEntryLite.Metadata metadata) + throws IOException { + output.writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); + output.writeUInt32NoTag(MapEntryLite.computeSerializedSize(metadata, key, value)); + MapEntryLite.writeTo(output, metadata, key, value); + } + + private void writeDeterministicIntegerMap( + int fieldNumber, MapEntryLite.Metadata metadata, Map map) + throws IOException { + int[] keys = new int[map.size()]; + int index = 0; + for (int k : map.keySet()) { + keys[index++] = k; + } + Arrays.sort(keys); + for (int key : keys) { + V value = map.get(key); + output.writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); + output.writeUInt32NoTag(MapEntryLite.computeSerializedSize(metadata, key, value)); + MapEntryLite.writeTo(output, metadata, key, value); + } + } + + private void writeDeterministicLongMap( + int fieldNumber, MapEntryLite.Metadata metadata, Map map) + throws IOException { + long[] keys = new long[map.size()]; + int index = 0; + for (long k : map.keySet()) { + keys[index++] = k; + } + Arrays.sort(keys); + for (long key : keys) { + V value = map.get(key); + output.writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); + output.writeUInt32NoTag(MapEntryLite.computeSerializedSize(metadata, key, value)); + MapEntryLite.writeTo(output, metadata, key, value); + } + } + + private void writeDeterministicStringMap( + int fieldNumber, MapEntryLite.Metadata metadata, Map map) + throws IOException { + String[] keys = new String[map.size()]; + int index = 0; + for (String k : map.keySet()) { + keys[index++] = k; + } + Arrays.sort(keys); + for (String key : keys) { + V value = map.get(key); + output.writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); + output.writeUInt32NoTag(MapEntryLite.computeSerializedSize(metadata, key, value)); + MapEntryLite.writeTo(output, metadata, key, value); + } + } +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java new file mode 100644 index 0000000..c2378ad --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java @@ -0,0 +1,70 @@ +// 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. + +package com.google.protobuf; + +/** Parsers to discard unknown fields during parsing. */ +public final class DiscardUnknownFieldsParser { + + /** + * Wraps a given {@link Parser} into a new {@link Parser} that discards unknown fields during + * parsing. + * + *

Usage example: + * + *

{@code
+   * private final static Parser FOO_PARSER = DiscardUnknownFieldsParser.wrap(Foo.parser());
+   * Foo parseFooDiscardUnknown(ByteBuffer input) throws IOException {
+   *   return FOO_PARSER.parseFrom(input);
+   * }
+   * }
+ * + *

Like all other implementations of {@code Parser}, this parser is stateless and thread-safe. + * + * @param parser The delegated parser that parses messages. + * @return a {@link Parser} that will discard unknown fields during parsing. + */ + public static final Parser wrap(final Parser parser) { + return new AbstractParser() { + @Override + public T parsePartialFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException { + try { + input.discardUnknownFields(); + return parser.parsePartialFrom(input, extensionRegistry); + } finally { + input.unsetDiscardUnknownFields(); + } + } + }; + } + + private DiscardUnknownFieldsParser() {} +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/ExtensionLite.java b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/ExtensionLite.java new file mode 100644 index 0000000..0fb5f49 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/ExtensionLite.java @@ -0,0 +1,60 @@ +// 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. + +package com.google.protobuf; + +/** + * Lite interface that generated extensions implement. + * + *

Methods are for use by generated code only. You can hold a reference to extensions using this + * type name. + */ +public abstract class ExtensionLite { + + /** Returns the field number of the extension. */ + public abstract int getNumber(); + + /** Returns the type of the field. */ + public abstract WireFormat.FieldType getLiteType(); + + /** Returns whether it is a repeated field. */ + public abstract boolean isRepeated(); + + /** Returns the default value of the extension field. */ + public abstract Type getDefaultValue(); + + /** Returns the default instance of the extension field, if it's a message extension. */ + public abstract MessageLite getMessageDefaultInstance(); + + /** Returns whether or not this extension is a Lite Extension. */ + boolean isLite() { + return true; + } +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/GeneratedMessage.java b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/GeneratedMessage.java new file mode 100644 index 0000000..de0ee11 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/GeneratedMessage.java @@ -0,0 +1,3051 @@ +// 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. + +package com.google.protobuf; + +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.EnumDescriptor; +import com.google.protobuf.Descriptors.EnumValueDescriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Descriptors.FileDescriptor; +import com.google.protobuf.Descriptors.OneofDescriptor; + +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectStreamException; +import java.io.Serializable; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +/** + * All generated protocol message classes extend this class. This class + * implements most of the Message and Builder interfaces using Java reflection. + * Users can ignore this class and pretend that generated messages implement + * the Message interface directly. + * + * @author kenton@google.com Kenton Varda + */ +public abstract class GeneratedMessage extends AbstractMessage + implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * For testing. Allows a test to disable the optimization that avoids using + * field builders for nested messages until they are requested. By disabling + * this optimization, existing tests can be reused to test the field builders. + */ + protected static boolean alwaysUseFieldBuilders = false; + + /** For use by generated code only. */ + protected UnknownFieldSet unknownFields; + + protected GeneratedMessage() { + unknownFields = UnknownFieldSet.getDefaultInstance(); + } + + protected GeneratedMessage(Builder builder) { + unknownFields = builder.getUnknownFields(); + } + + @Override + public Parser getParserForType() { + throw new UnsupportedOperationException( + "This is supposed to be overridden by subclasses."); + } + + /** + * For testing. Allows a test to disable the optimization that avoids using + * field builders for nested messages until they are requested. By disabling + * this optimization, existing tests can be reused to test the field builders. + * See {@link RepeatedFieldBuilder} and {@link SingleFieldBuilder}. + */ + static void enableAlwaysUseFieldBuildersForTesting() { + alwaysUseFieldBuilders = true; + } + + /** + * Get the FieldAccessorTable for this type. We can't have the message + * class pass this in to the constructor because of bootstrapping trouble + * with DescriptorProtos. + */ + protected abstract FieldAccessorTable internalGetFieldAccessorTable(); + + @Override + public Descriptor getDescriptorForType() { + return internalGetFieldAccessorTable().descriptor; + } + + /** + * Internal helper to return a modifiable map containing all the fields. + * The returned Map is modifialbe so that the caller can add additional + * extension fields to implement {@link #getAllFields()}. + * + * @param getBytesForString whether to generate ByteString for string fields + */ + private Map getAllFieldsMutable( + boolean getBytesForString) { + final TreeMap result = + new TreeMap(); + final Descriptor descriptor = internalGetFieldAccessorTable().descriptor; + final List fields = descriptor.getFields(); + + for (int i = 0; i < fields.size(); i++) { + FieldDescriptor field = fields.get(i); + final OneofDescriptor oneofDescriptor = field.getContainingOneof(); + + /* + * If the field is part of a Oneof, then at maximum one field in the Oneof is set + * and it is not repeated. There is no need to iterate through the others. + */ + if (oneofDescriptor != null) { + // Skip other fields in the Oneof we know are not set + i += oneofDescriptor.getFieldCount() - 1; + if (!hasOneof(oneofDescriptor)) { + // If no field is set in the Oneof, skip all the fields in the Oneof + continue; + } + // Get the pointer to the only field which is set in the Oneof + field = getOneofFieldDescriptor(oneofDescriptor); + } else { + // If we are not in a Oneof, we need to check if the field is set and if it is repeated + if (field.isRepeated()) { + final List value = (List) getField(field); + if (!value.isEmpty()) { + result.put(field, value); + } + continue; + } + if (!hasField(field)) { + continue; + } + } + // Add the field to the map + if (getBytesForString && field.getJavaType() == FieldDescriptor.JavaType.STRING) { + result.put(field, getFieldRaw(field)); + } else { + result.put(field, getField(field)); + } + } + return result; + } + + @Override + public boolean isInitialized() { + for (final FieldDescriptor field : getDescriptorForType().getFields()) { + // Check that all required fields are present. + if (field.isRequired()) { + if (!hasField(field)) { + return false; + } + } + // Check that embedded messages are initialized. + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + if (field.isRepeated()) { + @SuppressWarnings("unchecked") final + List messageList = (List) getField(field); + for (final Message element : messageList) { + if (!element.isInitialized()) { + return false; + } + } + } else { + if (hasField(field) && !((Message) getField(field)).isInitialized()) { + return false; + } + } + } + } + + return true; + } + + @Override + public Map getAllFields() { + return Collections.unmodifiableMap( + getAllFieldsMutable(/* getBytesForString = */ false)); + } + + /** + * Returns a collection of all the fields in this message which are set + * and their corresponding values. A singular ("required" or "optional") + * field is set iff hasField() returns true for that field. A "repeated" + * field is set iff getRepeatedFieldCount() is greater than zero. The + * values are exactly what would be returned by calling + * {@link #getFieldRaw(Descriptors.FieldDescriptor)} for each field. The map + * is guaranteed to be a sorted map, so iterating over it will return fields + * in order by field number. + */ + Map getAllFieldsRaw() { + return Collections.unmodifiableMap( + getAllFieldsMutable(/* getBytesForString = */ true)); + } + + @Override + public boolean hasOneof(final OneofDescriptor oneof) { + return internalGetFieldAccessorTable().getOneof(oneof).has(this); + } + + @Override + public FieldDescriptor getOneofFieldDescriptor(final OneofDescriptor oneof) { + return internalGetFieldAccessorTable().getOneof(oneof).get(this); + } + + @Override + public boolean hasField(final FieldDescriptor field) { + return internalGetFieldAccessorTable().getField(field).has(this); + } + + @Override + public Object getField(final FieldDescriptor field) { + return internalGetFieldAccessorTable().getField(field).get(this); + } + + /** + * Obtains the value of the given field, or the default value if it is + * not set. For primitive fields, the boxed primitive value is returned. + * For enum fields, the EnumValueDescriptor for the value is returned. For + * embedded message fields, the sub-message is returned. For repeated + * fields, a java.util.List is returned. For present string fields, a + * ByteString is returned representing the bytes that the field contains. + */ + Object getFieldRaw(final FieldDescriptor field) { + return internalGetFieldAccessorTable().getField(field).getRaw(this); + } + + @Override + public int getRepeatedFieldCount(final FieldDescriptor field) { + return internalGetFieldAccessorTable().getField(field) + .getRepeatedCount(this); + } + + @Override + public Object getRepeatedField(final FieldDescriptor field, final int index) { + return internalGetFieldAccessorTable().getField(field) + .getRepeated(this, index); + } + + @Override + public UnknownFieldSet getUnknownFields() { + throw new UnsupportedOperationException( + "This is supposed to be overridden by subclasses."); + } + + /** + * Called by subclasses to parse an unknown field. + * @return {@code true} unless the tag is an end-group tag. + */ + protected boolean parseUnknownField( + CodedInputStream input, + UnknownFieldSet.Builder unknownFields, + ExtensionRegistryLite extensionRegistry, + int tag) throws IOException { + return unknownFields.mergeFieldFrom(tag, input); + } + + protected static M parseWithIOException(Parser parser, InputStream input) + throws IOException { + try { + return parser.parseFrom(input); + } catch (InvalidProtocolBufferException e) { + throw e.unwrapIOException(); + } + } + + protected static M parseWithIOException(Parser parser, InputStream input, + ExtensionRegistryLite extensions) throws IOException { + try { + return parser.parseFrom(input, extensions); + } catch (InvalidProtocolBufferException e) { + throw e.unwrapIOException(); + } + } + + protected static M parseWithIOException(Parser parser, + CodedInputStream input) throws IOException { + try { + return parser.parseFrom(input); + } catch (InvalidProtocolBufferException e) { + throw e.unwrapIOException(); + } + } + + protected static M parseWithIOException(Parser parser, + CodedInputStream input, ExtensionRegistryLite extensions) throws IOException { + try { + return parser.parseFrom(input, extensions); + } catch (InvalidProtocolBufferException e) { + throw e.unwrapIOException(); + } + } + + protected static M parseDelimitedWithIOException(Parser parser, + InputStream input) throws IOException { + try { + return parser.parseDelimitedFrom(input); + } catch (InvalidProtocolBufferException e) { + throw e.unwrapIOException(); + } + } + + protected static M parseDelimitedWithIOException(Parser parser, + InputStream input, ExtensionRegistryLite extensions) throws IOException { + try { + return parser.parseDelimitedFrom(input, extensions); + } catch (InvalidProtocolBufferException e) { + throw e.unwrapIOException(); + } + } + + @Override + public void writeTo(final CodedOutputStream output) throws IOException { + MessageReflection.writeMessageTo(this, getAllFieldsRaw(), output, false); + } + + @Override + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) { + return size; + } + + memoizedSize = MessageReflection.getSerializedSize( + this, getAllFieldsRaw()); + return memoizedSize; + } + + + + /** + * Used by parsing constructors in generated classes. + */ + protected void makeExtensionsImmutable() { + // Noop for messages without extensions. + } + + /** + * TODO(xiaofeng): remove this after b/29368482 is fixed. We need to move this + * interface to AbstractMessage in order to versioning GeneratedMessage but + * this move breaks binary compatibility for AppEngine. After AppEngine is + * fixed we can exclude this from google3. + */ + protected interface BuilderParent extends AbstractMessage.BuilderParent {} + + /** + * TODO(xiaofeng): remove this together with GeneratedMessage.BuilderParent. + */ + protected abstract Message.Builder newBuilderForType(BuilderParent parent); + + @Override + protected Message.Builder newBuilderForType(final AbstractMessage.BuilderParent parent) { + return newBuilderForType(new BuilderParent() { + @Override + public void markDirty() { + parent.markDirty(); + } + }); + } + + + @SuppressWarnings("unchecked") + public abstract static class Builder > + extends AbstractMessage.Builder { + + private BuilderParent builderParent; + + private BuilderParentImpl meAsParent; + + // Indicates that we've built a message and so we are now obligated + // to dispatch dirty invalidations. See GeneratedMessage.BuilderListener. + private boolean isClean; + + private UnknownFieldSet unknownFields = + UnknownFieldSet.getDefaultInstance(); + + protected Builder() { + this(null); + } + + protected Builder(BuilderParent builderParent) { + this.builderParent = builderParent; + } + + @Override + void dispose() { + builderParent = null; + } + + /** + * Called by the subclass when a message is built. + */ + protected void onBuilt() { + if (builderParent != null) { + markClean(); + } + } + + /** + * Called by the subclass or a builder to notify us that a message was + * built and may be cached and therefore invalidations are needed. + */ + @Override + protected void markClean() { + this.isClean = true; + } + + /** + * Gets whether invalidations are needed + * + * @return whether invalidations are needed + */ + protected boolean isClean() { + return isClean; + } + + @Override + public BuilderType clone() { + BuilderType builder = + (BuilderType) getDefaultInstanceForType().newBuilderForType(); + builder.mergeFrom(buildPartial()); + return builder; + } + + /** + * Called by the initialization and clear code paths to allow subclasses to + * reset any of their builtin fields back to the initial values. + */ + @Override + public BuilderType clear() { + unknownFields = UnknownFieldSet.getDefaultInstance(); + onChanged(); + return (BuilderType) this; + } + + /** + * Get the FieldAccessorTable for this type. We can't have the message + * class pass this in to the constructor because of bootstrapping trouble + * with DescriptorProtos. + */ + protected abstract FieldAccessorTable internalGetFieldAccessorTable(); + + @Override + public Descriptor getDescriptorForType() { + return internalGetFieldAccessorTable().descriptor; + } + + @Override + public Map getAllFields() { + return Collections.unmodifiableMap(getAllFieldsMutable()); + } + + /** Internal helper which returns a mutable map. */ + private Map getAllFieldsMutable() { + final TreeMap result = + new TreeMap(); + final Descriptor descriptor = internalGetFieldAccessorTable().descriptor; + final List fields = descriptor.getFields(); + + for (int i = 0; i < fields.size(); i++) { + FieldDescriptor field = fields.get(i); + final OneofDescriptor oneofDescriptor = field.getContainingOneof(); + + /* + * If the field is part of a Oneof, then at maximum one field in the Oneof is set + * and it is not repeated. There is no need to iterate through the others. + */ + if (oneofDescriptor != null) { + // Skip other fields in the Oneof we know are not set + i += oneofDescriptor.getFieldCount() - 1; + if (!hasOneof(oneofDescriptor)) { + // If no field is set in the Oneof, skip all the fields in the Oneof + continue; + } + // Get the pointer to the only field which is set in the Oneof + field = getOneofFieldDescriptor(oneofDescriptor); + } else { + // If we are not in a Oneof, we need to check if the field is set and if it is repeated + if (field.isRepeated()) { + final List value = (List) getField(field); + if (!value.isEmpty()) { + result.put(field, value); + } + continue; + } + if (!hasField(field)) { + continue; + } + } + // Add the field to the map + result.put(field, getField(field)); + } + return result; + } + + @Override + public Message.Builder newBuilderForField(final FieldDescriptor field) { + return internalGetFieldAccessorTable().getField(field).newBuilder(); + } + + @Override + public Message.Builder getFieldBuilder(final FieldDescriptor field) { + return internalGetFieldAccessorTable().getField(field).getBuilder(this); + } + + @Override + public Message.Builder getRepeatedFieldBuilder(final FieldDescriptor field, int index) { + return internalGetFieldAccessorTable().getField(field).getRepeatedBuilder( + this, index); + } + + @Override + public boolean hasOneof(final OneofDescriptor oneof) { + return internalGetFieldAccessorTable().getOneof(oneof).has(this); + } + + @Override + public FieldDescriptor getOneofFieldDescriptor(final OneofDescriptor oneof) { + return internalGetFieldAccessorTable().getOneof(oneof).get(this); + } + + @Override + public boolean hasField(final FieldDescriptor field) { + return internalGetFieldAccessorTable().getField(field).has(this); + } + + @Override + public Object getField(final FieldDescriptor field) { + Object object = internalGetFieldAccessorTable().getField(field).get(this); + if (field.isRepeated()) { + // The underlying list object is still modifiable at this point. + // Make sure not to expose the modifiable list to the caller. + return Collections.unmodifiableList((List) object); + } else { + return object; + } + } + + @Override + public BuilderType setField(final FieldDescriptor field, final Object value) { + internalGetFieldAccessorTable().getField(field).set(this, value); + return (BuilderType) this; + } + + @Override + public BuilderType clearField(final FieldDescriptor field) { + internalGetFieldAccessorTable().getField(field).clear(this); + return (BuilderType) this; + } + + @Override + public BuilderType clearOneof(final OneofDescriptor oneof) { + internalGetFieldAccessorTable().getOneof(oneof).clear(this); + return (BuilderType) this; + } + + @Override + public int getRepeatedFieldCount(final FieldDescriptor field) { + return internalGetFieldAccessorTable().getField(field) + .getRepeatedCount(this); + } + + @Override + public Object getRepeatedField(final FieldDescriptor field, final int index) { + return internalGetFieldAccessorTable().getField(field) + .getRepeated(this, index); + } + + @Override + public BuilderType setRepeatedField( + final FieldDescriptor field, final int index, final Object value) { + internalGetFieldAccessorTable().getField(field) + .setRepeated(this, index, value); + return (BuilderType) this; + } + + @Override + public BuilderType addRepeatedField(final FieldDescriptor field, final Object value) { + internalGetFieldAccessorTable().getField(field).addRepeated(this, value); + return (BuilderType) this; + } + + @Override + public BuilderType setUnknownFields(final UnknownFieldSet unknownFields) { + this.unknownFields = unknownFields; + onChanged(); + return (BuilderType) this; + } + + @Override + public BuilderType mergeUnknownFields( + final UnknownFieldSet unknownFields) { + this.unknownFields = + UnknownFieldSet.newBuilder(this.unknownFields) + .mergeFrom(unknownFields) + .build(); + onChanged(); + return (BuilderType) this; + } + + @Override + public boolean isInitialized() { + for (final FieldDescriptor field : getDescriptorForType().getFields()) { + // Check that all required fields are present. + if (field.isRequired()) { + if (!hasField(field)) { + return false; + } + } + // Check that embedded messages are initialized. + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + if (field.isRepeated()) { + @SuppressWarnings("unchecked") final + List messageList = (List) getField(field); + for (final Message element : messageList) { + if (!element.isInitialized()) { + return false; + } + } + } else { + if (hasField(field) && + !((Message) getField(field)).isInitialized()) { + return false; + } + } + } + } + return true; + } + + @Override + public final UnknownFieldSet getUnknownFields() { + return unknownFields; + } + + /** + * Called by subclasses to parse an unknown field. + * @return {@code true} unless the tag is an end-group tag. + */ + protected boolean parseUnknownField( + final CodedInputStream input, + final UnknownFieldSet.Builder unknownFields, + final ExtensionRegistryLite extensionRegistry, + final int tag) throws IOException { + return unknownFields.mergeFieldFrom(tag, input); + } + + /** + * Implementation of {@link BuilderParent} for giving to our children. This + * small inner class makes it so we don't publicly expose the BuilderParent + * methods. + */ + private class BuilderParentImpl implements BuilderParent { + + @Override + public void markDirty() { + onChanged(); + } + } + + /** + * Gets the {@link BuilderParent} for giving to our children. + * @return The builder parent for our children. + */ + protected BuilderParent getParentForChildren() { + if (meAsParent == null) { + meAsParent = new BuilderParentImpl(); + } + return meAsParent; + } + + /** + * Called when a the builder or one of its nested children has changed + * and any parent should be notified of its invalidation. + */ + protected final void onChanged() { + if (isClean && builderParent != null) { + builderParent.markDirty(); + + // Don't keep dispatching invalidations until build is called again. + isClean = false; + } + } + + /** + * Gets the map field with the given field number. This method should be + * overridden in the generated message class if the message contains map + * fields. + * + * Unlike other field types, reflection support for map fields can't be + * implemented based on generated public API because we need to access a + * map field as a list in reflection API but the generated API only allows + * us to access it as a map. This method returns the underlying map field + * directly and thus enables us to access the map field as a list. + */ + @SuppressWarnings({"unused", "rawtypes"}) + protected MapField internalGetMapField(int fieldNumber) { + // Note that we can't use descriptor names here because this method will + // be called when descriptor is being initialized. + throw new RuntimeException( + "No map fields found in " + getClass().getName()); + } + + /** Like {@link #internalGetMapField} but return a mutable version. */ + @SuppressWarnings({"unused", "rawtypes"}) + protected MapField internalGetMutableMapField(int fieldNumber) { + // Note that we can't use descriptor names here because this method will + // be called when descriptor is being initialized. + throw new RuntimeException( + "No map fields found in " + getClass().getName()); + } + } + + // ================================================================= + // Extensions-related stuff + + public interface ExtendableMessageOrBuilder< + MessageType extends ExtendableMessage> extends MessageOrBuilder { + // Re-define for return type covariance. + @Override + Message getDefaultInstanceForType(); + + /** Check if a singular extension is present. */ + boolean hasExtension( + ExtensionLite extension); + + /** Get the number of elements in a repeated extension. */ + int getExtensionCount( + ExtensionLite> extension); + + /** Get the value of an extension. */ + Type getExtension( + ExtensionLite extension); + + /** Get one element of a repeated extension. */ + Type getExtension( + ExtensionLite> extension, + int index); + + /** Check if a singular extension is present. */ + boolean hasExtension( + Extension extension); + /** Check if a singular extension is present. */ + boolean hasExtension( + GeneratedExtension extension); + /** Get the number of elements in a repeated extension. */ + int getExtensionCount( + Extension> extension); + /** Get the number of elements in a repeated extension. */ + int getExtensionCount( + GeneratedExtension> extension); + /** Get the value of an extension. */ + Type getExtension( + Extension extension); + /** Get the value of an extension. */ + Type getExtension( + GeneratedExtension extension); + /** Get one element of a repeated extension. */ + Type getExtension( + Extension> extension, + int index); + /** Get one element of a repeated extension. */ + Type getExtension( + GeneratedExtension> extension, + int index); + } + + /** + * Generated message classes for message types that contain extension ranges + * subclass this. + * + *

This class implements type-safe accessors for extensions. They + * implement all the same operations that you can do with normal fields -- + * e.g. "has", "get", and "getCount" -- but for extensions. The extensions + * are identified using instances of the class {@link GeneratedExtension}; + * the protocol compiler generates a static instance of this class for every + * extension in its input. Through the magic of generics, all is made + * type-safe. + * + *

For example, imagine you have the {@code .proto} file: + * + *

+   * option java_class = "MyProto";
+   *
+   * message Foo {
+   *   extensions 1000 to max;
+   * }
+   *
+   * extend Foo {
+   *   optional int32 bar;
+   * }
+   * 
+ * + *

Then you might write code like: + * + *

+   * MyProto.Foo foo = getFoo();
+   * int i = foo.getExtension(MyProto.bar);
+   * 
+ * + *

See also {@link ExtendableBuilder}. + */ + public abstract static class ExtendableMessage< + MessageType extends ExtendableMessage> + extends GeneratedMessage + implements ExtendableMessageOrBuilder { + + private static final long serialVersionUID = 1L; + + private final FieldSet extensions; + + protected ExtendableMessage() { + this.extensions = FieldSet.newFieldSet(); + } + + protected ExtendableMessage( + ExtendableBuilder builder) { + super(builder); + this.extensions = builder.buildExtensions(); + } + + private void verifyExtensionContainingType( + final Extension extension) { + if (extension.getDescriptor().getContainingType() != + getDescriptorForType()) { + // This can only happen if someone uses unchecked operations. + throw new IllegalArgumentException( + "Extension is for type \"" + + extension.getDescriptor().getContainingType().getFullName() + + "\" which does not match message type \"" + + getDescriptorForType().getFullName() + "\"."); + } + } + + /** Check if a singular extension is present. */ + @Override + @SuppressWarnings("unchecked") + public final boolean hasExtension(final ExtensionLite extensionLite) { + Extension extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + return extensions.hasField(extension.getDescriptor()); + } + + /** Get the number of elements in a repeated extension. */ + @Override + @SuppressWarnings("unchecked") + public final int getExtensionCount( + final ExtensionLite> extensionLite) { + Extension> extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + final FieldDescriptor descriptor = extension.getDescriptor(); + return extensions.getRepeatedFieldCount(descriptor); + } + + /** Get the value of an extension. */ + @Override + @SuppressWarnings("unchecked") + public final Type getExtension(final ExtensionLite extensionLite) { + Extension extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + FieldDescriptor descriptor = extension.getDescriptor(); + final Object value = extensions.getField(descriptor); + if (value == null) { + if (descriptor.isRepeated()) { + return (Type) Collections.emptyList(); + } else if (descriptor.getJavaType() == + FieldDescriptor.JavaType.MESSAGE) { + return (Type) extension.getMessageDefaultInstance(); + } else { + return (Type) extension.fromReflectionType( + descriptor.getDefaultValue()); + } + } else { + return (Type) extension.fromReflectionType(value); + } + } + + /** Get one element of a repeated extension. */ + @Override + @SuppressWarnings("unchecked") + public final Type getExtension( + final ExtensionLite> extensionLite, final int index) { + Extension> extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + FieldDescriptor descriptor = extension.getDescriptor(); + return (Type) extension.singularFromReflectionType( + extensions.getRepeatedField(descriptor, index)); + } + + /** Check if a singular extension is present. */ + @Override + public final boolean hasExtension(final Extension extension) { + return hasExtension((ExtensionLite) extension); + } + /** Check if a singular extension is present. */ + @Override + public final boolean hasExtension( + final GeneratedExtension extension) { + return hasExtension((ExtensionLite) extension); + } + /** Get the number of elements in a repeated extension. */ + @Override + public final int getExtensionCount( + final Extension> extension) { + return getExtensionCount((ExtensionLite>) extension); + } + /** Get the number of elements in a repeated extension. */ + @Override + public final int getExtensionCount( + final GeneratedExtension> extension) { + return getExtensionCount((ExtensionLite>) extension); + } + /** Get the value of an extension. */ + @Override + public final Type getExtension(final Extension extension) { + return getExtension((ExtensionLite) extension); + } + /** Get the value of an extension. */ + @Override + public final Type getExtension( + final GeneratedExtension extension) { + return getExtension((ExtensionLite) extension); + } + /** Get one element of a repeated extension. */ + @Override + public final Type getExtension( + final Extension> extension, final int index) { + return getExtension((ExtensionLite>) extension, index); + } + /** Get one element of a repeated extension. */ + @Override + public final Type getExtension( + final GeneratedExtension> extension, final int index) { + return getExtension((ExtensionLite>) extension, index); + } + + /** Called by subclasses to check if all extensions are initialized. */ + protected boolean extensionsAreInitialized() { + return extensions.isInitialized(); + } + + @Override + public boolean isInitialized() { + return super.isInitialized() && extensionsAreInitialized(); + } + + @Override + protected boolean parseUnknownField( + CodedInputStream input, + UnknownFieldSet.Builder unknownFields, + ExtensionRegistryLite extensionRegistry, + int tag) throws IOException { + return MessageReflection.mergeFieldFrom( + input, unknownFields, extensionRegistry, getDescriptorForType(), + new MessageReflection.ExtensionAdapter(extensions), tag); + } + + + /** + * Used by parsing constructors in generated classes. + */ + @Override + protected void makeExtensionsImmutable() { + extensions.makeImmutable(); + } + + /** + * Used by subclasses to serialize extensions. Extension ranges may be + * interleaved with field numbers, but we must write them in canonical + * (sorted by field number) order. ExtensionWriter helps us write + * individual ranges of extensions at once. + */ + protected class ExtensionWriter { + // Imagine how much simpler this code would be if Java iterators had + // a way to get the next element without advancing the iterator. + + private final Iterator> iter = + extensions.iterator(); + private Map.Entry next; + private final boolean messageSetWireFormat; + + private ExtensionWriter(final boolean messageSetWireFormat) { + if (iter.hasNext()) { + next = iter.next(); + } + this.messageSetWireFormat = messageSetWireFormat; + } + + public void writeUntil(final int end, final CodedOutputStream output) + throws IOException { + while (next != null && next.getKey().getNumber() < end) { + FieldDescriptor descriptor = next.getKey(); + if (messageSetWireFormat && descriptor.getLiteJavaType() == + WireFormat.JavaType.MESSAGE && + !descriptor.isRepeated()) { + if (next instanceof LazyField.LazyEntry) { + output.writeRawMessageSetExtension(descriptor.getNumber(), + ((LazyField.LazyEntry) next).getField().toByteString()); + } else { + output.writeMessageSetExtension(descriptor.getNumber(), + (Message) next.getValue()); + } + } else { + // TODO(xiangl): Taken care of following code, it may cause + // problem when we use LazyField for normal fields/extensions. + // Due to the optional field can be duplicated at the end of + // serialized bytes, which will make the serialized size change + // after lazy field parsed. So when we use LazyField globally, + // we need to change the following write method to write cached + // bytes directly rather than write the parsed message. + FieldSet.writeField(descriptor, next.getValue(), output); + } + if (iter.hasNext()) { + next = iter.next(); + } else { + next = null; + } + } + } + } + + protected ExtensionWriter newExtensionWriter() { + return new ExtensionWriter(false); + } + protected ExtensionWriter newMessageSetExtensionWriter() { + return new ExtensionWriter(true); + } + + /** Called by subclasses to compute the size of extensions. */ + protected int extensionsSerializedSize() { + return extensions.getSerializedSize(); + } + protected int extensionsSerializedSizeAsMessageSet() { + return extensions.getMessageSetSerializedSize(); + } + + // --------------------------------------------------------------- + // Reflection + + protected Map getExtensionFields() { + return extensions.getAllFields(); + } + + @Override + public Map getAllFields() { + final Map result = + super.getAllFieldsMutable(/* getBytesForString = */ false); + result.putAll(getExtensionFields()); + return Collections.unmodifiableMap(result); + } + + @Override + public Map getAllFieldsRaw() { + final Map result = + super.getAllFieldsMutable(/* getBytesForString = */ false); + result.putAll(getExtensionFields()); + return Collections.unmodifiableMap(result); + } + + @Override + public boolean hasField(final FieldDescriptor field) { + if (field.isExtension()) { + verifyContainingType(field); + return extensions.hasField(field); + } else { + return super.hasField(field); + } + } + + @Override + public Object getField(final FieldDescriptor field) { + if (field.isExtension()) { + verifyContainingType(field); + final Object value = extensions.getField(field); + if (value == null) { + if (field.isRepeated()) { + return Collections.emptyList(); + } else if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + // Lacking an ExtensionRegistry, we have no way to determine the + // extension's real type, so we return a DynamicMessage. + return DynamicMessage.getDefaultInstance(field.getMessageType()); + } else { + return field.getDefaultValue(); + } + } else { + return value; + } + } else { + return super.getField(field); + } + } + + @Override + public int getRepeatedFieldCount(final FieldDescriptor field) { + if (field.isExtension()) { + verifyContainingType(field); + return extensions.getRepeatedFieldCount(field); + } else { + return super.getRepeatedFieldCount(field); + } + } + + @Override + public Object getRepeatedField(final FieldDescriptor field, + final int index) { + if (field.isExtension()) { + verifyContainingType(field); + return extensions.getRepeatedField(field, index); + } else { + return super.getRepeatedField(field, index); + } + } + + private void verifyContainingType(final FieldDescriptor field) { + if (field.getContainingType() != getDescriptorForType()) { + throw new IllegalArgumentException( + "FieldDescriptor does not match message type."); + } + } + } + + /** + * Generated message builders for message types that contain extension ranges + * subclass this. + * + *

This class implements type-safe accessors for extensions. They + * implement all the same operations that you can do with normal fields -- + * e.g. "get", "set", and "add" -- but for extensions. The extensions are + * identified using instances of the class {@link GeneratedExtension}; the + * protocol compiler generates a static instance of this class for every + * extension in its input. Through the magic of generics, all is made + * type-safe. + * + *

For example, imagine you have the {@code .proto} file: + * + *

+   * option java_class = "MyProto";
+   *
+   * message Foo {
+   *   extensions 1000 to max;
+   * }
+   *
+   * extend Foo {
+   *   optional int32 bar;
+   * }
+   * 
+ * + *

Then you might write code like: + * + *

+   * MyProto.Foo foo =
+   *   MyProto.Foo.newBuilder()
+   *     .setExtension(MyProto.bar, 123)
+   *     .build();
+   * 
+ * + *

See also {@link ExtendableMessage}. + */ + @SuppressWarnings("unchecked") + public abstract static class ExtendableBuilder< + MessageType extends ExtendableMessage, + BuilderType extends ExtendableBuilder> + extends Builder + implements ExtendableMessageOrBuilder { + + private FieldSet extensions = FieldSet.emptySet(); + + protected ExtendableBuilder() {} + + protected ExtendableBuilder( + BuilderParent parent) { + super(parent); + } + + // For immutable message conversion. + void internalSetExtensionSet(FieldSet extensions) { + this.extensions = extensions; + } + + @Override + public BuilderType clear() { + extensions = FieldSet.emptySet(); + return super.clear(); + } + + // This is implemented here only to work around an apparent bug in the + // Java compiler and/or build system. See bug #1898463. The mere presence + // of this clone() implementation makes it go away. + @Override + public BuilderType clone() { + return super.clone(); + } + + private void ensureExtensionsIsMutable() { + if (extensions.isImmutable()) { + extensions = extensions.clone(); + } + } + + private void verifyExtensionContainingType( + final Extension extension) { + if (extension.getDescriptor().getContainingType() != + getDescriptorForType()) { + // This can only happen if someone uses unchecked operations. + throw new IllegalArgumentException( + "Extension is for type \"" + + extension.getDescriptor().getContainingType().getFullName() + + "\" which does not match message type \"" + + getDescriptorForType().getFullName() + "\"."); + } + } + + /** Check if a singular extension is present. */ + @Override + public final boolean hasExtension(final ExtensionLite extensionLite) { + Extension extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + return extensions.hasField(extension.getDescriptor()); + } + + /** Get the number of elements in a repeated extension. */ + @Override + public final int getExtensionCount( + final ExtensionLite> extensionLite) { + Extension> extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + final FieldDescriptor descriptor = extension.getDescriptor(); + return extensions.getRepeatedFieldCount(descriptor); + } + + /** Get the value of an extension. */ + @Override + public final Type getExtension(final ExtensionLite extensionLite) { + Extension extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + FieldDescriptor descriptor = extension.getDescriptor(); + final Object value = extensions.getField(descriptor); + if (value == null) { + if (descriptor.isRepeated()) { + return (Type) Collections.emptyList(); + } else if (descriptor.getJavaType() == + FieldDescriptor.JavaType.MESSAGE) { + return (Type) extension.getMessageDefaultInstance(); + } else { + return (Type) extension.fromReflectionType( + descriptor.getDefaultValue()); + } + } else { + return (Type) extension.fromReflectionType(value); + } + } + + /** Get one element of a repeated extension. */ + @Override + public final Type getExtension( + final ExtensionLite> extensionLite, final int index) { + Extension> extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + FieldDescriptor descriptor = extension.getDescriptor(); + return (Type) extension.singularFromReflectionType( + extensions.getRepeatedField(descriptor, index)); + } + + /** Set the value of an extension. */ + public final BuilderType setExtension( + final ExtensionLite extensionLite, + final Type value) { + Extension extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + ensureExtensionsIsMutable(); + final FieldDescriptor descriptor = extension.getDescriptor(); + extensions.setField(descriptor, extension.toReflectionType(value)); + onChanged(); + return (BuilderType) this; + } + + /** Set the value of one element of a repeated extension. */ + public final BuilderType setExtension( + final ExtensionLite> extensionLite, + final int index, final Type value) { + Extension> extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + ensureExtensionsIsMutable(); + final FieldDescriptor descriptor = extension.getDescriptor(); + extensions.setRepeatedField( + descriptor, index, + extension.singularToReflectionType(value)); + onChanged(); + return (BuilderType) this; + } + + /** Append a value to a repeated extension. */ + public final BuilderType addExtension( + final ExtensionLite> extensionLite, + final Type value) { + Extension> extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + ensureExtensionsIsMutable(); + final FieldDescriptor descriptor = extension.getDescriptor(); + extensions.addRepeatedField( + descriptor, extension.singularToReflectionType(value)); + onChanged(); + return (BuilderType) this; + } + + /** Clear an extension. */ + public final BuilderType clearExtension( + final ExtensionLite extensionLite) { + Extension extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + ensureExtensionsIsMutable(); + extensions.clearField(extension.getDescriptor()); + onChanged(); + return (BuilderType) this; + } + + /** Check if a singular extension is present. */ + @Override + public final boolean hasExtension(final Extension extension) { + return hasExtension((ExtensionLite) extension); + } + /** Check if a singular extension is present. */ + @Override + public final boolean hasExtension( + final GeneratedExtension extension) { + return hasExtension((ExtensionLite) extension); + } + /** Get the number of elements in a repeated extension. */ + @Override + public final int getExtensionCount( + final Extension> extension) { + return getExtensionCount((ExtensionLite>) extension); + } + /** Get the number of elements in a repeated extension. */ + @Override + public final int getExtensionCount( + final GeneratedExtension> extension) { + return getExtensionCount((ExtensionLite>) extension); + } + /** Get the value of an extension. */ + @Override + public final Type getExtension(final Extension extension) { + return getExtension((ExtensionLite) extension); + } + /** Get the value of an extension. */ + @Override + public final Type getExtension( + final GeneratedExtension extension) { + return getExtension((ExtensionLite) extension); + } + /** Get the value of an extension. */ + @Override + public final Type getExtension( + final Extension> extension, final int index) { + return getExtension((ExtensionLite>) extension, index); + } + /** Get the value of an extension. */ + @Override + public final Type getExtension( + final GeneratedExtension> extension, final int index) { + return getExtension((ExtensionLite>) extension, index); + } + /** Set the value of an extension. */ + public final BuilderType setExtension( + final Extension extension, final Type value) { + return setExtension((ExtensionLite) extension, value); + } + /** Set the value of an extension. */ + public BuilderType setExtension( + final GeneratedExtension extension, final Type value) { + return setExtension((ExtensionLite) extension, value); + } + /** Set the value of one element of a repeated extension. */ + public final BuilderType setExtension( + final Extension> extension, + final int index, final Type value) { + return setExtension((ExtensionLite>) extension, index, value); + } + /** Set the value of one element of a repeated extension. */ + public BuilderType setExtension( + final GeneratedExtension> extension, + final int index, final Type value) { + return setExtension((ExtensionLite>) extension, index, value); + } + /** Append a value to a repeated extension. */ + public final BuilderType addExtension( + final Extension> extension, final Type value) { + return addExtension((ExtensionLite>) extension, value); + } + /** Append a value to a repeated extension. */ + public BuilderType addExtension( + final GeneratedExtension> extension, final Type value) { + return addExtension((ExtensionLite>) extension, value); + } + /** Clear an extension. */ + public final BuilderType clearExtension( + final Extension extension) { + return clearExtension((ExtensionLite) extension); + } + /** Clear an extension. */ + public BuilderType clearExtension( + final GeneratedExtension extension) { + return clearExtension((ExtensionLite) extension); + } + + /** Called by subclasses to check if all extensions are initialized. */ + protected boolean extensionsAreInitialized() { + return extensions.isInitialized(); + } + + /** + * Called by the build code path to create a copy of the extensions for + * building the message. + */ + private FieldSet buildExtensions() { + extensions.makeImmutable(); + return extensions; + } + + @Override + public boolean isInitialized() { + return super.isInitialized() && extensionsAreInitialized(); + } + + /** + * Called by subclasses to parse an unknown field or an extension. + * @return {@code true} unless the tag is an end-group tag. + */ + @Override + protected boolean parseUnknownField( + final CodedInputStream input, + final UnknownFieldSet.Builder unknownFields, + final ExtensionRegistryLite extensionRegistry, + final int tag) throws IOException { + return MessageReflection.mergeFieldFrom( + input, unknownFields, extensionRegistry, getDescriptorForType(), + new MessageReflection.BuilderAdapter(this), tag); + } + + // --------------------------------------------------------------- + // Reflection + + @Override + public Map getAllFields() { + final Map result = super.getAllFieldsMutable(); + result.putAll(extensions.getAllFields()); + return Collections.unmodifiableMap(result); + } + + @Override + public Object getField(final FieldDescriptor field) { + if (field.isExtension()) { + verifyContainingType(field); + final Object value = extensions.getField(field); + if (value == null) { + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + // Lacking an ExtensionRegistry, we have no way to determine the + // extension's real type, so we return a DynamicMessage. + return DynamicMessage.getDefaultInstance(field.getMessageType()); + } else { + return field.getDefaultValue(); + } + } else { + return value; + } + } else { + return super.getField(field); + } + } + + @Override + public int getRepeatedFieldCount(final FieldDescriptor field) { + if (field.isExtension()) { + verifyContainingType(field); + return extensions.getRepeatedFieldCount(field); + } else { + return super.getRepeatedFieldCount(field); + } + } + + @Override + public Object getRepeatedField(final FieldDescriptor field, + final int index) { + if (field.isExtension()) { + verifyContainingType(field); + return extensions.getRepeatedField(field, index); + } else { + return super.getRepeatedField(field, index); + } + } + + @Override + public boolean hasField(final FieldDescriptor field) { + if (field.isExtension()) { + verifyContainingType(field); + return extensions.hasField(field); + } else { + return super.hasField(field); + } + } + + @Override + public BuilderType setField(final FieldDescriptor field, + final Object value) { + if (field.isExtension()) { + verifyContainingType(field); + ensureExtensionsIsMutable(); + extensions.setField(field, value); + onChanged(); + return (BuilderType) this; + } else { + return super.setField(field, value); + } + } + + @Override + public BuilderType clearField(final FieldDescriptor field) { + if (field.isExtension()) { + verifyContainingType(field); + ensureExtensionsIsMutable(); + extensions.clearField(field); + onChanged(); + return (BuilderType) this; + } else { + return super.clearField(field); + } + } + + @Override + public BuilderType setRepeatedField(final FieldDescriptor field, + final int index, final Object value) { + if (field.isExtension()) { + verifyContainingType(field); + ensureExtensionsIsMutable(); + extensions.setRepeatedField(field, index, value); + onChanged(); + return (BuilderType) this; + } else { + return super.setRepeatedField(field, index, value); + } + } + + @Override + public BuilderType addRepeatedField(final FieldDescriptor field, + final Object value) { + if (field.isExtension()) { + verifyContainingType(field); + ensureExtensionsIsMutable(); + extensions.addRepeatedField(field, value); + onChanged(); + return (BuilderType) this; + } else { + return super.addRepeatedField(field, value); + } + } + + protected final void mergeExtensionFields(final ExtendableMessage other) { + ensureExtensionsIsMutable(); + extensions.mergeFrom(other.extensions); + onChanged(); + } + + private void verifyContainingType(final FieldDescriptor field) { + if (field.getContainingType() != getDescriptorForType()) { + throw new IllegalArgumentException( + "FieldDescriptor does not match message type."); + } + } + } + + // ----------------------------------------------------------------- + + /** + * Gets the descriptor for an extension. The implementation depends on whether + * the extension is scoped in the top level of a file or scoped in a Message. + */ + static interface ExtensionDescriptorRetriever { + FieldDescriptor getDescriptor(); + } + + /** For use by generated code only. */ + public static + GeneratedExtension + newMessageScopedGeneratedExtension(final Message scope, + final int descriptorIndex, + final Class singularType, + final Message defaultInstance) { + // For extensions scoped within a Message, we use the Message to resolve + // the outer class's descriptor, from which the extension descriptor is + // obtained. + return new GeneratedExtension( + new CachedDescriptorRetriever() { + @Override + public FieldDescriptor loadDescriptor() { + return scope.getDescriptorForType().getExtensions().get(descriptorIndex); + } + }, + singularType, + defaultInstance, + Extension.ExtensionType.IMMUTABLE); + } + + /** For use by generated code only. */ + public static + GeneratedExtension + newFileScopedGeneratedExtension(final Class singularType, + final Message defaultInstance) { + // For extensions scoped within a file, we rely on the outer class's + // static initializer to call internalInit() on the extension when the + // descriptor is available. + return new GeneratedExtension( + null, // ExtensionDescriptorRetriever is initialized in internalInit(); + singularType, + defaultInstance, + Extension.ExtensionType.IMMUTABLE); + } + + private abstract static class CachedDescriptorRetriever + implements ExtensionDescriptorRetriever { + private volatile FieldDescriptor descriptor; + protected abstract FieldDescriptor loadDescriptor(); + + @Override + public FieldDescriptor getDescriptor() { + if (descriptor == null) { + synchronized (this) { + if (descriptor == null) { + descriptor = loadDescriptor(); + } + } + } + return descriptor; + } + } + + /** + * Used in proto1 generated code only. + * + * After enabling bridge, we can define proto2 extensions (the extended type + * is a proto2 mutable message) in a proto1 .proto file. For these extensions + * we should generate proto2 GeneratedExtensions. + */ + public static + GeneratedExtension + newMessageScopedGeneratedExtension( + final Message scope, final String name, + final Class singularType, final Message defaultInstance) { + // For extensions scoped within a Message, we use the Message to resolve + // the outer class's descriptor, from which the extension descriptor is + // obtained. + return new GeneratedExtension( + new CachedDescriptorRetriever() { + @Override + protected FieldDescriptor loadDescriptor() { + return scope.getDescriptorForType().findFieldByName(name); + } + }, + singularType, + defaultInstance, + Extension.ExtensionType.MUTABLE); + } + + /** + * Used in proto1 generated code only. + * + * After enabling bridge, we can define proto2 extensions (the extended type + * is a proto2 mutable message) in a proto1 .proto file. For these extensions + * we should generate proto2 GeneratedExtensions. + */ + public static + GeneratedExtension + newFileScopedGeneratedExtension( + final Class singularType, final Message defaultInstance, + final String descriptorOuterClass, final String extensionName) { + // For extensions scoped within a file, we load the descriptor outer + // class and rely on it to get the FileDescriptor which then can be + // used to obtain the extension's FieldDescriptor. + return new GeneratedExtension( + new CachedDescriptorRetriever() { + @Override + protected FieldDescriptor loadDescriptor() { + try { + Class clazz = singularType.getClassLoader().loadClass(descriptorOuterClass); + FileDescriptor file = (FileDescriptor) clazz.getField("descriptor").get(null); + return file.findExtensionByName(extensionName); + } catch (Exception e) { + throw new RuntimeException( + "Cannot load descriptors: " + + descriptorOuterClass + + " is not a valid descriptor class name", + e); + } + } + }, + singularType, + defaultInstance, + Extension.ExtensionType.MUTABLE); + } + + /** + * Type used to represent generated extensions. The protocol compiler + * generates a static singleton instance of this class for each extension. + * + *

For example, imagine you have the {@code .proto} file: + * + *

+   * option java_class = "MyProto";
+   *
+   * message Foo {
+   *   extensions 1000 to max;
+   * }
+   *
+   * extend Foo {
+   *   optional int32 bar;
+   * }
+   * 
+ * + *

Then, {@code MyProto.Foo.bar} has type + * {@code GeneratedExtension}. + * + *

In general, users should ignore the details of this type, and simply use + * these static singletons as parameters to the extension accessors defined + * in {@link ExtendableMessage} and {@link ExtendableBuilder}. + */ + public static class GeneratedExtension< + ContainingType extends Message, Type> extends + Extension { + // TODO(kenton): Find ways to avoid using Java reflection within this + // class. Also try to avoid suppressing unchecked warnings. + + // We can't always initialize the descriptor of a GeneratedExtension when + // we first construct it due to initialization order difficulties (namely, + // the descriptor may not have been constructed yet, since it is often + // constructed by the initializer of a separate module). + // + // In the case of nested extensions, we initialize the + // ExtensionDescriptorRetriever with an instance that uses the scoping + // Message's default instance to retrieve the extension's descriptor. + // + // In the case of non-nested extensions, we initialize the + // ExtensionDescriptorRetriever to null and rely on the outer class's static + // initializer to call internalInit() after the descriptor has been parsed. + GeneratedExtension(ExtensionDescriptorRetriever descriptorRetriever, + Class singularType, + Message messageDefaultInstance, + ExtensionType extensionType) { + if (Message.class.isAssignableFrom(singularType) && + !singularType.isInstance(messageDefaultInstance)) { + throw new IllegalArgumentException( + "Bad messageDefaultInstance for " + singularType.getName()); + } + this.descriptorRetriever = descriptorRetriever; + this.singularType = singularType; + this.messageDefaultInstance = messageDefaultInstance; + + if (ProtocolMessageEnum.class.isAssignableFrom(singularType)) { + this.enumValueOf = getMethodOrDie(singularType, "valueOf", + EnumValueDescriptor.class); + this.enumGetValueDescriptor = + getMethodOrDie(singularType, "getValueDescriptor"); + } else { + this.enumValueOf = null; + this.enumGetValueDescriptor = null; + } + this.extensionType = extensionType; + } + + /** For use by generated code only. */ + public void internalInit(final FieldDescriptor descriptor) { + if (descriptorRetriever != null) { + throw new IllegalStateException("Already initialized."); + } + descriptorRetriever = + new ExtensionDescriptorRetriever() { + @Override + public FieldDescriptor getDescriptor() { + return descriptor; + } + }; + } + + private ExtensionDescriptorRetriever descriptorRetriever; + private final Class singularType; + private final Message messageDefaultInstance; + private final Method enumValueOf; + private final Method enumGetValueDescriptor; + private final ExtensionType extensionType; + + @Override + public FieldDescriptor getDescriptor() { + if (descriptorRetriever == null) { + throw new IllegalStateException( + "getDescriptor() called before internalInit()"); + } + return descriptorRetriever.getDescriptor(); + } + + /** + * If the extension is an embedded message or group, returns the default + * instance of the message. + */ + @Override + public Message getMessageDefaultInstance() { + return messageDefaultInstance; + } + + @Override + protected ExtensionType getExtensionType() { + return extensionType; + } + + /** + * Convert from the type used by the reflection accessors to the type used + * by native accessors. E.g., for enums, the reflection accessors use + * EnumValueDescriptors but the native accessors use the generated enum + * type. + */ + @Override + @SuppressWarnings("unchecked") + protected Object fromReflectionType(final Object value) { + FieldDescriptor descriptor = getDescriptor(); + if (descriptor.isRepeated()) { + if (descriptor.getJavaType() == FieldDescriptor.JavaType.MESSAGE || + descriptor.getJavaType() == FieldDescriptor.JavaType.ENUM) { + // Must convert the whole list. + final List result = new ArrayList(); + for (final Object element : (List) value) { + result.add(singularFromReflectionType(element)); + } + return result; + } else { + return value; + } + } else { + return singularFromReflectionType(value); + } + } + + /** + * Like {@link #fromReflectionType(Object)}, but if the type is a repeated + * type, this converts a single element. + */ + @Override + protected Object singularFromReflectionType(final Object value) { + FieldDescriptor descriptor = getDescriptor(); + switch (descriptor.getJavaType()) { + case MESSAGE: + if (singularType.isInstance(value)) { + return value; + } else { + return messageDefaultInstance.newBuilderForType() + .mergeFrom((Message) value).build(); + } + case ENUM: + return invokeOrDie(enumValueOf, null, (EnumValueDescriptor) value); + default: + return value; + } + } + + /** + * Convert from the type used by the native accessors to the type used + * by reflection accessors. E.g., for enums, the reflection accessors use + * EnumValueDescriptors but the native accessors use the generated enum + * type. + */ + @Override + @SuppressWarnings("unchecked") + protected Object toReflectionType(final Object value) { + FieldDescriptor descriptor = getDescriptor(); + if (descriptor.isRepeated()) { + if (descriptor.getJavaType() == FieldDescriptor.JavaType.ENUM) { + // Must convert the whole list. + final List result = new ArrayList(); + for (final Object element : (List) value) { + result.add(singularToReflectionType(element)); + } + return result; + } else { + return value; + } + } else { + return singularToReflectionType(value); + } + } + + /** + * Like {@link #toReflectionType(Object)}, but if the type is a repeated + * type, this converts a single element. + */ + @Override + protected Object singularToReflectionType(final Object value) { + FieldDescriptor descriptor = getDescriptor(); + switch (descriptor.getJavaType()) { + case ENUM: + return invokeOrDie(enumGetValueDescriptor, value); + default: + return value; + } + } + + @Override + public int getNumber() { + return getDescriptor().getNumber(); + } + + @Override + public WireFormat.FieldType getLiteType() { + return getDescriptor().getLiteType(); + } + + @Override + public boolean isRepeated() { + return getDescriptor().isRepeated(); + } + + @Override + @SuppressWarnings("unchecked") + public Type getDefaultValue() { + if (isRepeated()) { + return (Type) Collections.emptyList(); + } + if (getDescriptor().getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + return (Type) messageDefaultInstance; + } + return (Type) singularFromReflectionType( + getDescriptor().getDefaultValue()); + } + } + + // ================================================================= + + /** Calls Class.getMethod and throws a RuntimeException if it fails. */ + @SuppressWarnings("unchecked") + private static Method getMethodOrDie( + final Class clazz, final String name, final Class... params) { + try { + return clazz.getMethod(name, params); + } catch (NoSuchMethodException e) { + throw new RuntimeException( + "Generated message class \"" + clazz.getName() + + "\" missing method \"" + name + "\".", e); + } + } + + /** Calls invoke and throws a RuntimeException if it fails. */ + private static Object invokeOrDie( + final Method method, final Object object, final Object... params) { + try { + return method.invoke(object, params); + } catch (IllegalAccessException e) { + throw new RuntimeException( + "Couldn't use Java reflection to implement protocol message " + + "reflection.", e); + } catch (InvocationTargetException e) { + final Throwable cause = e.getCause(); + if (cause instanceof RuntimeException) { + throw (RuntimeException) cause; + } else if (cause instanceof Error) { + throw (Error) cause; + } else { + throw new RuntimeException( + "Unexpected exception thrown by generated accessor method.", cause); + } + } + } + + /** + * Gets the map field with the given field number. This method should be + * overridden in the generated message class if the message contains map + * fields. + * + * Unlike other field types, reflection support for map fields can't be + * implemented based on generated public API because we need to access a + * map field as a list in reflection API but the generated API only allows + * us to access it as a map. This method returns the underlying map field + * directly and thus enables us to access the map field as a list. + */ + @SuppressWarnings({"rawtypes", "unused"}) + protected MapField internalGetMapField(int fieldNumber) { + // Note that we can't use descriptor names here because this method will + // be called when descriptor is being initialized. + throw new RuntimeException( + "No map fields found in " + getClass().getName()); + } + + /** + * Users should ignore this class. This class provides the implementation + * with access to the fields of a message object using Java reflection. + */ + public static final class FieldAccessorTable { + + /** + * Construct a FieldAccessorTable for a particular message class. Only + * one FieldAccessorTable should ever be constructed per class. + * + * @param descriptor The type's descriptor. + * @param camelCaseNames The camelcase names of all fields in the message. + * These are used to derive the accessor method names. + * @param messageClass The message type. + * @param builderClass The builder type. + */ + public FieldAccessorTable( + final Descriptor descriptor, + final String[] camelCaseNames, + final Class messageClass, + final Class builderClass) { + this(descriptor, camelCaseNames); + ensureFieldAccessorsInitialized(messageClass, builderClass); + } + + /** + * Construct a FieldAccessorTable for a particular message class without + * initializing FieldAccessors. + */ + public FieldAccessorTable( + final Descriptor descriptor, + final String[] camelCaseNames) { + this.descriptor = descriptor; + this.camelCaseNames = camelCaseNames; + fields = new FieldAccessor[descriptor.getFields().size()]; + oneofs = new OneofAccessor[descriptor.getOneofs().size()]; + initialized = false; + } + + private boolean isMapFieldEnabled(FieldDescriptor field) { + boolean result = true; + return result; + } + + /** + * Ensures the field accessors are initialized. This method is thread-safe. + * + * @param messageClass The message type. + * @param builderClass The builder type. + * @return this + */ + public FieldAccessorTable ensureFieldAccessorsInitialized( + Class messageClass, + Class builderClass) { + if (initialized) { return this; } + synchronized (this) { + if (initialized) { return this; } + int fieldsSize = fields.length; + for (int i = 0; i < fieldsSize; i++) { + FieldDescriptor field = descriptor.getFields().get(i); + String containingOneofCamelCaseName = null; + if (field.getContainingOneof() != null) { + containingOneofCamelCaseName = + camelCaseNames[fieldsSize + field.getContainingOneof().getIndex()]; + } + if (field.isRepeated()) { + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + if (field.isMapField() && isMapFieldEnabled(field)) { + fields[i] = new MapFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass); + } else { + fields[i] = new RepeatedMessageFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass); + } + } else if (field.getJavaType() == FieldDescriptor.JavaType.ENUM) { + fields[i] = new RepeatedEnumFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass); + } else { + fields[i] = new RepeatedFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass); + } + } else { + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + fields[i] = new SingularMessageFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass, + containingOneofCamelCaseName); + } else if (field.getJavaType() == FieldDescriptor.JavaType.ENUM) { + fields[i] = new SingularEnumFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass, + containingOneofCamelCaseName); + } else if (field.getJavaType() == FieldDescriptor.JavaType.STRING) { + fields[i] = new SingularStringFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass, + containingOneofCamelCaseName); + } else { + fields[i] = new SingularFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass, + containingOneofCamelCaseName); + } + } + } + + int oneofsSize = oneofs.length; + for (int i = 0; i < oneofsSize; i++) { + oneofs[i] = new OneofAccessor( + descriptor, camelCaseNames[i + fieldsSize], + messageClass, builderClass); + } + initialized = true; + camelCaseNames = null; + return this; + } + } + + private final Descriptor descriptor; + private final FieldAccessor[] fields; + private String[] camelCaseNames; + private final OneofAccessor[] oneofs; + private volatile boolean initialized; + + /** Get the FieldAccessor for a particular field. */ + private FieldAccessor getField(final FieldDescriptor field) { + if (field.getContainingType() != descriptor) { + throw new IllegalArgumentException( + "FieldDescriptor does not match message type."); + } else if (field.isExtension()) { + // If this type had extensions, it would subclass ExtendableMessage, + // which overrides the reflection interface to handle extensions. + throw new IllegalArgumentException( + "This type does not have extensions."); + } + return fields[field.getIndex()]; + } + + /** Get the OneofAccessor for a particular oneof. */ + private OneofAccessor getOneof(final OneofDescriptor oneof) { + if (oneof.getContainingType() != descriptor) { + throw new IllegalArgumentException( + "OneofDescriptor does not match message type."); + } + return oneofs[oneof.getIndex()]; + } + + /** + * Abstract interface that provides access to a single field. This is + * implemented differently depending on the field type and cardinality. + */ + private interface FieldAccessor { + Object get(GeneratedMessage message); + Object get(GeneratedMessage.Builder builder); + Object getRaw(GeneratedMessage message); + Object getRaw(GeneratedMessage.Builder builder); + void set(Builder builder, Object value); + Object getRepeated(GeneratedMessage message, int index); + Object getRepeated(GeneratedMessage.Builder builder, int index); + Object getRepeatedRaw(GeneratedMessage message, int index); + Object getRepeatedRaw(GeneratedMessage.Builder builder, int index); + void setRepeated(Builder builder, + int index, Object value); + void addRepeated(Builder builder, Object value); + boolean has(GeneratedMessage message); + boolean has(GeneratedMessage.Builder builder); + int getRepeatedCount(GeneratedMessage message); + int getRepeatedCount(GeneratedMessage.Builder builder); + void clear(Builder builder); + Message.Builder newBuilder(); + Message.Builder getBuilder(GeneratedMessage.Builder builder); + Message.Builder getRepeatedBuilder(GeneratedMessage.Builder builder, + int index); + } + + /** OneofAccessor provides access to a single oneof. */ + private static class OneofAccessor { + OneofAccessor( + final Descriptor descriptor, final String camelCaseName, + final Class messageClass, + final Class builderClass) { + this.descriptor = descriptor; + caseMethod = + getMethodOrDie(messageClass, "get" + camelCaseName + "Case"); + caseMethodBuilder = + getMethodOrDie(builderClass, "get" + camelCaseName + "Case"); + clearMethod = getMethodOrDie(builderClass, "clear" + camelCaseName); + } + + private final Descriptor descriptor; + private final Method caseMethod; + private final Method caseMethodBuilder; + private final Method clearMethod; + + public boolean has(final GeneratedMessage message) { + if (((Internal.EnumLite) invokeOrDie(caseMethod, message)).getNumber() == 0) { + return false; + } + return true; + } + + public boolean has(GeneratedMessage.Builder builder) { + if (((Internal.EnumLite) invokeOrDie(caseMethodBuilder, builder)).getNumber() == 0) { + return false; + } + return true; + } + + public FieldDescriptor get(final GeneratedMessage message) { + int fieldNumber = ((Internal.EnumLite) invokeOrDie(caseMethod, message)).getNumber(); + if (fieldNumber > 0) { + return descriptor.findFieldByNumber(fieldNumber); + } + return null; + } + + public FieldDescriptor get(GeneratedMessage.Builder builder) { + int fieldNumber = ((Internal.EnumLite) invokeOrDie(caseMethodBuilder, builder)).getNumber(); + if (fieldNumber > 0) { + return descriptor.findFieldByNumber(fieldNumber); + } + return null; + } + + public void clear(final Builder builder) { + invokeOrDie(clearMethod, builder); + } + } + + private static boolean supportFieldPresence(FileDescriptor file) { + return file.getSyntax() == FileDescriptor.Syntax.PROTO2; + } + + // --------------------------------------------------------------- + + private static class SingularFieldAccessor implements FieldAccessor { + SingularFieldAccessor( + final FieldDescriptor descriptor, final String camelCaseName, + final Class messageClass, + final Class builderClass, + final String containingOneofCamelCaseName) { + field = descriptor; + isOneofField = descriptor.getContainingOneof() != null; + hasHasMethod = supportFieldPresence(descriptor.getFile()) + || (!isOneofField && descriptor.getJavaType() == FieldDescriptor.JavaType.MESSAGE); + getMethod = getMethodOrDie(messageClass, "get" + camelCaseName); + getMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName); + type = getMethod.getReturnType(); + setMethod = getMethodOrDie(builderClass, "set" + camelCaseName, type); + hasMethod = + hasHasMethod ? getMethodOrDie(messageClass, "has" + camelCaseName) : null; + hasMethodBuilder = + hasHasMethod ? getMethodOrDie(builderClass, "has" + camelCaseName) : null; + clearMethod = getMethodOrDie(builderClass, "clear" + camelCaseName); + caseMethod = isOneofField ? getMethodOrDie( + messageClass, "get" + containingOneofCamelCaseName + "Case") : null; + caseMethodBuilder = isOneofField ? getMethodOrDie( + builderClass, "get" + containingOneofCamelCaseName + "Case") : null; + } + + // Note: We use Java reflection to call public methods rather than + // access private fields directly as this avoids runtime security + // checks. + protected final Class type; + protected final Method getMethod; + protected final Method getMethodBuilder; + protected final Method setMethod; + protected final Method hasMethod; + protected final Method hasMethodBuilder; + protected final Method clearMethod; + protected final Method caseMethod; + protected final Method caseMethodBuilder; + protected final FieldDescriptor field; + protected final boolean isOneofField; + protected final boolean hasHasMethod; + + private int getOneofFieldNumber(final GeneratedMessage message) { + return ((Internal.EnumLite) invokeOrDie(caseMethod, message)).getNumber(); + } + + private int getOneofFieldNumber(final GeneratedMessage.Builder builder) { + return ((Internal.EnumLite) invokeOrDie(caseMethodBuilder, builder)).getNumber(); + } + + @Override + public Object get(final GeneratedMessage message) { + return invokeOrDie(getMethod, message); + } + @Override + public Object get(GeneratedMessage.Builder builder) { + return invokeOrDie(getMethodBuilder, builder); + } + @Override + public Object getRaw(final GeneratedMessage message) { + return get(message); + } + @Override + public Object getRaw(GeneratedMessage.Builder builder) { + return get(builder); + } + @Override + public void set(final Builder builder, final Object value) { + invokeOrDie(setMethod, builder, value); + } + @Override + public Object getRepeated(final GeneratedMessage message, final int index) { + throw new UnsupportedOperationException( + "getRepeatedField() called on a singular field."); + } + @Override + public Object getRepeatedRaw(final GeneratedMessage message, final int index) { + throw new UnsupportedOperationException( + "getRepeatedFieldRaw() called on a singular field."); + } + @Override + public Object getRepeated(GeneratedMessage.Builder builder, int index) { + throw new UnsupportedOperationException( + "getRepeatedField() called on a singular field."); + } + @Override + public Object getRepeatedRaw(GeneratedMessage.Builder builder, int index) { + throw new UnsupportedOperationException( + "getRepeatedFieldRaw() called on a singular field."); + } + @Override + public void setRepeated(final Builder builder, final int index, final Object value) { + throw new UnsupportedOperationException( + "setRepeatedField() called on a singular field."); + } + @Override + public void addRepeated(final Builder builder, final Object value) { + throw new UnsupportedOperationException( + "addRepeatedField() called on a singular field."); + } + @Override + public boolean has(final GeneratedMessage message) { + if (!hasHasMethod) { + if (isOneofField) { + return getOneofFieldNumber(message) == field.getNumber(); + } + return !get(message).equals(field.getDefaultValue()); + } + return (Boolean) invokeOrDie(hasMethod, message); + } + @Override + public boolean has(GeneratedMessage.Builder builder) { + if (!hasHasMethod) { + if (isOneofField) { + return getOneofFieldNumber(builder) == field.getNumber(); + } + return !get(builder).equals(field.getDefaultValue()); + } + return (Boolean) invokeOrDie(hasMethodBuilder, builder); + } + @Override + public int getRepeatedCount(final GeneratedMessage message) { + throw new UnsupportedOperationException( + "getRepeatedFieldSize() called on a singular field."); + } + @Override + public int getRepeatedCount(GeneratedMessage.Builder builder) { + throw new UnsupportedOperationException( + "getRepeatedFieldSize() called on a singular field."); + } + @Override + public void clear(final Builder builder) { + invokeOrDie(clearMethod, builder); + } + @Override + public Message.Builder newBuilder() { + throw new UnsupportedOperationException( + "newBuilderForField() called on a non-Message type."); + } + @Override + public Message.Builder getBuilder(GeneratedMessage.Builder builder) { + throw new UnsupportedOperationException( + "getFieldBuilder() called on a non-Message type."); + } + @Override + public Message.Builder getRepeatedBuilder(GeneratedMessage.Builder builder, int index) { + throw new UnsupportedOperationException( + "getRepeatedFieldBuilder() called on a non-Message type."); + } + } + + private static class RepeatedFieldAccessor implements FieldAccessor { + protected final Class type; + protected final Method getMethod; + protected final Method getMethodBuilder; + protected final Method getRepeatedMethod; + protected final Method getRepeatedMethodBuilder; + protected final Method setRepeatedMethod; + protected final Method addRepeatedMethod; + protected final Method getCountMethod; + protected final Method getCountMethodBuilder; + protected final Method clearMethod; + + RepeatedFieldAccessor( + final FieldDescriptor descriptor, final String camelCaseName, + final Class messageClass, + final Class builderClass) { + getMethod = getMethodOrDie(messageClass, + "get" + camelCaseName + "List"); + getMethodBuilder = getMethodOrDie(builderClass, + "get" + camelCaseName + "List"); + getRepeatedMethod = + getMethodOrDie(messageClass, "get" + camelCaseName, Integer.TYPE); + getRepeatedMethodBuilder = + getMethodOrDie(builderClass, "get" + camelCaseName, Integer.TYPE); + type = getRepeatedMethod.getReturnType(); + setRepeatedMethod = + getMethodOrDie(builderClass, "set" + camelCaseName, + Integer.TYPE, type); + addRepeatedMethod = + getMethodOrDie(builderClass, "add" + camelCaseName, type); + getCountMethod = + getMethodOrDie(messageClass, "get" + camelCaseName + "Count"); + getCountMethodBuilder = + getMethodOrDie(builderClass, "get" + camelCaseName + "Count"); + + clearMethod = getMethodOrDie(builderClass, "clear" + camelCaseName); + } + + @Override + public Object get(final GeneratedMessage message) { + return invokeOrDie(getMethod, message); + } + @Override + public Object get(GeneratedMessage.Builder builder) { + return invokeOrDie(getMethodBuilder, builder); + } + @Override + public Object getRaw(final GeneratedMessage message) { + return get(message); + } + @Override + public Object getRaw(GeneratedMessage.Builder builder) { + return get(builder); + } + @Override + public void set(final Builder builder, final Object value) { + // Add all the elements individually. This serves two purposes: + // 1) Verifies that each element has the correct type. + // 2) Insures that the caller cannot modify the list later on and + // have the modifications be reflected in the message. + clear(builder); + for (final Object element : (List) value) { + addRepeated(builder, element); + } + } + @Override + public Object getRepeated(final GeneratedMessage message, final int index) { + return invokeOrDie(getRepeatedMethod, message, index); + } + @Override + public Object getRepeated(GeneratedMessage.Builder builder, int index) { + return invokeOrDie(getRepeatedMethodBuilder, builder, index); + } + @Override + public Object getRepeatedRaw(GeneratedMessage message, int index) { + return getRepeated(message, index); + } + @Override + public Object getRepeatedRaw(GeneratedMessage.Builder builder, int index) { + return getRepeated(builder, index); + } + @Override + public void setRepeated(final Builder builder, final int index, final Object value) { + invokeOrDie(setRepeatedMethod, builder, index, value); + } + @Override + public void addRepeated(final Builder builder, final Object value) { + invokeOrDie(addRepeatedMethod, builder, value); + } + @Override + public boolean has(final GeneratedMessage message) { + throw new UnsupportedOperationException( + "hasField() called on a repeated field."); + } + @Override + public boolean has(GeneratedMessage.Builder builder) { + throw new UnsupportedOperationException( + "hasField() called on a repeated field."); + } + @Override + public int getRepeatedCount(final GeneratedMessage message) { + return (Integer) invokeOrDie(getCountMethod, message); + } + @Override + public int getRepeatedCount(GeneratedMessage.Builder builder) { + return (Integer) invokeOrDie(getCountMethodBuilder, builder); + } + @Override + public void clear(final Builder builder) { + invokeOrDie(clearMethod, builder); + } + @Override + public Message.Builder newBuilder() { + throw new UnsupportedOperationException( + "newBuilderForField() called on a non-Message type."); + } + @Override + public Message.Builder getBuilder(GeneratedMessage.Builder builder) { + throw new UnsupportedOperationException( + "getFieldBuilder() called on a non-Message type."); + } + @Override + public Message.Builder getRepeatedBuilder(GeneratedMessage.Builder builder, int index) { + throw new UnsupportedOperationException( + "getRepeatedFieldBuilder() called on a non-Message type."); + } + } + + private static class MapFieldAccessor implements FieldAccessor { + MapFieldAccessor( + final FieldDescriptor descriptor, final String camelCaseName, + final Class messageClass, + final Class builderClass) { + field = descriptor; + Method getDefaultInstanceMethod = + getMethodOrDie(messageClass, "getDefaultInstance"); + MapField defaultMapField = getMapField( + (GeneratedMessage) invokeOrDie(getDefaultInstanceMethod, null)); + mapEntryMessageDefaultInstance = + defaultMapField.getMapEntryMessageDefaultInstance(); + } + + private final FieldDescriptor field; + private final Message mapEntryMessageDefaultInstance; + + private MapField getMapField(GeneratedMessage message) { + return (MapField) message.internalGetMapField(field.getNumber()); + } + + private MapField getMapField(GeneratedMessage.Builder builder) { + return (MapField) builder.internalGetMapField(field.getNumber()); + } + + private MapField getMutableMapField( + GeneratedMessage.Builder builder) { + return (MapField) builder.internalGetMutableMapField( + field.getNumber()); + } + + @Override + @SuppressWarnings("unchecked") + public Object get(GeneratedMessage message) { + List result = new ArrayList(); + for (int i = 0; i < getRepeatedCount(message); i++) { + result.add(getRepeated(message, i)); + } + return Collections.unmodifiableList(result); + } + + @Override + @SuppressWarnings("unchecked") + public Object get(Builder builder) { + List result = new ArrayList(); + for (int i = 0; i < getRepeatedCount(builder); i++) { + result.add(getRepeated(builder, i)); + } + return Collections.unmodifiableList(result); + } + + @Override + public Object getRaw(GeneratedMessage message) { + return get(message); + } + + @Override + public Object getRaw(GeneratedMessage.Builder builder) { + return get(builder); + } + + @Override + public void set(Builder builder, Object value) { + clear(builder); + for (Object entry : (List) value) { + addRepeated(builder, entry); + } + } + + @Override + public Object getRepeated(GeneratedMessage message, int index) { + return getMapField(message).getList().get(index); + } + + @Override + public Object getRepeated(Builder builder, int index) { + return getMapField(builder).getList().get(index); + } + + @Override + public Object getRepeatedRaw(GeneratedMessage message, int index) { + return getRepeated(message, index); + } + + @Override + public Object getRepeatedRaw(Builder builder, int index) { + return getRepeated(builder, index); + } + + @Override + public void setRepeated(Builder builder, int index, Object value) { + getMutableMapField(builder).getMutableList().set(index, (Message) value); + } + + @Override + public void addRepeated(Builder builder, Object value) { + getMutableMapField(builder).getMutableList().add((Message) value); + } + + @Override + public boolean has(GeneratedMessage message) { + throw new UnsupportedOperationException( + "hasField() is not supported for repeated fields."); + } + + @Override + public boolean has(Builder builder) { + throw new UnsupportedOperationException( + "hasField() is not supported for repeated fields."); + } + + @Override + public int getRepeatedCount(GeneratedMessage message) { + return getMapField(message).getList().size(); + } + + @Override + public int getRepeatedCount(Builder builder) { + return getMapField(builder).getList().size(); + } + + @Override + public void clear(Builder builder) { + getMutableMapField(builder).getMutableList().clear(); + } + + @Override + public com.google.protobuf.Message.Builder newBuilder() { + return mapEntryMessageDefaultInstance.newBuilderForType(); + } + + @Override + public com.google.protobuf.Message.Builder getBuilder(Builder builder) { + throw new UnsupportedOperationException( + "Nested builder not supported for map fields."); + } + + @Override + public com.google.protobuf.Message.Builder getRepeatedBuilder(Builder builder, int index) { + throw new UnsupportedOperationException( + "Nested builder not supported for map fields."); + } + } + + // --------------------------------------------------------------- + + private static final class SingularEnumFieldAccessor + extends SingularFieldAccessor { + SingularEnumFieldAccessor( + final FieldDescriptor descriptor, final String camelCaseName, + final Class messageClass, + final Class builderClass, + final String containingOneofCamelCaseName) { + super(descriptor, camelCaseName, messageClass, builderClass, containingOneofCamelCaseName); + + enumDescriptor = descriptor.getEnumType(); + + valueOfMethod = getMethodOrDie(type, "valueOf", + EnumValueDescriptor.class); + getValueDescriptorMethod = + getMethodOrDie(type, "getValueDescriptor"); + + supportUnknownEnumValue = descriptor.getFile().supportsUnknownEnumValue(); + if (supportUnknownEnumValue) { + getValueMethod = + getMethodOrDie(messageClass, "get" + camelCaseName + "Value"); + getValueMethodBuilder = + getMethodOrDie(builderClass, "get" + camelCaseName + "Value"); + setValueMethod = + getMethodOrDie(builderClass, "set" + camelCaseName + "Value", int.class); + } + } + + private EnumDescriptor enumDescriptor; + + private Method valueOfMethod; + private Method getValueDescriptorMethod; + + private boolean supportUnknownEnumValue; + private Method getValueMethod; + private Method getValueMethodBuilder; + private Method setValueMethod; + + @Override + public Object get(final GeneratedMessage message) { + if (supportUnknownEnumValue) { + int value = (Integer) invokeOrDie(getValueMethod, message); + return enumDescriptor.findValueByNumberCreatingIfUnknown(value); + } + return invokeOrDie(getValueDescriptorMethod, super.get(message)); + } + + @Override + public Object get(final GeneratedMessage.Builder builder) { + if (supportUnknownEnumValue) { + int value = (Integer) invokeOrDie(getValueMethodBuilder, builder); + return enumDescriptor.findValueByNumberCreatingIfUnknown(value); + } + return invokeOrDie(getValueDescriptorMethod, super.get(builder)); + } + + @Override + public void set(final Builder builder, final Object value) { + if (supportUnknownEnumValue) { + invokeOrDie(setValueMethod, builder, + ((EnumValueDescriptor) value).getNumber()); + return; + } + super.set(builder, invokeOrDie(valueOfMethod, null, value)); + } + } + + private static final class RepeatedEnumFieldAccessor + extends RepeatedFieldAccessor { + RepeatedEnumFieldAccessor( + final FieldDescriptor descriptor, final String camelCaseName, + final Class messageClass, + final Class builderClass) { + super(descriptor, camelCaseName, messageClass, builderClass); + + enumDescriptor = descriptor.getEnumType(); + + valueOfMethod = getMethodOrDie(type, "valueOf", + EnumValueDescriptor.class); + getValueDescriptorMethod = + getMethodOrDie(type, "getValueDescriptor"); + + supportUnknownEnumValue = descriptor.getFile().supportsUnknownEnumValue(); + if (supportUnknownEnumValue) { + getRepeatedValueMethod = + getMethodOrDie(messageClass, "get" + camelCaseName + "Value", int.class); + getRepeatedValueMethodBuilder = + getMethodOrDie(builderClass, "get" + camelCaseName + "Value", int.class); + setRepeatedValueMethod = + getMethodOrDie(builderClass, "set" + camelCaseName + "Value", int.class, int.class); + addRepeatedValueMethod = + getMethodOrDie(builderClass, "add" + camelCaseName + "Value", int.class); + } + } + private EnumDescriptor enumDescriptor; + + private final Method valueOfMethod; + private final Method getValueDescriptorMethod; + + private boolean supportUnknownEnumValue; + private Method getRepeatedValueMethod; + private Method getRepeatedValueMethodBuilder; + private Method setRepeatedValueMethod; + private Method addRepeatedValueMethod; + + @Override + @SuppressWarnings("unchecked") + public Object get(final GeneratedMessage message) { + final List newList = new ArrayList(); + final int size = getRepeatedCount(message); + for (int i = 0; i < size; i++) { + newList.add(getRepeated(message, i)); + } + return Collections.unmodifiableList(newList); + } + + @Override + @SuppressWarnings("unchecked") + public Object get(final GeneratedMessage.Builder builder) { + final List newList = new ArrayList(); + final int size = getRepeatedCount(builder); + for (int i = 0; i < size; i++) { + newList.add(getRepeated(builder, i)); + } + return Collections.unmodifiableList(newList); + } + + @Override + public Object getRepeated(final GeneratedMessage message, + final int index) { + if (supportUnknownEnumValue) { + int value = (Integer) invokeOrDie(getRepeatedValueMethod, message, index); + return enumDescriptor.findValueByNumberCreatingIfUnknown(value); + } + return invokeOrDie(getValueDescriptorMethod, + super.getRepeated(message, index)); + } + @Override + public Object getRepeated(final GeneratedMessage.Builder builder, + final int index) { + if (supportUnknownEnumValue) { + int value = (Integer) invokeOrDie(getRepeatedValueMethodBuilder, builder, index); + return enumDescriptor.findValueByNumberCreatingIfUnknown(value); + } + return invokeOrDie(getValueDescriptorMethod, + super.getRepeated(builder, index)); + } + @Override + public void setRepeated(final Builder builder, + final int index, final Object value) { + if (supportUnknownEnumValue) { + invokeOrDie(setRepeatedValueMethod, builder, index, + ((EnumValueDescriptor) value).getNumber()); + return; + } + super.setRepeated(builder, index, invokeOrDie(valueOfMethod, null, + value)); + } + @Override + public void addRepeated(final Builder builder, final Object value) { + if (supportUnknownEnumValue) { + invokeOrDie(addRepeatedValueMethod, builder, + ((EnumValueDescriptor) value).getNumber()); + return; + } + super.addRepeated(builder, invokeOrDie(valueOfMethod, null, value)); + } + } + + // --------------------------------------------------------------- + + /** + * Field accessor for string fields. + * + *

This class makes getFooBytes() and setFooBytes() available for + * reflection API so that reflection based serialize/parse functions can + * access the raw bytes of the field to preserve non-UTF8 bytes in the + * string. + * + *

This ensures the serialize/parse round-trip safety, which is important + * for servers which forward messages. + */ + private static final class SingularStringFieldAccessor + extends SingularFieldAccessor { + SingularStringFieldAccessor( + final FieldDescriptor descriptor, final String camelCaseName, + final Class messageClass, + final Class builderClass, + final String containingOneofCamelCaseName) { + super(descriptor, camelCaseName, messageClass, builderClass, + containingOneofCamelCaseName); + getBytesMethod = getMethodOrDie(messageClass, + "get" + camelCaseName + "Bytes"); + getBytesMethodBuilder = getMethodOrDie(builderClass, + "get" + camelCaseName + "Bytes"); + setBytesMethodBuilder = getMethodOrDie(builderClass, + "set" + camelCaseName + "Bytes", ByteString.class); + } + + private final Method getBytesMethod; + private final Method getBytesMethodBuilder; + private final Method setBytesMethodBuilder; + + @Override + public Object getRaw(final GeneratedMessage message) { + return invokeOrDie(getBytesMethod, message); + } + + @Override + public Object getRaw(GeneratedMessage.Builder builder) { + return invokeOrDie(getBytesMethodBuilder, builder); + } + + @Override + public void set(GeneratedMessage.Builder builder, Object value) { + if (value instanceof ByteString) { + invokeOrDie(setBytesMethodBuilder, builder, value); + } else { + super.set(builder, value); + } + } + } + + // --------------------------------------------------------------- + + private static final class SingularMessageFieldAccessor + extends SingularFieldAccessor { + SingularMessageFieldAccessor( + final FieldDescriptor descriptor, final String camelCaseName, + final Class messageClass, + final Class builderClass, + final String containingOneofCamelCaseName) { + super(descriptor, camelCaseName, messageClass, builderClass, + containingOneofCamelCaseName); + + newBuilderMethod = getMethodOrDie(type, "newBuilder"); + getBuilderMethodBuilder = + getMethodOrDie(builderClass, "get" + camelCaseName + "Builder"); + } + + private final Method newBuilderMethod; + private final Method getBuilderMethodBuilder; + + private Object coerceType(final Object value) { + if (type.isInstance(value)) { + return value; + } else { + // The value is not the exact right message type. However, if it + // is an alternative implementation of the same type -- e.g. a + // DynamicMessage -- we should accept it. In this case we can make + // a copy of the message. + return ((Message.Builder) invokeOrDie(newBuilderMethod, null)) + .mergeFrom((Message) value).buildPartial(); + } + } + + @Override + public void set(final Builder builder, final Object value) { + super.set(builder, coerceType(value)); + } + @Override + public Message.Builder newBuilder() { + return (Message.Builder) invokeOrDie(newBuilderMethod, null); + } + @Override + public Message.Builder getBuilder(GeneratedMessage.Builder builder) { + return (Message.Builder) invokeOrDie(getBuilderMethodBuilder, builder); + } + } + + private static final class RepeatedMessageFieldAccessor + extends RepeatedFieldAccessor { + RepeatedMessageFieldAccessor( + final FieldDescriptor descriptor, final String camelCaseName, + final Class messageClass, + final Class builderClass) { + super(descriptor, camelCaseName, messageClass, builderClass); + + newBuilderMethod = getMethodOrDie(type, "newBuilder"); + getBuilderMethodBuilder = getMethodOrDie(builderClass, + "get" + camelCaseName + "Builder", Integer.TYPE); + } + + private final Method newBuilderMethod; + private final Method getBuilderMethodBuilder; + + private Object coerceType(final Object value) { + if (type.isInstance(value)) { + return value; + } else { + // The value is not the exact right message type. However, if it + // is an alternative implementation of the same type -- e.g. a + // DynamicMessage -- we should accept it. In this case we can make + // a copy of the message. + return ((Message.Builder) invokeOrDie(newBuilderMethod, null)) + .mergeFrom((Message) value).build(); + } + } + + @Override + public void setRepeated(final Builder builder, + final int index, final Object value) { + super.setRepeated(builder, index, coerceType(value)); + } + @Override + public void addRepeated(final Builder builder, final Object value) { + super.addRepeated(builder, coerceType(value)); + } + @Override + public Message.Builder newBuilder() { + return (Message.Builder) invokeOrDie(newBuilderMethod, null); + } + @Override + public Message.Builder getRepeatedBuilder( + final GeneratedMessage.Builder builder, final int index) { + return (Message.Builder) invokeOrDie( + getBuilderMethodBuilder, builder, index); + } + } + } + + /** + * Replaces this object in the output stream with a serialized form. + * Part of Java's serialization magic. Generated sub-classes must override + * this method by calling {@code return super.writeReplace();} + * @return a SerializedForm of this message + */ + protected Object writeReplace() throws ObjectStreamException { + return new GeneratedMessageLite.SerializedForm(this); + } + + /** + * Checks that the {@link Extension} is non-Lite and returns it as a + * {@link GeneratedExtension}. + */ + private static , T> + Extension checkNotLite( + ExtensionLite extension) { + if (extension.isLite()) { + throw new IllegalArgumentException("Expected non-lite extension."); + } + + return (Extension) extension; + } + + protected static int computeStringSize(final int fieldNumber, final Object value) { + if (value instanceof String) { + return CodedOutputStream.computeStringSize(fieldNumber, (String) value); + } else { + return CodedOutputStream.computeBytesSize(fieldNumber, (ByteString) value); + } + } + + protected static int computeStringSizeNoTag(final Object value) { + if (value instanceof String) { + return CodedOutputStream.computeStringSizeNoTag((String) value); + } else { + return CodedOutputStream.computeBytesSizeNoTag((ByteString) value); + } + } + + protected static void writeString( + CodedOutputStream output, final int fieldNumber, final Object value) throws IOException { + if (value instanceof String) { + output.writeString(fieldNumber, (String) value); + } else { + output.writeBytes(fieldNumber, (ByteString) value); + } + } + + protected static void writeStringNoTag( + CodedOutputStream output, final Object value) throws IOException { + if (value instanceof String) { + output.writeStringNoTag((String) value); + } else { + output.writeBytesNoTag((ByteString) value); + } + } +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/GeneratedMessageInfoFactory.java b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/GeneratedMessageInfoFactory.java new file mode 100644 index 0000000..3e3efb9 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/GeneratedMessageInfoFactory.java @@ -0,0 +1,65 @@ +// 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. + +package com.google.protobuf; + +/** A factory for message info that is generated into the message itself. */ +@ExperimentalApi +class GeneratedMessageInfoFactory implements MessageInfoFactory { + + private static final GeneratedMessageInfoFactory instance = new GeneratedMessageInfoFactory(); + + // Disallow construction - it's a singleton. + private GeneratedMessageInfoFactory() {} + + public static GeneratedMessageInfoFactory getInstance() { + return instance; + } + + @Override + public boolean isSupported(Class messageType) { + return GeneratedMessageLite.class.isAssignableFrom(messageType); + } + + @Override + public MessageInfo messageInfoFor(Class messageType) { + if (!GeneratedMessageLite.class.isAssignableFrom(messageType)) { + throw new IllegalArgumentException("Unsupported message type: " + messageType.getName()); + } + + try { + return (MessageInfo) GeneratedMessageLite.getDefaultInstance( + messageType.asSubclass(GeneratedMessageLite.class)) + .buildMessageInfo(); + } catch (Exception e) { + throw new RuntimeException("Unable to get message info for " + messageType.getName(), e); + } + } +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java new file mode 100644 index 0000000..46427b3 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java @@ -0,0 +1,3240 @@ +// 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. + +package com.google.protobuf; + +import static com.google.protobuf.Internal.checkNotNull; + +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.EnumDescriptor; +import com.google.protobuf.Descriptors.EnumValueDescriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Descriptors.FileDescriptor; +import com.google.protobuf.Descriptors.OneofDescriptor; +import com.google.protobuf.Internal.BooleanList; +import com.google.protobuf.Internal.DoubleList; +import com.google.protobuf.Internal.FloatList; +import com.google.protobuf.Internal.IntList; +import com.google.protobuf.Internal.LongList; +// In opensource protobuf, we have versioned this GeneratedMessageV3 class to GeneratedMessageV3 and +// in the future may have GeneratedMessageV4 etc. This allows us to change some aspects of this +// class without breaking binary compatibility with old generated code that still subclasses +// the old GeneratedMessageV3 class. To allow these different GeneratedMessageV? classes to +// interoperate (e.g., a GeneratedMessageV3 object has a message extension field whose class +// type is GeneratedMessageV4), these classes still share a common parent class AbstractMessage +// and are using the same GeneratedMessage.GeneratedExtension class for extension definitions. +// Since this class becomes GeneratedMessageV? in opensource, we have to add an import here +// to be able to use GeneratedMessage.GeneratedExtension. The GeneratedExtension definition in +// this file is also excluded from opensource to avoid conflict. +import com.google.protobuf.GeneratedMessage.GeneratedExtension; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectStreamException; +import java.io.Serializable; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +/** + * All generated protocol message classes extend this class. This class + * implements most of the Message and Builder interfaces using Java reflection. + * Users can ignore this class and pretend that generated messages implement + * the Message interface directly. + * + * @author kenton@google.com Kenton Varda + */ +public abstract class GeneratedMessageV3 extends AbstractMessage + implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * For testing. Allows a test to disable the optimization that avoids using field builders for + * nested messages until they are requested. By disabling this optimization, existing tests can be + * reused to test the field builders. + */ + protected static boolean alwaysUseFieldBuilders = false; + + /** For use by generated code only. */ + protected UnknownFieldSet unknownFields; + + protected GeneratedMessageV3() { + unknownFields = UnknownFieldSet.getDefaultInstance(); + } + + protected GeneratedMessageV3(Builder builder) { + unknownFields = builder.getUnknownFields(); + } + + @Override + public Parser getParserForType() { + throw new UnsupportedOperationException( + "This is supposed to be overridden by subclasses."); + } + + /** + * @see #setAlwaysUseFieldBuildersForTesting(boolean) + */ + static void enableAlwaysUseFieldBuildersForTesting() { + setAlwaysUseFieldBuildersForTesting(true); + } + + /** + * For testing. Allows a test to disable/re-enable the optimization that avoids + * using field builders for nested messages until they are requested. By disabling + * this optimization, existing tests can be reused to test the field builders. + * See {@link RepeatedFieldBuilder} and {@link SingleFieldBuilder}. + */ + static void setAlwaysUseFieldBuildersForTesting(boolean useBuilders) { + alwaysUseFieldBuilders = useBuilders; + } + + /** + * Get the FieldAccessorTable for this type. We can't have the message + * class pass this in to the constructor because of bootstrapping trouble + * with DescriptorProtos. + */ + protected abstract FieldAccessorTable internalGetFieldAccessorTable(); + + @Override + public Descriptor getDescriptorForType() { + return internalGetFieldAccessorTable().descriptor; + } + + protected void mergeFromAndMakeImmutableInternal( + CodedInputStream input, ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException { + Schema schema = + (Schema) Protobuf.getInstance().schemaFor(this); + try { + schema.mergeFrom(this, CodedInputStreamReader.forCodedInput(input), extensionRegistry); + } catch (InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (IOException e) { + throw new InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } + schema.makeImmutable(this); + } + + /** + * Internal helper to return a modifiable map containing all the fields. + * The returned Map is modifiable so that the caller can add additional + * extension fields to implement {@link #getAllFields()}. + * + * @param getBytesForString whether to generate ByteString for string fields + */ + private Map getAllFieldsMutable( + boolean getBytesForString) { + final TreeMap result = + new TreeMap(); + final Descriptor descriptor = internalGetFieldAccessorTable().descriptor; + final List fields = descriptor.getFields(); + + for (int i = 0; i < fields.size(); i++) { + FieldDescriptor field = fields.get(i); + final OneofDescriptor oneofDescriptor = field.getContainingOneof(); + + /* + * If the field is part of a Oneof, then at maximum one field in the Oneof is set + * and it is not repeated. There is no need to iterate through the others. + */ + if (oneofDescriptor != null) { + // Skip other fields in the Oneof we know are not set + i += oneofDescriptor.getFieldCount() - 1; + if (!hasOneof(oneofDescriptor)) { + // If no field is set in the Oneof, skip all the fields in the Oneof + continue; + } + // Get the pointer to the only field which is set in the Oneof + field = getOneofFieldDescriptor(oneofDescriptor); + } else { + // If we are not in a Oneof, we need to check if the field is set and if it is repeated + if (field.isRepeated()) { + final List value = (List) getField(field); + if (!value.isEmpty()) { + result.put(field, value); + } + continue; + } + if (!hasField(field)) { + continue; + } + } + // Add the field to the map + if (getBytesForString && field.getJavaType() == FieldDescriptor.JavaType.STRING) { + result.put(field, getFieldRaw(field)); + } else { + result.put(field, getField(field)); + } + } + return result; + } + + @Override + public boolean isInitialized() { + for (final FieldDescriptor field : getDescriptorForType().getFields()) { + // Check that all required fields are present. + if (field.isRequired()) { + if (!hasField(field)) { + return false; + } + } + // Check that embedded messages are initialized. + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + if (field.isRepeated()) { + @SuppressWarnings("unchecked") final + List messageList = (List) getField(field); + for (final Message element : messageList) { + if (!element.isInitialized()) { + return false; + } + } + } else { + if (hasField(field) && !((Message) getField(field)).isInitialized()) { + return false; + } + } + } + } + + return true; + } + + @Override + public Map getAllFields() { + return Collections.unmodifiableMap( + getAllFieldsMutable(/* getBytesForString = */ false)); + } + + /** + * Returns a collection of all the fields in this message which are set + * and their corresponding values. A singular ("required" or "optional") + * field is set iff hasField() returns true for that field. A "repeated" + * field is set iff getRepeatedFieldCount() is greater than zero. The + * values are exactly what would be returned by calling + * {@link #getFieldRaw(Descriptors.FieldDescriptor)} for each field. The map + * is guaranteed to be a sorted map, so iterating over it will return fields + * in order by field number. + */ + Map getAllFieldsRaw() { + return Collections.unmodifiableMap( + getAllFieldsMutable(/* getBytesForString = */ true)); + } + + @Override + public boolean hasOneof(final OneofDescriptor oneof) { + return internalGetFieldAccessorTable().getOneof(oneof).has(this); + } + + @Override + public FieldDescriptor getOneofFieldDescriptor(final OneofDescriptor oneof) { + return internalGetFieldAccessorTable().getOneof(oneof).get(this); + } + + @Override + public boolean hasField(final FieldDescriptor field) { + return internalGetFieldAccessorTable().getField(field).has(this); + } + + @Override + public Object getField(final FieldDescriptor field) { + return internalGetFieldAccessorTable().getField(field).get(this); + } + + /** + * Obtains the value of the given field, or the default value if it is + * not set. For primitive fields, the boxed primitive value is returned. + * For enum fields, the EnumValueDescriptor for the value is returned. For + * embedded message fields, the sub-message is returned. For repeated + * fields, a java.util.List is returned. For present string fields, a + * ByteString is returned representing the bytes that the field contains. + */ + Object getFieldRaw(final FieldDescriptor field) { + return internalGetFieldAccessorTable().getField(field).getRaw(this); + } + + @Override + public int getRepeatedFieldCount(final FieldDescriptor field) { + return internalGetFieldAccessorTable().getField(field) + .getRepeatedCount(this); + } + + @Override + public Object getRepeatedField(final FieldDescriptor field, final int index) { + return internalGetFieldAccessorTable().getField(field) + .getRepeated(this, index); + } + + @Override + public UnknownFieldSet getUnknownFields() { + throw new UnsupportedOperationException( + "This is supposed to be overridden by subclasses."); + } + + /** + * Called by subclasses to parse an unknown field. + * + * @return {@code true} unless the tag is an end-group tag. + */ + protected boolean parseUnknownField( + CodedInputStream input, + UnknownFieldSet.Builder unknownFields, + ExtensionRegistryLite extensionRegistry, + int tag) + throws IOException { + if (input.shouldDiscardUnknownFields()) { + return input.skipField(tag); + } + return unknownFields.mergeFieldFrom(tag, input); + } + + /** + * Delegates to parseUnknownField. This method is obsolete, but we must retain it for + * compatibility with older generated code. + */ + protected boolean parseUnknownFieldProto3( + CodedInputStream input, + UnknownFieldSet.Builder unknownFields, + ExtensionRegistryLite extensionRegistry, + int tag) + throws IOException { + return parseUnknownField(input, unknownFields, extensionRegistry, tag); + } + + protected static M parseWithIOException(Parser parser, InputStream input) + throws IOException { + try { + return parser.parseFrom(input); + } catch (InvalidProtocolBufferException e) { + throw e.unwrapIOException(); + } + } + + protected static M parseWithIOException(Parser parser, InputStream input, + ExtensionRegistryLite extensions) throws IOException { + try { + return parser.parseFrom(input, extensions); + } catch (InvalidProtocolBufferException e) { + throw e.unwrapIOException(); + } + } + + protected static M parseWithIOException(Parser parser, + CodedInputStream input) throws IOException { + try { + return parser.parseFrom(input); + } catch (InvalidProtocolBufferException e) { + throw e.unwrapIOException(); + } + } + + protected static M parseWithIOException(Parser parser, + CodedInputStream input, ExtensionRegistryLite extensions) throws IOException { + try { + return parser.parseFrom(input, extensions); + } catch (InvalidProtocolBufferException e) { + throw e.unwrapIOException(); + } + } + + protected static M parseDelimitedWithIOException(Parser parser, + InputStream input) throws IOException { + try { + return parser.parseDelimitedFrom(input); + } catch (InvalidProtocolBufferException e) { + throw e.unwrapIOException(); + } + } + + protected static M parseDelimitedWithIOException(Parser parser, + InputStream input, ExtensionRegistryLite extensions) throws IOException { + try { + return parser.parseDelimitedFrom(input, extensions); + } catch (InvalidProtocolBufferException e) { + throw e.unwrapIOException(); + } + } + + protected static boolean canUseUnsafe() { + return UnsafeUtil.hasUnsafeArrayOperations() && UnsafeUtil.hasUnsafeByteBufferOperations(); + } + + protected static IntList emptyIntList() { + return IntArrayList.emptyList(); + } + + protected static IntList newIntList() { + return new IntArrayList(); + } + + protected static IntList mutableCopy(IntList list) { + int size = list.size(); + return list.mutableCopyWithCapacity( + size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2); + } + + protected static LongList emptyLongList() { + return LongArrayList.emptyList(); + } + + protected static LongList newLongList() { + return new LongArrayList(); + } + + protected static LongList mutableCopy(LongList list) { + int size = list.size(); + return list.mutableCopyWithCapacity( + size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2); + } + + protected static FloatList emptyFloatList() { + return FloatArrayList.emptyList(); + } + + protected static FloatList newFloatList() { + return new FloatArrayList(); + } + + protected static FloatList mutableCopy(FloatList list) { + int size = list.size(); + return list.mutableCopyWithCapacity( + size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2); + } + + protected static DoubleList emptyDoubleList() { + return DoubleArrayList.emptyList(); + } + + protected static DoubleList newDoubleList() { + return new DoubleArrayList(); + } + + protected static DoubleList mutableCopy(DoubleList list) { + int size = list.size(); + return list.mutableCopyWithCapacity( + size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2); + } + + protected static BooleanList emptyBooleanList() { + return BooleanArrayList.emptyList(); + } + + protected static BooleanList newBooleanList() { + return new BooleanArrayList(); + } + + protected static BooleanList mutableCopy(BooleanList list) { + int size = list.size(); + return list.mutableCopyWithCapacity( + size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2); + } + + + @Override + public void writeTo(final CodedOutputStream output) throws IOException { + MessageReflection.writeMessageTo(this, getAllFieldsRaw(), output, false); + } + + @Override + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) { + return size; + } + + memoizedSize = MessageReflection.getSerializedSize( + this, getAllFieldsRaw()); + return memoizedSize; + } + + + + /** + * This class is used to make a generated protected method inaccessible from user's code (e.g., + * the {@link #newInstance} method below). When this class is used as a parameter's type in a + * generated protected method, the method is visible to user's code in the same package, but + * since the constructor of this class is private to protobuf runtime, user's code can't obtain + * an instance of this class and as such can't actually make a method call on the protected + * method. + */ + protected static final class UnusedPrivateParameter { + static final UnusedPrivateParameter INSTANCE = new UnusedPrivateParameter(); + + private UnusedPrivateParameter() { + } + } + + /** + * Creates a new instance of this message type. Overridden in the generated code. + */ + @SuppressWarnings({"unused"}) + protected Object newInstance(UnusedPrivateParameter unused) { + throw new UnsupportedOperationException("This method must be overridden by the subclass."); + } + + /** + * Used by parsing constructors in generated classes. + */ + protected void makeExtensionsImmutable() { + // Noop for messages without extensions. + } + + /** + * TODO(xiaofeng): remove this after b/29368482 is fixed. We need to move this + * interface to AbstractMessage in order to versioning GeneratedMessageV3 but + * this move breaks binary compatibility for AppEngine. After AppEngine is + * fixed we can exclude this from google3. + */ + protected interface BuilderParent extends AbstractMessage.BuilderParent {} + + /** + * TODO(xiaofeng): remove this together with GeneratedMessageV3.BuilderParent. + */ + protected abstract Message.Builder newBuilderForType(BuilderParent parent); + + @Override + protected Message.Builder newBuilderForType(final AbstractMessage.BuilderParent parent) { + return newBuilderForType(new BuilderParent() { + @Override + public void markDirty() { + parent.markDirty(); + } + }); + } + + + @SuppressWarnings("unchecked") + public abstract static class Builder > + extends AbstractMessage.Builder { + + private BuilderParent builderParent; + + private BuilderParentImpl meAsParent; + + // Indicates that we've built a message and so we are now obligated + // to dispatch dirty invalidations. See GeneratedMessageV3.BuilderListener. + private boolean isClean; + + private UnknownFieldSet unknownFields = + UnknownFieldSet.getDefaultInstance(); + + protected Builder() { + this(null); + } + + protected Builder(BuilderParent builderParent) { + this.builderParent = builderParent; + } + + @Override + void dispose() { + builderParent = null; + } + + /** + * Called by the subclass when a message is built. + */ + protected void onBuilt() { + if (builderParent != null) { + markClean(); + } + } + + /** + * Called by the subclass or a builder to notify us that a message was + * built and may be cached and therefore invalidations are needed. + */ + @Override + protected void markClean() { + this.isClean = true; + } + + /** + * Gets whether invalidations are needed + * + * @return whether invalidations are needed + */ + protected boolean isClean() { + return isClean; + } + + @Override + public BuilderType clone() { + BuilderType builder = + (BuilderType) getDefaultInstanceForType().newBuilderForType(); + builder.mergeFrom(buildPartial()); + return builder; + } + + /** + * Called by the initialization and clear code paths to allow subclasses to + * reset any of their builtin fields back to the initial values. + */ + @Override + public BuilderType clear() { + unknownFields = UnknownFieldSet.getDefaultInstance(); + onChanged(); + return (BuilderType) this; + } + + /** + * Get the FieldAccessorTable for this type. We can't have the message + * class pass this in to the constructor because of bootstrapping trouble + * with DescriptorProtos. + */ + protected abstract FieldAccessorTable internalGetFieldAccessorTable(); + + @Override + public Descriptor getDescriptorForType() { + return internalGetFieldAccessorTable().descriptor; + } + + @Override + public Map getAllFields() { + return Collections.unmodifiableMap(getAllFieldsMutable()); + } + + /** Internal helper which returns a mutable map. */ + private Map getAllFieldsMutable() { + final TreeMap result = + new TreeMap(); + final Descriptor descriptor = internalGetFieldAccessorTable().descriptor; + final List fields = descriptor.getFields(); + + for (int i = 0; i < fields.size(); i++) { + FieldDescriptor field = fields.get(i); + final OneofDescriptor oneofDescriptor = field.getContainingOneof(); + + /* + * If the field is part of a Oneof, then at maximum one field in the Oneof is set + * and it is not repeated. There is no need to iterate through the others. + */ + if (oneofDescriptor != null) { + // Skip other fields in the Oneof we know are not set + i += oneofDescriptor.getFieldCount() - 1; + if (!hasOneof(oneofDescriptor)) { + // If no field is set in the Oneof, skip all the fields in the Oneof + continue; + } + // Get the pointer to the only field which is set in the Oneof + field = getOneofFieldDescriptor(oneofDescriptor); + } else { + // If we are not in a Oneof, we need to check if the field is set and if it is repeated + if (field.isRepeated()) { + final List value = (List) getField(field); + if (!value.isEmpty()) { + result.put(field, value); + } + continue; + } + if (!hasField(field)) { + continue; + } + } + // Add the field to the map + result.put(field, getField(field)); + } + return result; + } + + @Override + public Message.Builder newBuilderForField(final FieldDescriptor field) { + return internalGetFieldAccessorTable().getField(field).newBuilder(); + } + + @Override + public Message.Builder getFieldBuilder(final FieldDescriptor field) { + return internalGetFieldAccessorTable().getField(field).getBuilder(this); + } + + @Override + public Message.Builder getRepeatedFieldBuilder(final FieldDescriptor field, int index) { + return internalGetFieldAccessorTable().getField(field).getRepeatedBuilder( + this, index); + } + + @Override + public boolean hasOneof(final OneofDescriptor oneof) { + return internalGetFieldAccessorTable().getOneof(oneof).has(this); + } + + @Override + public FieldDescriptor getOneofFieldDescriptor(final OneofDescriptor oneof) { + return internalGetFieldAccessorTable().getOneof(oneof).get(this); + } + + @Override + public boolean hasField(final FieldDescriptor field) { + return internalGetFieldAccessorTable().getField(field).has(this); + } + + @Override + public Object getField(final FieldDescriptor field) { + Object object = internalGetFieldAccessorTable().getField(field).get(this); + if (field.isRepeated()) { + // The underlying list object is still modifiable at this point. + // Make sure not to expose the modifiable list to the caller. + return Collections.unmodifiableList((List) object); + } else { + return object; + } + } + + @Override + public BuilderType setField(final FieldDescriptor field, final Object value) { + internalGetFieldAccessorTable().getField(field).set(this, value); + return (BuilderType) this; + } + + @Override + public BuilderType clearField(final FieldDescriptor field) { + internalGetFieldAccessorTable().getField(field).clear(this); + return (BuilderType) this; + } + + @Override + public BuilderType clearOneof(final OneofDescriptor oneof) { + internalGetFieldAccessorTable().getOneof(oneof).clear(this); + return (BuilderType) this; + } + + @Override + public int getRepeatedFieldCount(final FieldDescriptor field) { + return internalGetFieldAccessorTable().getField(field) + .getRepeatedCount(this); + } + + @Override + public Object getRepeatedField(final FieldDescriptor field, final int index) { + return internalGetFieldAccessorTable().getField(field) + .getRepeated(this, index); + } + + @Override + public BuilderType setRepeatedField( + final FieldDescriptor field, final int index, final Object value) { + internalGetFieldAccessorTable().getField(field) + .setRepeated(this, index, value); + return (BuilderType) this; + } + + @Override + public BuilderType addRepeatedField(final FieldDescriptor field, final Object value) { + internalGetFieldAccessorTable().getField(field).addRepeated(this, value); + return (BuilderType) this; + } + + private BuilderType setUnknownFieldsInternal(final UnknownFieldSet unknownFields) { + this.unknownFields = unknownFields; + onChanged(); + return (BuilderType) this; + } + + @Override + public BuilderType setUnknownFields(final UnknownFieldSet unknownFields) { + return setUnknownFieldsInternal(unknownFields); + } + + /** + * This method is obsolete, but we must retain it for compatibility with + * older generated code. + */ + protected BuilderType setUnknownFieldsProto3(final UnknownFieldSet unknownFields) { + return setUnknownFieldsInternal(unknownFields); + } + + @Override + public BuilderType mergeUnknownFields( + final UnknownFieldSet unknownFields) { + return setUnknownFields( + UnknownFieldSet.newBuilder(this.unknownFields) + .mergeFrom(unknownFields) + .build()); + } + + + @Override + public boolean isInitialized() { + for (final FieldDescriptor field : getDescriptorForType().getFields()) { + // Check that all required fields are present. + if (field.isRequired()) { + if (!hasField(field)) { + return false; + } + } + // Check that embedded messages are initialized. + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + if (field.isRepeated()) { + @SuppressWarnings("unchecked") final + List messageList = (List) getField(field); + for (final Message element : messageList) { + if (!element.isInitialized()) { + return false; + } + } + } else { + if (hasField(field) && + !((Message) getField(field)).isInitialized()) { + return false; + } + } + } + } + return true; + } + + @Override + public final UnknownFieldSet getUnknownFields() { + return unknownFields; + } + + /** + * Implementation of {@link BuilderParent} for giving to our children. This + * small inner class makes it so we don't publicly expose the BuilderParent + * methods. + */ + private class BuilderParentImpl implements BuilderParent { + + @Override + public void markDirty() { + onChanged(); + } + } + + /** + * Gets the {@link BuilderParent} for giving to our children. + * @return The builder parent for our children. + */ + protected BuilderParent getParentForChildren() { + if (meAsParent == null) { + meAsParent = new BuilderParentImpl(); + } + return meAsParent; + } + + /** + * Called when a the builder or one of its nested children has changed + * and any parent should be notified of its invalidation. + */ + protected final void onChanged() { + if (isClean && builderParent != null) { + builderParent.markDirty(); + + // Don't keep dispatching invalidations until build is called again. + isClean = false; + } + } + + /** + * Gets the map field with the given field number. This method should be + * overridden in the generated message class if the message contains map + * fields. + * + * Unlike other field types, reflection support for map fields can't be + * implemented based on generated public API because we need to access a + * map field as a list in reflection API but the generated API only allows + * us to access it as a map. This method returns the underlying map field + * directly and thus enables us to access the map field as a list. + */ + @SuppressWarnings({"unused", "rawtypes"}) + protected MapField internalGetMapField(int fieldNumber) { + // Note that we can't use descriptor names here because this method will + // be called when descriptor is being initialized. + throw new RuntimeException( + "No map fields found in " + getClass().getName()); + } + + /** Like {@link #internalGetMapField} but return a mutable version. */ + @SuppressWarnings({"unused", "rawtypes"}) + protected MapField internalGetMutableMapField(int fieldNumber) { + // Note that we can't use descriptor names here because this method will + // be called when descriptor is being initialized. + throw new RuntimeException( + "No map fields found in " + getClass().getName()); + } + } + + // ================================================================= + // Extensions-related stuff + + public interface ExtendableMessageOrBuilder< + MessageType extends ExtendableMessage> extends MessageOrBuilder { + // Re-define for return type covariance. + @Override + Message getDefaultInstanceForType(); + + /** Check if a singular extension is present. */ + boolean hasExtension( + ExtensionLite extension); + + /** Get the number of elements in a repeated extension. */ + int getExtensionCount( + ExtensionLite> extension); + + /** Get the value of an extension. */ + Type getExtension( + ExtensionLite extension); + + /** Get one element of a repeated extension. */ + Type getExtension( + ExtensionLite> extension, + int index); + + /** Check if a singular extension is present. */ + boolean hasExtension( + Extension extension); + /** Check if a singular extension is present. */ + boolean hasExtension( + GeneratedExtension extension); + /** Get the number of elements in a repeated extension. */ + int getExtensionCount( + Extension> extension); + /** Get the number of elements in a repeated extension. */ + int getExtensionCount( + GeneratedExtension> extension); + /** Get the value of an extension. */ + Type getExtension( + Extension extension); + /** Get the value of an extension. */ + Type getExtension( + GeneratedExtension extension); + /** Get one element of a repeated extension. */ + Type getExtension( + Extension> extension, + int index); + /** Get one element of a repeated extension. */ + Type getExtension( + GeneratedExtension> extension, + int index); + } + + /** + * Generated message classes for message types that contain extension ranges + * subclass this. + * + *

This class implements type-safe accessors for extensions. They + * implement all the same operations that you can do with normal fields -- + * e.g. "has", "get", and "getCount" -- but for extensions. The extensions + * are identified using instances of the class {@link GeneratedExtension}; + * the protocol compiler generates a static instance of this class for every + * extension in its input. Through the magic of generics, all is made + * type-safe. + * + *

For example, imagine you have the {@code .proto} file: + * + *

+   * option java_class = "MyProto";
+   *
+   * message Foo {
+   *   extensions 1000 to max;
+   * }
+   *
+   * extend Foo {
+   *   optional int32 bar;
+   * }
+   * 
+ * + *

Then you might write code like: + * + *

+   * MyProto.Foo foo = getFoo();
+   * int i = foo.getExtension(MyProto.bar);
+   * 
+ * + *

See also {@link ExtendableBuilder}. + */ + public abstract static class ExtendableMessage< + MessageType extends ExtendableMessage> + extends GeneratedMessageV3 + implements ExtendableMessageOrBuilder { + + private static final long serialVersionUID = 1L; + + private final FieldSet extensions; + + protected ExtendableMessage() { + this.extensions = FieldSet.newFieldSet(); + } + + protected ExtendableMessage( + ExtendableBuilder builder) { + super(builder); + this.extensions = builder.buildExtensions(); + } + + private void verifyExtensionContainingType( + final Extension extension) { + if (extension.getDescriptor().getContainingType() != + getDescriptorForType()) { + // This can only happen if someone uses unchecked operations. + throw new IllegalArgumentException( + "Extension is for type \"" + + extension.getDescriptor().getContainingType().getFullName() + + "\" which does not match message type \"" + + getDescriptorForType().getFullName() + "\"."); + } + } + + /** Check if a singular extension is present. */ + @Override + @SuppressWarnings("unchecked") + public final boolean hasExtension(final ExtensionLite extensionLite) { + Extension extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + return extensions.hasField(extension.getDescriptor()); + } + + /** Get the number of elements in a repeated extension. */ + @Override + @SuppressWarnings("unchecked") + public final int getExtensionCount( + final ExtensionLite> extensionLite) { + Extension> extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + final FieldDescriptor descriptor = extension.getDescriptor(); + return extensions.getRepeatedFieldCount(descriptor); + } + + /** Get the value of an extension. */ + @Override + @SuppressWarnings("unchecked") + public final Type getExtension(final ExtensionLite extensionLite) { + Extension extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + FieldDescriptor descriptor = extension.getDescriptor(); + final Object value = extensions.getField(descriptor); + if (value == null) { + if (descriptor.isRepeated()) { + return (Type) Collections.emptyList(); + } else if (descriptor.getJavaType() == + FieldDescriptor.JavaType.MESSAGE) { + return (Type) extension.getMessageDefaultInstance(); + } else { + return (Type) extension.fromReflectionType( + descriptor.getDefaultValue()); + } + } else { + return (Type) extension.fromReflectionType(value); + } + } + + /** Get one element of a repeated extension. */ + @Override + @SuppressWarnings("unchecked") + public final Type getExtension( + final ExtensionLite> extensionLite, final int index) { + Extension> extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + FieldDescriptor descriptor = extension.getDescriptor(); + return (Type) extension.singularFromReflectionType( + extensions.getRepeatedField(descriptor, index)); + } + + /** Check if a singular extension is present. */ + @Override + public final boolean hasExtension(final Extension extension) { + return hasExtension((ExtensionLite) extension); + } + /** Check if a singular extension is present. */ + @Override + public final boolean hasExtension( + final GeneratedExtension extension) { + return hasExtension((ExtensionLite) extension); + } + /** Get the number of elements in a repeated extension. */ + @Override + public final int getExtensionCount( + final Extension> extension) { + return getExtensionCount((ExtensionLite>) extension); + } + /** Get the number of elements in a repeated extension. */ + @Override + public final int getExtensionCount( + final GeneratedExtension> extension) { + return getExtensionCount((ExtensionLite>) extension); + } + /** Get the value of an extension. */ + @Override + public final Type getExtension(final Extension extension) { + return getExtension((ExtensionLite) extension); + } + /** Get the value of an extension. */ + @Override + public final Type getExtension( + final GeneratedExtension extension) { + return getExtension((ExtensionLite) extension); + } + /** Get one element of a repeated extension. */ + @Override + public final Type getExtension( + final Extension> extension, final int index) { + return getExtension((ExtensionLite>) extension, index); + } + /** Get one element of a repeated extension. */ + @Override + public final Type getExtension( + final GeneratedExtension> extension, final int index) { + return getExtension((ExtensionLite>) extension, index); + } + + /** Called by subclasses to check if all extensions are initialized. */ + protected boolean extensionsAreInitialized() { + return extensions.isInitialized(); + } + + @Override + public boolean isInitialized() { + return super.isInitialized() && extensionsAreInitialized(); + } + + @Override + protected boolean parseUnknownField( + CodedInputStream input, + UnknownFieldSet.Builder unknownFields, + ExtensionRegistryLite extensionRegistry, + int tag) throws IOException { + return MessageReflection.mergeFieldFrom( + input, input.shouldDiscardUnknownFields() ? null : unknownFields, extensionRegistry, + getDescriptorForType(), new MessageReflection.ExtensionAdapter(extensions), tag); + } + + /** + * Delegates to parseUnknownField. This method is obsolete, but we must retain it for + * compatibility with older generated code. + */ + @Override + protected boolean parseUnknownFieldProto3( + CodedInputStream input, + UnknownFieldSet.Builder unknownFields, + ExtensionRegistryLite extensionRegistry, + int tag) throws IOException { + return parseUnknownField(input, unknownFields, extensionRegistry, tag); + } + + + /** + * Used by parsing constructors in generated classes. + */ + @Override + protected void makeExtensionsImmutable() { + extensions.makeImmutable(); + } + + /** + * Used by subclasses to serialize extensions. Extension ranges may be + * interleaved with field numbers, but we must write them in canonical + * (sorted by field number) order. ExtensionWriter helps us write + * individual ranges of extensions at once. + */ + protected class ExtensionWriter { + // Imagine how much simpler this code would be if Java iterators had + // a way to get the next element without advancing the iterator. + + private final Iterator> iter = + extensions.iterator(); + private Map.Entry next; + private final boolean messageSetWireFormat; + + private ExtensionWriter(final boolean messageSetWireFormat) { + if (iter.hasNext()) { + next = iter.next(); + } + this.messageSetWireFormat = messageSetWireFormat; + } + + public void writeUntil(final int end, final CodedOutputStream output) + throws IOException { + while (next != null && next.getKey().getNumber() < end) { + FieldDescriptor descriptor = next.getKey(); + if (messageSetWireFormat && descriptor.getLiteJavaType() == + WireFormat.JavaType.MESSAGE && + !descriptor.isRepeated()) { + if (next instanceof LazyField.LazyEntry) { + output.writeRawMessageSetExtension(descriptor.getNumber(), + ((LazyField.LazyEntry) next).getField().toByteString()); + } else { + output.writeMessageSetExtension(descriptor.getNumber(), + (Message) next.getValue()); + } + } else { + // TODO(xiangl): Taken care of following code, it may cause + // problem when we use LazyField for normal fields/extensions. + // Due to the optional field can be duplicated at the end of + // serialized bytes, which will make the serialized size change + // after lazy field parsed. So when we use LazyField globally, + // we need to change the following write method to write cached + // bytes directly rather than write the parsed message. + FieldSet.writeField(descriptor, next.getValue(), output); + } + if (iter.hasNext()) { + next = iter.next(); + } else { + next = null; + } + } + } + } + + protected ExtensionWriter newExtensionWriter() { + return new ExtensionWriter(false); + } + protected ExtensionWriter newMessageSetExtensionWriter() { + return new ExtensionWriter(true); + } + + /** Called by subclasses to compute the size of extensions. */ + protected int extensionsSerializedSize() { + return extensions.getSerializedSize(); + } + protected int extensionsSerializedSizeAsMessageSet() { + return extensions.getMessageSetSerializedSize(); + } + + // --------------------------------------------------------------- + // Reflection + + protected Map getExtensionFields() { + return extensions.getAllFields(); + } + + @Override + public Map getAllFields() { + final Map result = + super.getAllFieldsMutable(/* getBytesForString = */ false); + result.putAll(getExtensionFields()); + return Collections.unmodifiableMap(result); + } + + @Override + public Map getAllFieldsRaw() { + final Map result = + super.getAllFieldsMutable(/* getBytesForString = */ false); + result.putAll(getExtensionFields()); + return Collections.unmodifiableMap(result); + } + + @Override + public boolean hasField(final FieldDescriptor field) { + if (field.isExtension()) { + verifyContainingType(field); + return extensions.hasField(field); + } else { + return super.hasField(field); + } + } + + @Override + public Object getField(final FieldDescriptor field) { + if (field.isExtension()) { + verifyContainingType(field); + final Object value = extensions.getField(field); + if (value == null) { + if (field.isRepeated()) { + return Collections.emptyList(); + } else if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + // Lacking an ExtensionRegistry, we have no way to determine the + // extension's real type, so we return a DynamicMessage. + return DynamicMessage.getDefaultInstance(field.getMessageType()); + } else { + return field.getDefaultValue(); + } + } else { + return value; + } + } else { + return super.getField(field); + } + } + + @Override + public int getRepeatedFieldCount(final FieldDescriptor field) { + if (field.isExtension()) { + verifyContainingType(field); + return extensions.getRepeatedFieldCount(field); + } else { + return super.getRepeatedFieldCount(field); + } + } + + @Override + public Object getRepeatedField(final FieldDescriptor field, + final int index) { + if (field.isExtension()) { + verifyContainingType(field); + return extensions.getRepeatedField(field, index); + } else { + return super.getRepeatedField(field, index); + } + } + + private void verifyContainingType(final FieldDescriptor field) { + if (field.getContainingType() != getDescriptorForType()) { + throw new IllegalArgumentException( + "FieldDescriptor does not match message type."); + } + } + } + + /** + * Generated message builders for message types that contain extension ranges + * subclass this. + * + *

This class implements type-safe accessors for extensions. They + * implement all the same operations that you can do with normal fields -- + * e.g. "get", "set", and "add" -- but for extensions. The extensions are + * identified using instances of the class {@link GeneratedExtension}; the + * protocol compiler generates a static instance of this class for every + * extension in its input. Through the magic of generics, all is made + * type-safe. + * + *

For example, imagine you have the {@code .proto} file: + * + *

+   * option java_class = "MyProto";
+   *
+   * message Foo {
+   *   extensions 1000 to max;
+   * }
+   *
+   * extend Foo {
+   *   optional int32 bar;
+   * }
+   * 
+ * + *

Then you might write code like: + * + *

+   * MyProto.Foo foo =
+   *   MyProto.Foo.newBuilder()
+   *     .setExtension(MyProto.bar, 123)
+   *     .build();
+   * 
+ * + *

See also {@link ExtendableMessage}. + */ + @SuppressWarnings("unchecked") + public abstract static class ExtendableBuilder< + MessageType extends ExtendableMessage, + BuilderType extends ExtendableBuilder> + extends Builder + implements ExtendableMessageOrBuilder { + + private FieldSet.Builder extensions; + + protected ExtendableBuilder() {} + + protected ExtendableBuilder( + BuilderParent parent) { + super(parent); + } + + // For immutable message conversion. + void internalSetExtensionSet(FieldSet extensions) { + this.extensions = FieldSet.Builder.fromFieldSet(extensions); + } + + @Override + public BuilderType clear() { + extensions = null; + return super.clear(); + } + + private void ensureExtensionsIsMutable() { + if (extensions == null) { + extensions = FieldSet.newBuilder(); + } + } + + private void verifyExtensionContainingType( + final Extension extension) { + if (extension.getDescriptor().getContainingType() != + getDescriptorForType()) { + // This can only happen if someone uses unchecked operations. + throw new IllegalArgumentException( + "Extension is for type \"" + + extension.getDescriptor().getContainingType().getFullName() + + "\" which does not match message type \"" + + getDescriptorForType().getFullName() + "\"."); + } + } + + /** Check if a singular extension is present. */ + @Override + public final boolean hasExtension(final ExtensionLite extensionLite) { + Extension extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + return extensions == null ? false : extensions.hasField(extension.getDescriptor()); + } + + /** Get the number of elements in a repeated extension. */ + @Override + public final int getExtensionCount( + final ExtensionLite> extensionLite) { + Extension> extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + final FieldDescriptor descriptor = extension.getDescriptor(); + return extensions == null ? 0 : extensions.getRepeatedFieldCount(descriptor); + } + + /** Get the value of an extension. */ + @Override + public final Type getExtension(final ExtensionLite extensionLite) { + Extension extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + FieldDescriptor descriptor = extension.getDescriptor(); + final Object value = extensions == null ? null : extensions.getField(descriptor); + if (value == null) { + if (descriptor.isRepeated()) { + return (Type) Collections.emptyList(); + } else if (descriptor.getJavaType() == + FieldDescriptor.JavaType.MESSAGE) { + return (Type) extension.getMessageDefaultInstance(); + } else { + return (Type) extension.fromReflectionType( + descriptor.getDefaultValue()); + } + } else { + return (Type) extension.fromReflectionType(value); + } + } + + /** Get one element of a repeated extension. */ + @Override + public final Type getExtension( + final ExtensionLite> extensionLite, final int index) { + Extension> extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + FieldDescriptor descriptor = extension.getDescriptor(); + if (extensions == null) { + throw new IndexOutOfBoundsException(); + } + return (Type) + extension.singularFromReflectionType(extensions.getRepeatedField(descriptor, index)); + } + + /** Set the value of an extension. */ + public final BuilderType setExtension( + final ExtensionLite extensionLite, + final Type value) { + Extension extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + ensureExtensionsIsMutable(); + final FieldDescriptor descriptor = extension.getDescriptor(); + extensions.setField(descriptor, extension.toReflectionType(value)); + onChanged(); + return (BuilderType) this; + } + + /** Set the value of one element of a repeated extension. */ + public final BuilderType setExtension( + final ExtensionLite> extensionLite, + final int index, final Type value) { + Extension> extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + ensureExtensionsIsMutable(); + final FieldDescriptor descriptor = extension.getDescriptor(); + extensions.setRepeatedField( + descriptor, index, + extension.singularToReflectionType(value)); + onChanged(); + return (BuilderType) this; + } + + /** Append a value to a repeated extension. */ + public final BuilderType addExtension( + final ExtensionLite> extensionLite, + final Type value) { + Extension> extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + ensureExtensionsIsMutable(); + final FieldDescriptor descriptor = extension.getDescriptor(); + extensions.addRepeatedField( + descriptor, extension.singularToReflectionType(value)); + onChanged(); + return (BuilderType) this; + } + + /** Clear an extension. */ + public final BuilderType clearExtension(final ExtensionLite extensionLite) { + Extension extension = checkNotLite(extensionLite); + + verifyExtensionContainingType(extension); + ensureExtensionsIsMutable(); + extensions.clearField(extension.getDescriptor()); + onChanged(); + return (BuilderType) this; + } + + /** Check if a singular extension is present. */ + @Override + public final boolean hasExtension(final Extension extension) { + return hasExtension((ExtensionLite) extension); + } + /** Check if a singular extension is present. */ + @Override + public final boolean hasExtension( + final GeneratedExtension extension) { + return hasExtension((ExtensionLite) extension); + } + /** Get the number of elements in a repeated extension. */ + @Override + public final int getExtensionCount( + final Extension> extension) { + return getExtensionCount((ExtensionLite>) extension); + } + /** Get the number of elements in a repeated extension. */ + @Override + public final int getExtensionCount( + final GeneratedExtension> extension) { + return getExtensionCount((ExtensionLite>) extension); + } + /** Get the value of an extension. */ + @Override + public final Type getExtension(final Extension extension) { + return getExtension((ExtensionLite) extension); + } + /** Get the value of an extension. */ + @Override + public final Type getExtension( + final GeneratedExtension extension) { + return getExtension((ExtensionLite) extension); + } + /** Get the value of an extension. */ + @Override + public final Type getExtension( + final Extension> extension, final int index) { + return getExtension((ExtensionLite>) extension, index); + } + /** Get the value of an extension. */ + @Override + public final Type getExtension( + final GeneratedExtension> extension, final int index) { + return getExtension((ExtensionLite>) extension, index); + } + /** Set the value of an extension. */ + public final BuilderType setExtension( + final Extension extension, final Type value) { + return setExtension((ExtensionLite) extension, value); + } + /** Set the value of an extension. */ + public BuilderType setExtension( + final GeneratedExtension extension, final Type value) { + return setExtension((ExtensionLite) extension, value); + } + /** Set the value of one element of a repeated extension. */ + public final BuilderType setExtension( + final Extension> extension, + final int index, final Type value) { + return setExtension((ExtensionLite>) extension, index, value); + } + /** Set the value of one element of a repeated extension. */ + public BuilderType setExtension( + final GeneratedExtension> extension, + final int index, final Type value) { + return setExtension((ExtensionLite>) extension, index, value); + } + /** Append a value to a repeated extension. */ + public final BuilderType addExtension( + final Extension> extension, final Type value) { + return addExtension((ExtensionLite>) extension, value); + } + /** Append a value to a repeated extension. */ + public BuilderType addExtension( + final GeneratedExtension> extension, final Type value) { + return addExtension((ExtensionLite>) extension, value); + } + /** Clear an extension. */ + public final BuilderType clearExtension( + final Extension extension) { + return clearExtension((ExtensionLite) extension); + } + /** Clear an extension. */ + public BuilderType clearExtension( + final GeneratedExtension extension) { + return clearExtension((ExtensionLite) extension); + } + + /** Called by subclasses to check if all extensions are initialized. */ + protected boolean extensionsAreInitialized() { + return extensions == null ? true : extensions.isInitialized(); + } + + /** + * Called by the build code path to create a copy of the extensions for + * building the message. + */ + private FieldSet buildExtensions() { + return extensions == null + ? (FieldSet) FieldSet.emptySet() + : extensions.build(); + } + + @Override + public boolean isInitialized() { + return super.isInitialized() && extensionsAreInitialized(); + } + + // --------------------------------------------------------------- + // Reflection + + @Override + public Map getAllFields() { + final Map result = super.getAllFieldsMutable(); + if (extensions != null) { + result.putAll(extensions.getAllFields()); + } + return Collections.unmodifiableMap(result); + } + + @Override + public Object getField(final FieldDescriptor field) { + if (field.isExtension()) { + verifyContainingType(field); + final Object value = extensions == null ? null : extensions.getField(field); + if (value == null) { + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + // Lacking an ExtensionRegistry, we have no way to determine the + // extension's real type, so we return a DynamicMessage. + return DynamicMessage.getDefaultInstance(field.getMessageType()); + } else { + return field.getDefaultValue(); + } + } else { + return value; + } + } else { + return super.getField(field); + } + } + + @Override + public Message.Builder getFieldBuilder(final FieldDescriptor field) { + if (field.isExtension()) { + verifyContainingType(field); + if (field.getJavaType() != FieldDescriptor.JavaType.MESSAGE) { + throw new UnsupportedOperationException( + "getFieldBuilder() called on a non-Message type."); + } + ensureExtensionsIsMutable(); + final Object value = extensions.getFieldAllowBuilders(field); + if (value == null) { + Message.Builder builder = DynamicMessage.newBuilder(field.getMessageType()); + extensions.setField(field, builder); + onChanged(); + return builder; + } else { + if (value instanceof Message.Builder) { + return (Message.Builder) value; + } else if (value instanceof Message) { + Message.Builder builder = ((Message) value).toBuilder(); + extensions.setField(field, builder); + onChanged(); + return builder; + } else { + throw new UnsupportedOperationException( + "getRepeatedFieldBuilder() called on a non-Message type."); + } + } + } else { + return super.getFieldBuilder(field); + } + } + + @Override + public int getRepeatedFieldCount(final FieldDescriptor field) { + if (field.isExtension()) { + verifyContainingType(field); + return extensions == null ? 0 : extensions.getRepeatedFieldCount(field); + } else { + return super.getRepeatedFieldCount(field); + } + } + + @Override + public Object getRepeatedField(final FieldDescriptor field, + final int index) { + if (field.isExtension()) { + verifyContainingType(field); + if (extensions == null) { + throw new IndexOutOfBoundsException(); + } + return extensions.getRepeatedField(field, index); + } else { + return super.getRepeatedField(field, index); + } + } + + @Override + public Message.Builder getRepeatedFieldBuilder(final FieldDescriptor field, final int index) { + if (field.isExtension()) { + verifyContainingType(field); + ensureExtensionsIsMutable(); + if (field.getJavaType() != FieldDescriptor.JavaType.MESSAGE) { + throw new UnsupportedOperationException( + "getRepeatedFieldBuilder() called on a non-Message type."); + } + final Object value = extensions.getRepeatedFieldAllowBuilders(field, index); + if (value instanceof Message.Builder) { + return (Message.Builder) value; + } else if (value instanceof Message) { + Message.Builder builder = ((Message) value).toBuilder(); + extensions.setRepeatedField(field, index, builder); + onChanged(); + return builder; + } else { + throw new UnsupportedOperationException( + "getRepeatedFieldBuilder() called on a non-Message type."); + } + } else { + return super.getRepeatedFieldBuilder(field, index); + } + } + + @Override + public boolean hasField(final FieldDescriptor field) { + if (field.isExtension()) { + verifyContainingType(field); + return extensions == null ? false : extensions.hasField(field); + } else { + return super.hasField(field); + } + } + + @Override + public BuilderType setField(final FieldDescriptor field, + final Object value) { + if (field.isExtension()) { + verifyContainingType(field); + ensureExtensionsIsMutable(); + extensions.setField(field, value); + onChanged(); + return (BuilderType) this; + } else { + return super.setField(field, value); + } + } + + @Override + public BuilderType clearField(final FieldDescriptor field) { + if (field.isExtension()) { + verifyContainingType(field); + ensureExtensionsIsMutable(); + extensions.clearField(field); + onChanged(); + return (BuilderType) this; + } else { + return super.clearField(field); + } + } + + @Override + public BuilderType setRepeatedField(final FieldDescriptor field, + final int index, final Object value) { + if (field.isExtension()) { + verifyContainingType(field); + ensureExtensionsIsMutable(); + extensions.setRepeatedField(field, index, value); + onChanged(); + return (BuilderType) this; + } else { + return super.setRepeatedField(field, index, value); + } + } + + @Override + public BuilderType addRepeatedField(final FieldDescriptor field, + final Object value) { + if (field.isExtension()) { + verifyContainingType(field); + ensureExtensionsIsMutable(); + extensions.addRepeatedField(field, value); + onChanged(); + return (BuilderType) this; + } else { + return super.addRepeatedField(field, value); + } + } + + @Override + public Message.Builder newBuilderForField(final FieldDescriptor field) { + if (field.isExtension()) { + return DynamicMessage.newBuilder(field.getMessageType()); + } else { + return super.newBuilderForField(field); + } + } + + protected final void mergeExtensionFields(final ExtendableMessage other) { + if (other.extensions != null) { + ensureExtensionsIsMutable(); + extensions.mergeFrom(other.extensions); + onChanged(); + } + } + + private void verifyContainingType(final FieldDescriptor field) { + if (field.getContainingType() != getDescriptorForType()) { + throw new IllegalArgumentException( + "FieldDescriptor does not match message type."); + } + } + } + + // ----------------------------------------------------------------- + + /** + * Gets the descriptor for an extension. The implementation depends on whether + * the extension is scoped in the top level of a file or scoped in a Message. + */ + static interface ExtensionDescriptorRetriever { + FieldDescriptor getDescriptor(); + } + + + // ================================================================= + + /** Calls Class.getMethod and throws a RuntimeException if it fails. */ + @SuppressWarnings("unchecked") + private static Method getMethodOrDie( + final Class clazz, final String name, final Class... params) { + try { + return clazz.getMethod(name, params); + } catch (NoSuchMethodException e) { + throw new RuntimeException( + "Generated message class \"" + clazz.getName() + + "\" missing method \"" + name + "\".", e); + } + } + + /** Calls invoke and throws a RuntimeException if it fails. */ + private static Object invokeOrDie( + final Method method, final Object object, final Object... params) { + try { + return method.invoke(object, params); + } catch (IllegalAccessException e) { + throw new RuntimeException( + "Couldn't use Java reflection to implement protocol message " + + "reflection.", e); + } catch (InvocationTargetException e) { + final Throwable cause = e.getCause(); + if (cause instanceof RuntimeException) { + throw (RuntimeException) cause; + } else if (cause instanceof Error) { + throw (Error) cause; + } else { + throw new RuntimeException( + "Unexpected exception thrown by generated accessor method.", cause); + } + } + } + + /** + * Gets the map field with the given field number. This method should be overridden in the + * generated message class if the message contains map fields. + * + *

Unlike other field types, reflection support for map fields can't be implemented based on + * generated public API because we need to access a map field as a list in reflection API but the + * generated API only allows us to access it as a map. This method returns the underlying map + * field directly and thus enables us to access the map field as a list. + */ + @SuppressWarnings({"rawtypes", "unused"}) + protected MapField internalGetMapField(int fieldNumber) { + // Note that we can't use descriptor names here because this method will + // be called when descriptor is being initialized. + throw new RuntimeException( + "No map fields found in " + getClass().getName()); + } + + /** + * Users should ignore this class. This class provides the implementation + * with access to the fields of a message object using Java reflection. + */ + public static final class FieldAccessorTable { + + /** + * Construct a FieldAccessorTable for a particular message class. Only + * one FieldAccessorTable should ever be constructed per class. + * + * @param descriptor The type's descriptor. + * @param camelCaseNames The camelcase names of all fields in the message. + * These are used to derive the accessor method names. + * @param messageClass The message type. + * @param builderClass The builder type. + */ + public FieldAccessorTable( + final Descriptor descriptor, + final String[] camelCaseNames, + final Class messageClass, + final Class builderClass) { + this(descriptor, camelCaseNames); + ensureFieldAccessorsInitialized(messageClass, builderClass); + } + + /** + * Construct a FieldAccessorTable for a particular message class without + * initializing FieldAccessors. + */ + public FieldAccessorTable( + final Descriptor descriptor, + final String[] camelCaseNames) { + this.descriptor = descriptor; + this.camelCaseNames = camelCaseNames; + fields = new FieldAccessor[descriptor.getFields().size()]; + oneofs = new OneofAccessor[descriptor.getOneofs().size()]; + initialized = false; + } + + /** + * Ensures the field accessors are initialized. This method is thread-safe. + * + * @param messageClass The message type. + * @param builderClass The builder type. + * @return this + */ + public FieldAccessorTable ensureFieldAccessorsInitialized( + Class messageClass, + Class builderClass) { + if (initialized) { return this; } + synchronized (this) { + if (initialized) { return this; } + int fieldsSize = fields.length; + for (int i = 0; i < fieldsSize; i++) { + FieldDescriptor field = descriptor.getFields().get(i); + String containingOneofCamelCaseName = null; + if (field.getContainingOneof() != null) { + containingOneofCamelCaseName = + camelCaseNames[fieldsSize + field.getContainingOneof().getIndex()]; + } + if (field.isRepeated()) { + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + if (field.isMapField()) { + fields[i] = new MapFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass); + } else { + fields[i] = new RepeatedMessageFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass); + } + } else if (field.getJavaType() == FieldDescriptor.JavaType.ENUM) { + fields[i] = new RepeatedEnumFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass); + } else { + fields[i] = new RepeatedFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass); + } + } else { + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + fields[i] = new SingularMessageFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass, + containingOneofCamelCaseName); + } else if (field.getJavaType() == FieldDescriptor.JavaType.ENUM) { + fields[i] = new SingularEnumFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass, + containingOneofCamelCaseName); + } else if (field.getJavaType() == FieldDescriptor.JavaType.STRING) { + fields[i] = new SingularStringFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass, + containingOneofCamelCaseName); + } else { + fields[i] = new SingularFieldAccessor( + field, camelCaseNames[i], messageClass, builderClass, + containingOneofCamelCaseName); + } + } + } + + int oneofsSize = oneofs.length; + for (int i = 0; i < oneofsSize; i++) { + oneofs[i] = + new OneofAccessor( + descriptor, i, camelCaseNames[i + fieldsSize], messageClass, builderClass); + } + initialized = true; + camelCaseNames = null; + return this; + } + } + + private final Descriptor descriptor; + private final FieldAccessor[] fields; + private String[] camelCaseNames; + private final OneofAccessor[] oneofs; + private volatile boolean initialized; + + /** Get the FieldAccessor for a particular field. */ + private FieldAccessor getField(final FieldDescriptor field) { + if (field.getContainingType() != descriptor) { + throw new IllegalArgumentException( + "FieldDescriptor does not match message type."); + } else if (field.isExtension()) { + // If this type had extensions, it would subclass ExtendableMessage, + // which overrides the reflection interface to handle extensions. + throw new IllegalArgumentException( + "This type does not have extensions."); + } + return fields[field.getIndex()]; + } + + /** Get the OneofAccessor for a particular oneof. */ + private OneofAccessor getOneof(final OneofDescriptor oneof) { + if (oneof.getContainingType() != descriptor) { + throw new IllegalArgumentException( + "OneofDescriptor does not match message type."); + } + return oneofs[oneof.getIndex()]; + } + + /** + * Abstract interface that provides access to a single field. This is + * implemented differently depending on the field type and cardinality. + */ + private interface FieldAccessor { + Object get(GeneratedMessageV3 message); + Object get(GeneratedMessageV3.Builder builder); + Object getRaw(GeneratedMessageV3 message); + Object getRaw(GeneratedMessageV3.Builder builder); + void set(Builder builder, Object value); + Object getRepeated(GeneratedMessageV3 message, int index); + Object getRepeated(GeneratedMessageV3.Builder builder, int index); + Object getRepeatedRaw(GeneratedMessageV3 message, int index); + Object getRepeatedRaw(GeneratedMessageV3.Builder builder, int index); + void setRepeated(Builder builder, + int index, Object value); + void addRepeated(Builder builder, Object value); + boolean has(GeneratedMessageV3 message); + boolean has(GeneratedMessageV3.Builder builder); + int getRepeatedCount(GeneratedMessageV3 message); + int getRepeatedCount(GeneratedMessageV3.Builder builder); + void clear(Builder builder); + Message.Builder newBuilder(); + Message.Builder getBuilder(GeneratedMessageV3.Builder builder); + Message.Builder getRepeatedBuilder(GeneratedMessageV3.Builder builder, + int index); + } + + /** OneofAccessor provides access to a single oneof. */ + private static class OneofAccessor { + OneofAccessor( + final Descriptor descriptor, + final int oneofIndex, + final String camelCaseName, + final Class messageClass, + final Class builderClass) { + this.descriptor = descriptor; + OneofDescriptor oneofDescriptor = descriptor.getOneofs().get(oneofIndex); + if (oneofDescriptor.isSynthetic()) { + caseMethod = null; + caseMethodBuilder = null; + fieldDescriptor = oneofDescriptor.getFields().get(0); + } else { + caseMethod = getMethodOrDie(messageClass, "get" + camelCaseName + "Case"); + caseMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName + "Case"); + fieldDescriptor = null; + } + clearMethod = getMethodOrDie(builderClass, "clear" + camelCaseName); + } + + private final Descriptor descriptor; + private final Method caseMethod; + private final Method caseMethodBuilder; + private final Method clearMethod; + private final FieldDescriptor fieldDescriptor; + + public boolean has(final GeneratedMessageV3 message) { + if (fieldDescriptor != null) { + return message.hasField(fieldDescriptor); + } else { + if (((Internal.EnumLite) invokeOrDie(caseMethod, message)).getNumber() == 0) { + return false; + } + } + return true; + } + + public boolean has(GeneratedMessageV3.Builder builder) { + if (fieldDescriptor != null) { + return builder.hasField(fieldDescriptor); + } else { + if (((Internal.EnumLite) invokeOrDie(caseMethodBuilder, builder)).getNumber() == 0) { + return false; + } + } + return true; + } + + public FieldDescriptor get(final GeneratedMessageV3 message) { + if (fieldDescriptor != null) { + return message.hasField(fieldDescriptor) ? fieldDescriptor : null; + } else { + int fieldNumber = ((Internal.EnumLite) invokeOrDie(caseMethod, message)).getNumber(); + if (fieldNumber > 0) { + return descriptor.findFieldByNumber(fieldNumber); + } + } + return null; + } + + public FieldDescriptor get(GeneratedMessageV3.Builder builder) { + if (fieldDescriptor != null) { + return builder.hasField(fieldDescriptor) ? fieldDescriptor : null; + } else { + int fieldNumber = + ((Internal.EnumLite) invokeOrDie(caseMethodBuilder, builder)).getNumber(); + if (fieldNumber > 0) { + return descriptor.findFieldByNumber(fieldNumber); + } + } + return null; + } + + public void clear(final Builder builder) { + invokeOrDie(clearMethod, builder); + } + } + + // --------------------------------------------------------------- + + private static class SingularFieldAccessor implements FieldAccessor { + private interface MethodInvoker { + Object get(final GeneratedMessageV3 message); + + Object get(GeneratedMessageV3.Builder builder); + + int getOneofFieldNumber(final GeneratedMessageV3 message); + + int getOneofFieldNumber(final GeneratedMessageV3.Builder builder); + + void set(final GeneratedMessageV3.Builder builder, final Object value); + + boolean has(final GeneratedMessageV3 message); + + boolean has(GeneratedMessageV3.Builder builder); + + void clear(final GeneratedMessageV3.Builder builder); + } + + private static final class ReflectionInvoker implements MethodInvoker { + protected final Method getMethod; + protected final Method getMethodBuilder; + protected final Method setMethod; + protected final Method hasMethod; + protected final Method hasMethodBuilder; + protected final Method clearMethod; + protected final Method caseMethod; + protected final Method caseMethodBuilder; + + ReflectionInvoker( + final FieldDescriptor descriptor, + final String camelCaseName, + final Class messageClass, + final Class builderClass, + final String containingOneofCamelCaseName, + boolean isOneofField, + boolean hasHasMethod) { + getMethod = getMethodOrDie(messageClass, "get" + camelCaseName); + getMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName); + Class type = getMethod.getReturnType(); + setMethod = getMethodOrDie(builderClass, "set" + camelCaseName, type); + hasMethod = hasHasMethod ? getMethodOrDie(messageClass, "has" + camelCaseName) : null; + hasMethodBuilder = + hasHasMethod ? getMethodOrDie(builderClass, "has" + camelCaseName) : null; + clearMethod = getMethodOrDie(builderClass, "clear" + camelCaseName); + caseMethod = + isOneofField + ? getMethodOrDie(messageClass, "get" + containingOneofCamelCaseName + "Case") + : null; + caseMethodBuilder = + isOneofField + ? getMethodOrDie(builderClass, "get" + containingOneofCamelCaseName + "Case") + : null; + } + + @Override + public Object get(final GeneratedMessageV3 message) { + return invokeOrDie(getMethod, message); + } + + @Override + public Object get(GeneratedMessageV3.Builder builder) { + return invokeOrDie(getMethodBuilder, builder); + } + + @Override + public int getOneofFieldNumber(final GeneratedMessageV3 message) { + return ((Internal.EnumLite) invokeOrDie(caseMethod, message)).getNumber(); + } + + @Override + public int getOneofFieldNumber(final GeneratedMessageV3.Builder builder) { + return ((Internal.EnumLite) invokeOrDie(caseMethodBuilder, builder)).getNumber(); + } + + @Override + public void set(final GeneratedMessageV3.Builder builder, final Object value) { + invokeOrDie(setMethod, builder, value); + } + + @Override + public boolean has(final GeneratedMessageV3 message) { + return (Boolean) invokeOrDie(hasMethod, message); + } + + @Override + public boolean has(GeneratedMessageV3.Builder builder) { + return (Boolean) invokeOrDie(hasMethodBuilder, builder); + } + + @Override + public void clear(final GeneratedMessageV3.Builder builder) { + invokeOrDie(clearMethod, builder); + } + } + + SingularFieldAccessor( + final FieldDescriptor descriptor, + final String camelCaseName, + final Class messageClass, + final Class builderClass, + final String containingOneofCamelCaseName) { + isOneofField = + descriptor.getContainingOneof() != null + && !descriptor.getContainingOneof().isSynthetic(); + hasHasMethod = + descriptor.getFile().getSyntax() == FileDescriptor.Syntax.PROTO2 + || descriptor.hasOptionalKeyword() + || (!isOneofField && descriptor.getJavaType() == FieldDescriptor.JavaType.MESSAGE); + ReflectionInvoker reflectionInvoker = + new ReflectionInvoker( + descriptor, + camelCaseName, + messageClass, + builderClass, + containingOneofCamelCaseName, + isOneofField, + hasHasMethod); + field = descriptor; + type = reflectionInvoker.getMethod.getReturnType(); + invoker = getMethodInvoker(reflectionInvoker); + } + + static MethodInvoker getMethodInvoker(ReflectionInvoker accessor) { + return accessor; + } + + // Note: We use Java reflection to call public methods rather than + // access private fields directly as this avoids runtime security + // checks. + protected final Class type; + protected final FieldDescriptor field; + protected final boolean isOneofField; + protected final boolean hasHasMethod; + protected final MethodInvoker invoker; + + @Override + public Object get(final GeneratedMessageV3 message) { + return invoker.get(message); + } + @Override + public Object get(GeneratedMessageV3.Builder builder) { + return invoker.get(builder); + } + @Override + public Object getRaw(final GeneratedMessageV3 message) { + return get(message); + } + @Override + public Object getRaw(GeneratedMessageV3.Builder builder) { + return get(builder); + } + @Override + public void set(final Builder builder, final Object value) { + invoker.set(builder, value); + } + @Override + public Object getRepeated(final GeneratedMessageV3 message, final int index) { + throw new UnsupportedOperationException("getRepeatedField() called on a singular field."); + } + @Override + public Object getRepeatedRaw(final GeneratedMessageV3 message, final int index) { + throw new UnsupportedOperationException( + "getRepeatedFieldRaw() called on a singular field."); + } + @Override + public Object getRepeated(GeneratedMessageV3.Builder builder, int index) { + throw new UnsupportedOperationException("getRepeatedField() called on a singular field."); + } + @Override + public Object getRepeatedRaw(GeneratedMessageV3.Builder builder, int index) { + throw new UnsupportedOperationException( + "getRepeatedFieldRaw() called on a singular field."); + } + @Override + public void setRepeated(final Builder builder, final int index, final Object value) { + throw new UnsupportedOperationException("setRepeatedField() called on a singular field."); + } + @Override + public void addRepeated(final Builder builder, final Object value) { + throw new UnsupportedOperationException("addRepeatedField() called on a singular field."); + } + @Override + public boolean has(final GeneratedMessageV3 message) { + if (!hasHasMethod) { + if (isOneofField) { + return invoker.getOneofFieldNumber(message) == field.getNumber(); + } + return !get(message).equals(field.getDefaultValue()); + } + return invoker.has(message); + } + @Override + public boolean has(GeneratedMessageV3.Builder builder) { + if (!hasHasMethod) { + if (isOneofField) { + return invoker.getOneofFieldNumber(builder) == field.getNumber(); + } + return !get(builder).equals(field.getDefaultValue()); + } + return invoker.has(builder); + } + @Override + public int getRepeatedCount(final GeneratedMessageV3 message) { + throw new UnsupportedOperationException( + "getRepeatedFieldSize() called on a singular field."); + } + @Override + public int getRepeatedCount(GeneratedMessageV3.Builder builder) { + throw new UnsupportedOperationException( + "getRepeatedFieldSize() called on a singular field."); + } + @Override + public void clear(final Builder builder) { + invoker.clear(builder); + } + @Override + public Message.Builder newBuilder() { + throw new UnsupportedOperationException( + "newBuilderForField() called on a non-Message type."); + } + @Override + public Message.Builder getBuilder(GeneratedMessageV3.Builder builder) { + throw new UnsupportedOperationException("getFieldBuilder() called on a non-Message type."); + } + @Override + public Message.Builder getRepeatedBuilder(GeneratedMessageV3.Builder builder, int index) { + throw new UnsupportedOperationException( + "getRepeatedFieldBuilder() called on a non-Message type."); + } + } + + private static class RepeatedFieldAccessor implements FieldAccessor { + interface MethodInvoker { + public Object get(final GeneratedMessageV3 message); + + public Object get(GeneratedMessageV3.Builder builder); + + Object getRepeated(final GeneratedMessageV3 message, final int index); + + Object getRepeated(GeneratedMessageV3.Builder builder, int index); + + void setRepeated( + final GeneratedMessageV3.Builder builder, final int index, final Object value); + + void addRepeated(final GeneratedMessageV3.Builder builder, final Object value); + + int getRepeatedCount(final GeneratedMessageV3 message); + + int getRepeatedCount(GeneratedMessageV3.Builder builder); + + void clear(final GeneratedMessageV3.Builder builder); + } + + private static final class ReflectionInvoker implements MethodInvoker { + protected final Method getMethod; + protected final Method getMethodBuilder; + protected final Method getRepeatedMethod; + protected final Method getRepeatedMethodBuilder; + protected final Method setRepeatedMethod; + protected final Method addRepeatedMethod; + protected final Method getCountMethod; + protected final Method getCountMethodBuilder; + protected final Method clearMethod; + + ReflectionInvoker( + final FieldDescriptor descriptor, + final String camelCaseName, + final Class messageClass, + final Class builderClass) { + getMethod = getMethodOrDie(messageClass, "get" + camelCaseName + "List"); + getMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName + "List"); + getRepeatedMethod = getMethodOrDie(messageClass, "get" + camelCaseName, Integer.TYPE); + getRepeatedMethodBuilder = + getMethodOrDie(builderClass, "get" + camelCaseName, Integer.TYPE); + Class type = getRepeatedMethod.getReturnType(); + setRepeatedMethod = + getMethodOrDie(builderClass, "set" + camelCaseName, Integer.TYPE, type); + addRepeatedMethod = getMethodOrDie(builderClass, "add" + camelCaseName, type); + getCountMethod = getMethodOrDie(messageClass, "get" + camelCaseName + "Count"); + getCountMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName + "Count"); + clearMethod = getMethodOrDie(builderClass, "clear" + camelCaseName); + } + + @Override + public Object get(final GeneratedMessageV3 message) { + return invokeOrDie(getMethod, message); + } + + @Override + public Object get(GeneratedMessageV3.Builder builder) { + return invokeOrDie(getMethodBuilder, builder); + } + + @Override + public Object getRepeated( + final GeneratedMessageV3 message, final int index) { + return invokeOrDie(getRepeatedMethod, message, index); + } + + @Override + public Object getRepeated(GeneratedMessageV3.Builder builder, int index) { + return invokeOrDie(getRepeatedMethodBuilder, builder, index); + } + + @Override + public void setRepeated( + final GeneratedMessageV3.Builder builder, final int index, final Object value) { + invokeOrDie(setRepeatedMethod, builder, index, value); + } + + @Override + public void addRepeated( + final GeneratedMessageV3.Builder builder, final Object value) { + invokeOrDie(addRepeatedMethod, builder, value); + } + + @Override + public int getRepeatedCount(final GeneratedMessageV3 message) { + return (Integer) invokeOrDie(getCountMethod, message); + } + + @Override + public int getRepeatedCount(GeneratedMessageV3.Builder builder) { + return (Integer) invokeOrDie(getCountMethodBuilder, builder); + } + + @Override + public void clear(final GeneratedMessageV3.Builder builder) { + invokeOrDie(clearMethod, builder); + } + } + + protected final Class type; + protected final MethodInvoker invoker; + + RepeatedFieldAccessor( + final FieldDescriptor descriptor, final String camelCaseName, + final Class messageClass, + final Class builderClass) { + ReflectionInvoker reflectionInvoker = + new ReflectionInvoker(descriptor, camelCaseName, messageClass, builderClass); + type = reflectionInvoker.getRepeatedMethod.getReturnType(); + invoker = getMethodInvoker(reflectionInvoker); + } + + static MethodInvoker getMethodInvoker(ReflectionInvoker accessor) { + return accessor; + } + + @Override + public Object get(final GeneratedMessageV3 message) { + return invoker.get(message); + } + @Override + public Object get(GeneratedMessageV3.Builder builder) { + return invoker.get(builder); + } + @Override + public Object getRaw(final GeneratedMessageV3 message) { + return get(message); + } + @Override + public Object getRaw(GeneratedMessageV3.Builder builder) { + return get(builder); + } + @Override + public void set(final Builder builder, final Object value) { + // Add all the elements individually. This serves two purposes: + // 1) Verifies that each element has the correct type. + // 2) Insures that the caller cannot modify the list later on and + // have the modifications be reflected in the message. + clear(builder); + for (final Object element : (List) value) { + addRepeated(builder, element); + } + } + @Override + public Object getRepeated(final GeneratedMessageV3 message, final int index) { + return invoker.getRepeated(message, index); + } + @Override + public Object getRepeated(GeneratedMessageV3.Builder builder, int index) { + return invoker.getRepeated(builder, index); + } + @Override + public Object getRepeatedRaw(GeneratedMessageV3 message, int index) { + return getRepeated(message, index); + } + @Override + public Object getRepeatedRaw(GeneratedMessageV3.Builder builder, int index) { + return getRepeated(builder, index); + } + @Override + public void setRepeated(final Builder builder, final int index, final Object value) { + invoker.setRepeated(builder, index, value); + } + @Override + public void addRepeated(final Builder builder, final Object value) { + invoker.addRepeated(builder, value); + } + @Override + public boolean has(final GeneratedMessageV3 message) { + throw new UnsupportedOperationException("hasField() called on a repeated field."); + } + @Override + public boolean has(GeneratedMessageV3.Builder builder) { + throw new UnsupportedOperationException("hasField() called on a repeated field."); + } + @Override + public int getRepeatedCount(final GeneratedMessageV3 message) { + return invoker.getRepeatedCount(message); + } + @Override + public int getRepeatedCount(GeneratedMessageV3.Builder builder) { + return invoker.getRepeatedCount(builder); + } + @Override + public void clear(final Builder builder) { + invoker.clear(builder); + } + @Override + public Message.Builder newBuilder() { + throw new UnsupportedOperationException( + "newBuilderForField() called on a non-Message type."); + } + @Override + public Message.Builder getBuilder(GeneratedMessageV3.Builder builder) { + throw new UnsupportedOperationException("getFieldBuilder() called on a non-Message type."); + } + @Override + public Message.Builder getRepeatedBuilder(GeneratedMessageV3.Builder builder, int index) { + throw new UnsupportedOperationException( + "getRepeatedFieldBuilder() called on a non-Message type."); + } + } + + private static class MapFieldAccessor implements FieldAccessor { + MapFieldAccessor( + final FieldDescriptor descriptor, final String camelCaseName, + final Class messageClass, + final Class builderClass) { + field = descriptor; + Method getDefaultInstanceMethod = + getMethodOrDie(messageClass, "getDefaultInstance"); + MapField defaultMapField = getMapField( + (GeneratedMessageV3) invokeOrDie(getDefaultInstanceMethod, null)); + mapEntryMessageDefaultInstance = + defaultMapField.getMapEntryMessageDefaultInstance(); + } + + private final FieldDescriptor field; + private final Message mapEntryMessageDefaultInstance; + + private MapField getMapField(GeneratedMessageV3 message) { + return (MapField) message.internalGetMapField(field.getNumber()); + } + + private MapField getMapField(GeneratedMessageV3.Builder builder) { + return (MapField) builder.internalGetMapField(field.getNumber()); + } + + private MapField getMutableMapField( + GeneratedMessageV3.Builder builder) { + return (MapField) builder.internalGetMutableMapField( + field.getNumber()); + } + + private Message coerceType(Message value) { + if (value == null) { + return null; + } + if (mapEntryMessageDefaultInstance.getClass().isInstance(value)) { + return value; + } + // The value is not the exact right message type. However, if it + // is an alternative implementation of the same type -- e.g. a + // DynamicMessage -- we should accept it. In this case we can make + // a copy of the message. + return mapEntryMessageDefaultInstance.toBuilder().mergeFrom(value).build(); + } + + @Override + @SuppressWarnings("unchecked") + public Object get(GeneratedMessageV3 message) { + List result = new ArrayList<>(); + for (int i = 0; i < getRepeatedCount(message); i++) { + result.add(getRepeated(message, i)); + } + return Collections.unmodifiableList(result); + } + + @Override + @SuppressWarnings("unchecked") + public Object get(Builder builder) { + List result = new ArrayList<>(); + for (int i = 0; i < getRepeatedCount(builder); i++) { + result.add(getRepeated(builder, i)); + } + return Collections.unmodifiableList(result); + } + + @Override + public Object getRaw(GeneratedMessageV3 message) { + return get(message); + } + + @Override + public Object getRaw(GeneratedMessageV3.Builder builder) { + return get(builder); + } + + @Override + public void set(Builder builder, Object value) { + clear(builder); + for (Object entry : (List) value) { + addRepeated(builder, entry); + } + } + + @Override + public Object getRepeated(GeneratedMessageV3 message, int index) { + return getMapField(message).getList().get(index); + } + + @Override + public Object getRepeated(Builder builder, int index) { + return getMapField(builder).getList().get(index); + } + + @Override + public Object getRepeatedRaw(GeneratedMessageV3 message, int index) { + return getRepeated(message, index); + } + + @Override + public Object getRepeatedRaw(Builder builder, int index) { + return getRepeated(builder, index); + } + + @Override + public void setRepeated(Builder builder, int index, Object value) { + getMutableMapField(builder).getMutableList().set(index, coerceType((Message) value)); + } + + @Override + public void addRepeated(Builder builder, Object value) { + getMutableMapField(builder).getMutableList().add(coerceType((Message) value)); + } + + @Override + public boolean has(GeneratedMessageV3 message) { + throw new UnsupportedOperationException( + "hasField() is not supported for repeated fields."); + } + + @Override + public boolean has(Builder builder) { + throw new UnsupportedOperationException( + "hasField() is not supported for repeated fields."); + } + + @Override + public int getRepeatedCount(GeneratedMessageV3 message) { + return getMapField(message).getList().size(); + } + + @Override + public int getRepeatedCount(Builder builder) { + return getMapField(builder).getList().size(); + } + + @Override + public void clear(Builder builder) { + getMutableMapField(builder).getMutableList().clear(); + } + + @Override + public com.google.protobuf.Message.Builder newBuilder() { + return mapEntryMessageDefaultInstance.newBuilderForType(); + } + + @Override + public com.google.protobuf.Message.Builder getBuilder(Builder builder) { + throw new UnsupportedOperationException( + "Nested builder not supported for map fields."); + } + + @Override + public com.google.protobuf.Message.Builder getRepeatedBuilder(Builder builder, int index) { + throw new UnsupportedOperationException( + "Nested builder not supported for map fields."); + } + } + + // --------------------------------------------------------------- + + private static final class SingularEnumFieldAccessor + extends SingularFieldAccessor { + SingularEnumFieldAccessor( + final FieldDescriptor descriptor, final String camelCaseName, + final Class messageClass, + final Class builderClass, + final String containingOneofCamelCaseName) { + super(descriptor, camelCaseName, messageClass, builderClass, containingOneofCamelCaseName); + + enumDescriptor = descriptor.getEnumType(); + + valueOfMethod = getMethodOrDie(type, "valueOf", EnumValueDescriptor.class); + getValueDescriptorMethod = getMethodOrDie(type, "getValueDescriptor"); + + supportUnknownEnumValue = descriptor.getFile().supportsUnknownEnumValue(); + if (supportUnknownEnumValue) { + getValueMethod = + getMethodOrDie(messageClass, "get" + camelCaseName + "Value"); + getValueMethodBuilder = + getMethodOrDie(builderClass, "get" + camelCaseName + "Value"); + setValueMethod = + getMethodOrDie(builderClass, "set" + camelCaseName + "Value", int.class); + } + } + + private EnumDescriptor enumDescriptor; + + private Method valueOfMethod; + private Method getValueDescriptorMethod; + + private boolean supportUnknownEnumValue; + private Method getValueMethod; + private Method getValueMethodBuilder; + private Method setValueMethod; + + @Override + public Object get(final GeneratedMessageV3 message) { + if (supportUnknownEnumValue) { + int value = (Integer) invokeOrDie(getValueMethod, message); + return enumDescriptor.findValueByNumberCreatingIfUnknown(value); + } + return invokeOrDie(getValueDescriptorMethod, super.get(message)); + } + + @Override + public Object get(final GeneratedMessageV3.Builder builder) { + if (supportUnknownEnumValue) { + int value = (Integer) invokeOrDie(getValueMethodBuilder, builder); + return enumDescriptor.findValueByNumberCreatingIfUnknown(value); + } + return invokeOrDie(getValueDescriptorMethod, super.get(builder)); + } + + @Override + public void set(final Builder builder, final Object value) { + if (supportUnknownEnumValue) { + invokeOrDie(setValueMethod, builder, + ((EnumValueDescriptor) value).getNumber()); + return; + } + super.set(builder, invokeOrDie(valueOfMethod, null, value)); + } + } + + private static final class RepeatedEnumFieldAccessor + extends RepeatedFieldAccessor { + RepeatedEnumFieldAccessor( + final FieldDescriptor descriptor, final String camelCaseName, + final Class messageClass, + final Class builderClass) { + super(descriptor, camelCaseName, messageClass, builderClass); + + enumDescriptor = descriptor.getEnumType(); + + valueOfMethod = getMethodOrDie(type, "valueOf", EnumValueDescriptor.class); + getValueDescriptorMethod = getMethodOrDie(type, "getValueDescriptor"); + + supportUnknownEnumValue = descriptor.getFile().supportsUnknownEnumValue(); + if (supportUnknownEnumValue) { + getRepeatedValueMethod = + getMethodOrDie(messageClass, "get" + camelCaseName + "Value", int.class); + getRepeatedValueMethodBuilder = + getMethodOrDie(builderClass, "get" + camelCaseName + "Value", int.class); + setRepeatedValueMethod = + getMethodOrDie(builderClass, "set" + camelCaseName + "Value", int.class, int.class); + addRepeatedValueMethod = + getMethodOrDie(builderClass, "add" + camelCaseName + "Value", int.class); + } + } + private EnumDescriptor enumDescriptor; + + private final Method valueOfMethod; + private final Method getValueDescriptorMethod; + + private boolean supportUnknownEnumValue; + private Method getRepeatedValueMethod; + private Method getRepeatedValueMethodBuilder; + private Method setRepeatedValueMethod; + private Method addRepeatedValueMethod; + + @Override + @SuppressWarnings("unchecked") + public Object get(final GeneratedMessageV3 message) { + final List newList = new ArrayList<>(); + final int size = getRepeatedCount(message); + for (int i = 0; i < size; i++) { + newList.add(getRepeated(message, i)); + } + return Collections.unmodifiableList(newList); + } + + @Override + @SuppressWarnings("unchecked") + public Object get(final GeneratedMessageV3.Builder builder) { + final List newList = new ArrayList<>(); + final int size = getRepeatedCount(builder); + for (int i = 0; i < size; i++) { + newList.add(getRepeated(builder, i)); + } + return Collections.unmodifiableList(newList); + } + + @Override + public Object getRepeated(final GeneratedMessageV3 message, final int index) { + if (supportUnknownEnumValue) { + int value = (Integer) invokeOrDie(getRepeatedValueMethod, message, index); + return enumDescriptor.findValueByNumberCreatingIfUnknown(value); + } + return invokeOrDie(getValueDescriptorMethod, super.getRepeated(message, index)); + } + + @Override + public Object getRepeated(final GeneratedMessageV3.Builder builder, final int index) { + if (supportUnknownEnumValue) { + int value = (Integer) invokeOrDie(getRepeatedValueMethodBuilder, builder, index); + return enumDescriptor.findValueByNumberCreatingIfUnknown(value); + } + return invokeOrDie(getValueDescriptorMethod, super.getRepeated(builder, index)); + } + + @Override + public void setRepeated(final Builder builder, final int index, final Object value) { + if (supportUnknownEnumValue) { + invokeOrDie(setRepeatedValueMethod, builder, index, + ((EnumValueDescriptor) value).getNumber()); + return; + } + super.setRepeated(builder, index, invokeOrDie(valueOfMethod, null, value)); + } + @Override + public void addRepeated(final Builder builder, final Object value) { + if (supportUnknownEnumValue) { + invokeOrDie(addRepeatedValueMethod, builder, + ((EnumValueDescriptor) value).getNumber()); + return; + } + super.addRepeated(builder, invokeOrDie(valueOfMethod, null, value)); + } + } + + // --------------------------------------------------------------- + + /** + * Field accessor for string fields. + * + *

This class makes getFooBytes() and setFooBytes() available for + * reflection API so that reflection based serialize/parse functions can + * access the raw bytes of the field to preserve non-UTF8 bytes in the + * string. + * + *

This ensures the serialize/parse round-trip safety, which is important + * for servers which forward messages. + */ + private static final class SingularStringFieldAccessor + extends SingularFieldAccessor { + SingularStringFieldAccessor( + final FieldDescriptor descriptor, final String camelCaseName, + final Class messageClass, + final Class builderClass, + final String containingOneofCamelCaseName) { + super(descriptor, camelCaseName, messageClass, builderClass, + containingOneofCamelCaseName); + getBytesMethod = getMethodOrDie(messageClass, + "get" + camelCaseName + "Bytes"); + getBytesMethodBuilder = getMethodOrDie(builderClass, + "get" + camelCaseName + "Bytes"); + setBytesMethodBuilder = getMethodOrDie(builderClass, + "set" + camelCaseName + "Bytes", ByteString.class); + } + + private final Method getBytesMethod; + private final Method getBytesMethodBuilder; + private final Method setBytesMethodBuilder; + + @Override + public Object getRaw(final GeneratedMessageV3 message) { + return invokeOrDie(getBytesMethod, message); + } + + @Override + public Object getRaw(GeneratedMessageV3.Builder builder) { + return invokeOrDie(getBytesMethodBuilder, builder); + } + + @Override + public void set(GeneratedMessageV3.Builder builder, Object value) { + if (value instanceof ByteString) { + invokeOrDie(setBytesMethodBuilder, builder, value); + } else { + super.set(builder, value); + } + } + } + + // --------------------------------------------------------------- + + private static final class SingularMessageFieldAccessor + extends SingularFieldAccessor { + SingularMessageFieldAccessor( + final FieldDescriptor descriptor, final String camelCaseName, + final Class messageClass, + final Class builderClass, + final String containingOneofCamelCaseName) { + super(descriptor, camelCaseName, messageClass, builderClass, + containingOneofCamelCaseName); + + newBuilderMethod = getMethodOrDie(type, "newBuilder"); + getBuilderMethodBuilder = + getMethodOrDie(builderClass, "get" + camelCaseName + "Builder"); + } + + private final Method newBuilderMethod; + private final Method getBuilderMethodBuilder; + + private Object coerceType(final Object value) { + if (type.isInstance(value)) { + return value; + } else { + // The value is not the exact right message type. However, if it + // is an alternative implementation of the same type -- e.g. a + // DynamicMessage -- we should accept it. In this case we can make + // a copy of the message. + return ((Message.Builder) invokeOrDie(newBuilderMethod, null)) + .mergeFrom((Message) value) + .buildPartial(); + } + } + + @Override + public void set(final Builder builder, final Object value) { + super.set(builder, coerceType(value)); + } + @Override + public Message.Builder newBuilder() { + return (Message.Builder) invokeOrDie(newBuilderMethod, null); + } + @Override + public Message.Builder getBuilder(GeneratedMessageV3.Builder builder) { + return (Message.Builder) invokeOrDie(getBuilderMethodBuilder, builder); + } + } + + private static final class RepeatedMessageFieldAccessor + extends RepeatedFieldAccessor { + RepeatedMessageFieldAccessor( + final FieldDescriptor descriptor, final String camelCaseName, + final Class messageClass, + final Class builderClass) { + super(descriptor, camelCaseName, messageClass, builderClass); + + newBuilderMethod = getMethodOrDie(type, "newBuilder"); + getBuilderMethodBuilder = getMethodOrDie(builderClass, + "get" + camelCaseName + "Builder", Integer.TYPE); + } + + private final Method newBuilderMethod; + private final Method getBuilderMethodBuilder; + + private Object coerceType(final Object value) { + if (type.isInstance(value)) { + return value; + } else { + // The value is not the exact right message type. However, if it + // is an alternative implementation of the same type -- e.g. a + // DynamicMessage -- we should accept it. In this case we can make + // a copy of the message. + return ((Message.Builder) invokeOrDie(newBuilderMethod, null)) + .mergeFrom((Message) value) + .build(); + } + } + + @Override + public void setRepeated(final Builder builder, final int index, final Object value) { + super.setRepeated(builder, index, coerceType(value)); + } + @Override + public void addRepeated(final Builder builder, final Object value) { + super.addRepeated(builder, coerceType(value)); + } + @Override + public Message.Builder newBuilder() { + return (Message.Builder) invokeOrDie(newBuilderMethod, null); + } + @Override + public Message.Builder getRepeatedBuilder( + final GeneratedMessageV3.Builder builder, final int index) { + return (Message.Builder) invokeOrDie( + getBuilderMethodBuilder, builder, index); + } + } + } + + /** + * Replaces this object in the output stream with a serialized form. + * Part of Java's serialization magic. Generated sub-classes must override + * this method by calling {@code return super.writeReplace();} + * @return a SerializedForm of this message + */ + protected Object writeReplace() throws ObjectStreamException { + return new GeneratedMessageLite.SerializedForm(this); + } + + /** + * Checks that the {@link Extension} is non-Lite and returns it as a {@link GeneratedExtension}. + */ + private static , T> + Extension checkNotLite(ExtensionLite extension) { + if (extension.isLite()) { + throw new IllegalArgumentException("Expected non-lite extension."); + } + + return (Extension) extension; + } + + protected static boolean isStringEmpty(final Object value) { + if (value instanceof String) { + return ((String) value).isEmpty(); + } else { + return ((ByteString) value).isEmpty(); + } + } + + protected static int computeStringSize(final int fieldNumber, final Object value) { + if (value instanceof String) { + return CodedOutputStream.computeStringSize(fieldNumber, (String) value); + } else { + return CodedOutputStream.computeBytesSize(fieldNumber, (ByteString) value); + } + } + + protected static int computeStringSizeNoTag(final Object value) { + if (value instanceof String) { + return CodedOutputStream.computeStringSizeNoTag((String) value); + } else { + return CodedOutputStream.computeBytesSizeNoTag((ByteString) value); + } + } + + protected static void writeString( + CodedOutputStream output, final int fieldNumber, final Object value) throws IOException { + if (value instanceof String) { + output.writeString(fieldNumber, (String) value); + } else { + output.writeBytes(fieldNumber, (ByteString) value); + } + } + + protected static void writeStringNoTag( + CodedOutputStream output, final Object value) throws IOException { + if (value instanceof String) { + output.writeStringNoTag((String) value); + } else { + output.writeBytesNoTag((ByteString) value); + } + } + + protected static void serializeIntegerMapTo( + CodedOutputStream out, + MapField field, + MapEntry defaultEntry, + int fieldNumber) throws IOException { + Map m = field.getMap(); + if (!out.isSerializationDeterministic()) { + serializeMapTo(out, m, defaultEntry, fieldNumber); + return; + } + // Sorting the unboxed keys and then look up the values during serialization is 2x faster + // than sorting map entries with a custom comparator directly. + int[] keys = new int[m.size()]; + int index = 0; + for (int k : m.keySet()) { + keys[index++] = k; + } + Arrays.sort(keys); + for (int key : keys) { + out.writeMessage(fieldNumber, + defaultEntry.newBuilderForType() + .setKey(key) + .setValue(m.get(key)) + .build()); + } + } + + protected static void serializeLongMapTo( + CodedOutputStream out, + MapField field, + MapEntry defaultEntry, + int fieldNumber) + throws IOException { + Map m = field.getMap(); + if (!out.isSerializationDeterministic()) { + serializeMapTo(out, m, defaultEntry, fieldNumber); + return; + } + + long[] keys = new long[m.size()]; + int index = 0; + for (long k : m.keySet()) { + keys[index++] = k; + } + Arrays.sort(keys); + for (long key : keys) { + out.writeMessage(fieldNumber, + defaultEntry.newBuilderForType() + .setKey(key) + .setValue(m.get(key)) + .build()); + } + } + + protected static void serializeStringMapTo( + CodedOutputStream out, + MapField field, + MapEntry defaultEntry, + int fieldNumber) + throws IOException { + Map m = field.getMap(); + if (!out.isSerializationDeterministic()) { + serializeMapTo(out, m, defaultEntry, fieldNumber); + return; + } + + // Sorting the String keys and then look up the values during serialization is 25% faster than + // sorting map entries with a custom comparator directly. + String[] keys = new String[m.size()]; + keys = m.keySet().toArray(keys); + Arrays.sort(keys); + for (String key : keys) { + out.writeMessage(fieldNumber, + defaultEntry.newBuilderForType() + .setKey(key) + .setValue(m.get(key)) + .build()); + } + } + + protected static void serializeBooleanMapTo( + CodedOutputStream out, + MapField field, + MapEntry defaultEntry, + int fieldNumber) + throws IOException { + Map m = field.getMap(); + if (!out.isSerializationDeterministic()) { + serializeMapTo(out, m, defaultEntry, fieldNumber); + return; + } + maybeSerializeBooleanEntryTo(out, m, defaultEntry, fieldNumber, false); + maybeSerializeBooleanEntryTo(out, m, defaultEntry, fieldNumber, true); + } + + private static void maybeSerializeBooleanEntryTo( + CodedOutputStream out, + Map m, + MapEntry defaultEntry, + int fieldNumber, + boolean key) + throws IOException { + if (m.containsKey(key)) { + out.writeMessage(fieldNumber, + defaultEntry.newBuilderForType() + .setKey(key) + .setValue(m.get(key)) + .build()); + } + } + + /** Serialize the map using the iteration order. */ + private static void serializeMapTo( + CodedOutputStream out, + Map m, + MapEntry defaultEntry, + int fieldNumber) + throws IOException { + for (Map.Entry entry : m.entrySet()) { + out.writeMessage(fieldNumber, + defaultEntry.newBuilderForType() + .setKey(entry.getKey()) + .setValue(entry.getValue()) + .build()); + } + } +} + diff --git a/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/LazyField.java b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/LazyField.java new file mode 100644 index 0000000..035ea60 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/LazyField.java @@ -0,0 +1,154 @@ +// 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. + +package com.google.protobuf; + +import java.util.Iterator; +import java.util.Map.Entry; + +/** + * LazyField encapsulates the logic of lazily parsing message fields. It stores the message in a + * ByteString initially and then parses it on-demand. + * + *

Most methods are implemented in {@link LazyFieldLite} but this class can contain a + * default instance of the message to provide {@code hashCode()}, {@code equals()}, and {@code + * toString()}. + * + * @author xiangl@google.com (Xiang Li) + */ +public class LazyField extends LazyFieldLite { + + /** + * Carry a message's default instance which is used by {@code hashCode()}, {@code equals()}, and + * {@code toString()}. + */ + private final MessageLite defaultInstance; + + public LazyField( + MessageLite defaultInstance, ExtensionRegistryLite extensionRegistry, ByteString bytes) { + super(extensionRegistry, bytes); + + this.defaultInstance = defaultInstance; + } + + @Override + public boolean containsDefaultInstance() { + return super.containsDefaultInstance() || value == defaultInstance; + } + + public MessageLite getValue() { + return getValue(defaultInstance); + } + + @Override + public int hashCode() { + return getValue().hashCode(); + } + + @Override + public boolean equals(Object obj) { + return getValue().equals(obj); + } + + @Override + public String toString() { + return getValue().toString(); + } + + // ==================================================== + + /** + * LazyEntry and LazyIterator are used to encapsulate the LazyField, when users iterate all fields + * from FieldSet. + */ + static class LazyEntry implements Entry { + private Entry entry; + + private LazyEntry(Entry entry) { + this.entry = entry; + } + + @Override + public K getKey() { + return entry.getKey(); + } + + @Override + public Object getValue() { + LazyField field = entry.getValue(); + if (field == null) { + return null; + } + return field.getValue(); + } + + public LazyField getField() { + return entry.getValue(); + } + + @Override + public Object setValue(Object value) { + if (!(value instanceof MessageLite)) { + throw new IllegalArgumentException( + "LazyField now only used for MessageSet, " + + "and the value of MessageSet must be an instance of MessageLite"); + } + return entry.getValue().setValue((MessageLite) value); + } + } + + static class LazyIterator implements Iterator> { + private Iterator> iterator; + + public LazyIterator(Iterator> iterator) { + this.iterator = iterator; + } + + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + @SuppressWarnings("unchecked") + public Entry next() { + Entry entry = iterator.next(); + if (entry.getValue() instanceof LazyField) { + return new LazyEntry((Entry) entry); + } + return (Entry) entry; + } + + @Override + public void remove() { + iterator.remove(); + } + } +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/MapFieldSchemaLite.java b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/MapFieldSchemaLite.java new file mode 100644 index 0000000..8a8c78d --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/MapFieldSchemaLite.java @@ -0,0 +1,107 @@ +// 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. + +package com.google.protobuf; + +import com.google.protobuf.MapEntryLite.Metadata; +import java.util.Map; + +class MapFieldSchemaLite implements MapFieldSchema { + + @Override + public Map forMutableMapData(Object mapField) { + return (MapFieldLite) mapField; + } + + @Override + public Metadata forMapMetadata(Object mapDefaultEntry) { + return ((MapEntryLite) mapDefaultEntry).getMetadata(); + } + + @Override + public Map forMapData(Object mapField) { + return (MapFieldLite) mapField; + } + + @Override + public boolean isImmutable(Object mapField) { + return !((MapFieldLite) mapField).isMutable(); + } + + @Override + public Object toImmutable(Object mapField) { + ((MapFieldLite) mapField).makeImmutable(); + return mapField; + } + + @Override + public Object newMapField(Object unused) { + return MapFieldLite.emptyMapField().mutableCopy(); + } + + @Override + public Object mergeFrom(Object destMapField, Object srcMapField) { + return mergeFromLite(destMapField, srcMapField); + } + + @SuppressWarnings("unchecked") + private static MapFieldLite mergeFromLite(Object destMapField, Object srcMapField) { + MapFieldLite mine = (MapFieldLite) destMapField; + MapFieldLite other = (MapFieldLite) srcMapField; + if (!other.isEmpty()) { + if (!mine.isMutable()) { + mine = mine.mutableCopy(); + } + mine.mergeFrom(other); + } + return mine; + } + + @Override + public int getSerializedSize(int fieldNumber, Object mapField, Object mapDefaultEntry) { + return getSerializedSizeLite(fieldNumber, mapField, mapDefaultEntry); + } + + @SuppressWarnings("unchecked") + private static int getSerializedSizeLite( + int fieldNumber, Object mapField, Object defaultEntry) { + MapFieldLite mapFieldLite = (MapFieldLite) mapField; + MapEntryLite defaultEntryLite = (MapEntryLite) defaultEntry; + + if (mapFieldLite.isEmpty()) { + return 0; + } + int size = 0; + for (Map.Entry entry : mapFieldLite.entrySet()) { + size += defaultEntryLite.computeMessageSize(fieldNumber, entry.getKey(), entry.getValue()); + } + return size; + } +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/Reader.java b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/Reader.java new file mode 100644 index 0000000..705096f --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/Reader.java @@ -0,0 +1,379 @@ +// 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. + +package com.google.protobuf; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +/** A reader of fields from a serialized protobuf message. */ +// TODO(nathanmittler): Refactor to allow the reader to allocate properly sized lists. +@ExperimentalApi +interface Reader { + /** Value used to indicate that the end of input has been reached. */ + int READ_DONE = Integer.MAX_VALUE; + + /** Value used to indicate that the reader does not know the tag about the field. */ + int TAG_UNKNOWN = 0; + + boolean shouldDiscardUnknownFields(); + + /** + * Gets the field number for the current field being read. + * + *

TODO(liujisi): Rename it to make it more explicit about the side effect on the underlying + * buffer. + * + * @return the current field number or {@link #READ_DONE} if the end of input has been reached. + */ + int getFieldNumber() throws IOException; + + /** + * Gets the wire tag of the current field. + * + * @return the current wire tag or {@link #TAG_UNKNOWN} if the reader does not know the tag of the + * current field. + */ + int getTag(); + + /** + * Skips the current field and advances the reader to the next field. + * + * @return {@code true} if there are more fields or {@code false} if the end of input has been + * reached. + */ + boolean skipField() throws IOException; + + /** + * Reads and returns the next field of type {@code DOUBLE} and advances the reader to the next + * field. + */ + double readDouble() throws IOException; + + /** + * Reads and returns the next field of type {@code FLOAT} and advances the reader to the next + * field. + */ + float readFloat() throws IOException; + + /** + * Reads and returns the next field of type {@code UINT64} and advances the reader to the next + * field. + */ + long readUInt64() throws IOException; + + /** + * Reads and returns the next field of type {@code INT64} and advances the reader to the next + * field. + */ + long readInt64() throws IOException; + + /** + * Reads and returns the next field of type {@code INT32} and advances the reader to the next + * field. + */ + int readInt32() throws IOException; + + /** + * Reads and returns the next field of type {@code FIXED64} and advances the reader to the next + * field. + */ + long readFixed64() throws IOException; + + /** + * Reads and returns the next field of type {@code FIXED32} and advances the reader to the next + * field. + */ + int readFixed32() throws IOException; + + /** + * Reads and returns the next field of type {@code BOOL} and advances the reader to the next + * field. + */ + boolean readBool() throws IOException; + + /** + * Reads and returns the next field of type {@code STRING} and advances the reader to the next + * field. If the stream contains malformed UTF-8, replace the offending bytes with the standard + * UTF-8 replacement character. + */ + String readString() throws IOException; + + /** + * Reads and returns the next field of type {@code STRING} and advances the reader to the next + * field. If the stream contains malformed UTF-8, throw exception {@link + * InvalidProtocolBufferException}. + */ + String readStringRequireUtf8() throws IOException; + + // TODO(yilunchong): the lack of other opinions for whether to expose this on the interface + T readMessageBySchemaWithCheck(Schema schema, ExtensionRegistryLite extensionRegistry) + throws IOException; + + /** + * Reads and returns the next field of type {@code MESSAGE} and advances the reader to the next + * field. + */ + T readMessage(Class clazz, ExtensionRegistryLite extensionRegistry) throws IOException; + + /** + * Reads and returns the next field of type {@code GROUP} and advances the reader to the next + * field. + * + * @deprecated groups fields are deprecated. + */ + @Deprecated + T readGroup(Class clazz, ExtensionRegistryLite extensionRegistry) throws IOException; + + // TODO(yilunchong): the lack of other opinions for whether to expose this on the interface + @Deprecated + T readGroupBySchemaWithCheck(Schema schema, ExtensionRegistryLite extensionRegistry) + throws IOException; + + /** + * Reads and returns the next field of type {@code BYTES} and advances the reader to the next + * field. + */ + ByteString readBytes() throws IOException; + + /** + * Reads and returns the next field of type {@code UINT32} and advances the reader to the next + * field. + */ + int readUInt32() throws IOException; + + /** + * Reads and returns the next field of type {@code ENUM} and advances the reader to the next + * field. + */ + int readEnum() throws IOException; + + /** + * Reads and returns the next field of type {@code SFIXED32} and advances the reader to the next + * field. + */ + int readSFixed32() throws IOException; + + /** + * Reads and returns the next field of type {@code SFIXED64} and advances the reader to the next + * field. + */ + long readSFixed64() throws IOException; + + /** + * Reads and returns the next field of type {@code SINT32} and advances the reader to the next + * field. + */ + int readSInt32() throws IOException; + + /** + * Reads and returns the next field of type {@code SINT64} and advances the reader to the next + * field. + */ + long readSInt64() throws IOException; + + /** + * Reads the next field of type {@code DOUBLE_LIST} or {@code DOUBLE_LIST_PACKED} and advances the + * reader to the next field. + * + * @param target the list that will receive the read values. + */ + void readDoubleList(List target) throws IOException; + + /** + * Reads the next field of type {@code FLOAT_LIST} or {@code FLOAT_LIST_PACKED} and advances the + * reader to the next field. + * + * @param target the list that will receive the read values. + */ + void readFloatList(List target) throws IOException; + + /** + * Reads the next field of type {@code UINT64_LIST} or {@code UINT64_LIST_PACKED} and advances the + * reader to the next field. + * + * @param target the list that will receive the read values. + */ + void readUInt64List(List target) throws IOException; + + /** + * Reads the next field of type {@code INT64_LIST} or {@code INT64_LIST_PACKED} and advances the + * reader to the next field. + * + * @param target the list that will receive the read values. + */ + void readInt64List(List target) throws IOException; + + /** + * Reads the next field of type {@code INT32_LIST} or {@code INT32_LIST_PACKED} and advances the + * reader to the next field. + * + * @param target the list that will receive the read values. + */ + void readInt32List(List target) throws IOException; + + /** + * Reads the next field of type {@code FIXED64_LIST} or {@code FIXED64_LIST_PACKED} and advances + * the reader to the next field. + * + * @param target the list that will receive the read values. + */ + void readFixed64List(List target) throws IOException; + + /** + * Reads the next field of type {@code FIXED32_LIST} or {@code FIXED32_LIST_PACKED} and advances + * the reader to the next field. + * + * @param target the list that will receive the read values. + */ + void readFixed32List(List target) throws IOException; + + /** + * Reads the next field of type {@code BOOL_LIST} or {@code BOOL_LIST_PACKED} and advances the + * reader to the next field. + * + * @param target the list that will receive the read values. + */ + void readBoolList(List target) throws IOException; + + /** + * Reads the next field of type {@code STRING_LIST} and advances the reader to the next field. + * + * @param target the list that will receive the read values. + */ + void readStringList(List target) throws IOException; + + /** + * Reads the next field of type {@code STRING_LIST} and advances the reader to the next field. If + * the stream contains malformed UTF-8, throw exception {@link InvalidProtocolBufferException}. + * + * @param target the list that will receive the read values. + */ + void readStringListRequireUtf8(List target) throws IOException; + + /** + * Reads the next field of type {@code MESSAGE_LIST} and advances the reader to the next field. + * + * @param target the list that will receive the read values. + * @param targetType the type of the elements stored in the {@code target} list. + */ + void readMessageList( + List target, Schema schema, ExtensionRegistryLite extensionRegistry) throws IOException; + + void readMessageList( + List target, Class targetType, ExtensionRegistryLite extensionRegistry) + throws IOException; + + /** + * Reads the next field of type {@code GROUP_LIST} and advances the reader to the next field. + * + * @param target the list that will receive the read values. + * @param targetType the type of the elements stored in the {@code target} list. + * @deprecated groups fields are deprecated. + */ + @Deprecated + void readGroupList( + List target, Class targetType, ExtensionRegistryLite extensionRegistry) + throws IOException; + + @Deprecated + void readGroupList( + List target, Schema targetType, ExtensionRegistryLite extensionRegistry) + throws IOException; + + /** + * Reads the next field of type {@code BYTES_LIST} and advances the reader to the next field. + * + * @param target the list that will receive the read values. + */ + void readBytesList(List target) throws IOException; + + /** + * Reads the next field of type {@code UINT32_LIST} or {@code UINT32_LIST_PACKED} and advances the + * reader to the next field. + * + * @param target the list that will receive the read values. + */ + void readUInt32List(List target) throws IOException; + + /** + * Reads the next field of type {@code ENUM_LIST} or {@code ENUM_LIST_PACKED} and advances the + * reader to the next field. + * + * @param target the list that will receive the read values. + */ + void readEnumList(List target) throws IOException; + + /** + * Reads the next field of type {@code SFIXED32_LIST} or {@code SFIXED32_LIST_PACKED} and advances + * the reader to the next field. + * + * @param target the list that will receive the read values. + */ + void readSFixed32List(List target) throws IOException; + + /** + * Reads the next field of type {@code SFIXED64_LIST} or {@code SFIXED64_LIST_PACKED} and advances + * the reader to the next field. + * + * @param target the list that will receive the read values. + */ + void readSFixed64List(List target) throws IOException; + + /** + * Reads the next field of type {@code SINT32_LIST} or {@code SINT32_LIST_PACKED} and advances the + * reader to the next field. + * + * @param target the list that will receive the read values. + */ + void readSInt32List(List target) throws IOException; + + /** + * Reads the next field of type {@code SINT64_LIST} or {@code SINT64_LIST_PACKED} and advances the + * reader to the next field. + * + * @param target the list that will receive the read values. + */ + void readSInt64List(List target) throws IOException; + + /** + * Reads the next field of type {@code MAP} and advances the reader to the next field. + * + * @param target the mutable map that will receive the read values. + * @param mapDefaultEntry the default entry of the map field. + * @param extensionRegistry the extension registry for parsing message value fields. + */ + void readMap( + Map target, + MapEntryLite.Metadata mapDefaultEntry, + ExtensionRegistryLite extensionRegistry) + throws IOException; +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/SchemaFactory.java b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/SchemaFactory.java new file mode 100644 index 0000000..cf38dd6 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/SchemaFactory.java @@ -0,0 +1,38 @@ +// 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. + +package com.google.protobuf; + +/** A factory that manufactures {@link Schema} instances for protobuf messages. */ +@ExperimentalApi +interface SchemaFactory { + /** Creates a schema instance for the given protobuf message type. */ + Schema createSchema(Class messageType); +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/TextFormatParseLocation.java b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/TextFormatParseLocation.java new file mode 100644 index 0000000..eebfb1b --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/TextFormatParseLocation.java @@ -0,0 +1,101 @@ +// 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. + +package com.google.protobuf; + +import java.util.Arrays; + +/** + * A location in the source code. + * + *

A location is the starting line number and starting column number. + */ +public final class TextFormatParseLocation { + + /** The empty location. */ + public static final TextFormatParseLocation EMPTY = new TextFormatParseLocation(-1, -1); + + /** + * Create a location. + * + * @param line the starting line number + * @param column the starting column number + * @return a {@code ParseLocation} + */ + static TextFormatParseLocation create(int line, int column) { + if (line == -1 && column == -1) { + return EMPTY; + } + if (line < 0 || column < 0) { + throw new IllegalArgumentException( + String.format("line and column values must be >= 0: line %d, column: %d", line, column)); + } + return new TextFormatParseLocation(line, column); + } + + private final int line; + private final int column; + + private TextFormatParseLocation(int line, int column) { + this.line = line; + this.column = column; + } + + public int getLine() { + return line; + } + + public int getColumn() { + return column; + } + + @Override + public String toString() { + return String.format("ParseLocation{line=%d, column=%d}", line, column); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof TextFormatParseLocation)) { + return false; + } + TextFormatParseLocation that = (TextFormatParseLocation) o; + return (this.line == that.getLine()) && (this.column == that.getColumn()); + } + + @Override + public int hashCode() { + int[] values = {line, column}; + return Arrays.hashCode(values); + } +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLiteSchema.java b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLiteSchema.java new file mode 100644 index 0000000..ffd7232 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLiteSchema.java @@ -0,0 +1,140 @@ +// 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. + +package com.google.protobuf; + +import java.io.IOException; + +class UnknownFieldSetLiteSchema + extends UnknownFieldSchema { + + UnknownFieldSetLiteSchema() {} + + @Override + boolean shouldDiscardUnknownFields(Reader reader) { + // We never drop unknown fields in lite. + return false; + } + + @Override + UnknownFieldSetLite newBuilder() { + return UnknownFieldSetLite.newInstance(); + } + + @Override + void addVarint(UnknownFieldSetLite fields, int number, long value) { + fields.storeField(WireFormat.makeTag(number, WireFormat.WIRETYPE_VARINT), value); + } + + @Override + void addFixed32(UnknownFieldSetLite fields, int number, int value) { + fields.storeField(WireFormat.makeTag(number, WireFormat.WIRETYPE_FIXED32), value); + } + + @Override + void addFixed64(UnknownFieldSetLite fields, int number, long value) { + fields.storeField(WireFormat.makeTag(number, WireFormat.WIRETYPE_FIXED64), value); + } + + @Override + void addLengthDelimited(UnknownFieldSetLite fields, int number, ByteString value) { + fields.storeField(WireFormat.makeTag(number, WireFormat.WIRETYPE_LENGTH_DELIMITED), value); + } + + @Override + void addGroup(UnknownFieldSetLite fields, int number, UnknownFieldSetLite subFieldSet) { + fields.storeField(WireFormat.makeTag(number, WireFormat.WIRETYPE_START_GROUP), subFieldSet); + } + + @Override + UnknownFieldSetLite toImmutable(UnknownFieldSetLite fields) { + fields.makeImmutable(); + return fields; + } + + @Override + void setToMessage(Object message, UnknownFieldSetLite fields) { + ((GeneratedMessageLite) message).unknownFields = fields; + } + + @Override + UnknownFieldSetLite getFromMessage(Object message) { + return ((GeneratedMessageLite) message).unknownFields; + } + + @Override + UnknownFieldSetLite getBuilderFromMessage(Object message) { + UnknownFieldSetLite unknownFields = getFromMessage(message); + // When parsing into a lite message object, its UnknownFieldSet is either the default instance + // or mutable. It can't be in a state where it's immutable but not default instance. + if (unknownFields == UnknownFieldSetLite.getDefaultInstance()) { + unknownFields = UnknownFieldSetLite.newInstance(); + setToMessage(message, unknownFields); + } + return unknownFields; + } + + @Override + void setBuilderToMessage(Object message, UnknownFieldSetLite fields) { + setToMessage(message, fields); + } + + @Override + void makeImmutable(Object message) { + getFromMessage(message).makeImmutable(); + } + + @Override + void writeTo(UnknownFieldSetLite fields, Writer writer) throws IOException { + fields.writeTo(writer); + } + + @Override + void writeAsMessageSetTo(UnknownFieldSetLite fields, Writer writer) throws IOException { + fields.writeAsMessageSetTo(writer); + } + + @Override + UnknownFieldSetLite merge(UnknownFieldSetLite message, UnknownFieldSetLite other) { + return other.equals(UnknownFieldSetLite.getDefaultInstance()) + ? message + : UnknownFieldSetLite.mutableCopyOf(message, other); + } + + @Override + int getSerializedSize(UnknownFieldSetLite unknowns) { + return unknowns.getSerializedSize(); + } + + @Override + int getSerializedSizeAsMessageSet(UnknownFieldSetLite unknowns) { + return unknowns.getSerializedSizeAsMessageSet(); + } +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/UnsafeByteOperations.java b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/UnsafeByteOperations.java new file mode 100644 index 0000000..bcaf1d2 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/UnsafeByteOperations.java @@ -0,0 +1,121 @@ +// 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. + +package com.google.protobuf; + +import java.io.IOException; +import java.nio.ByteBuffer; + +/** + * Provides a number of unsafe byte operations to be used by advanced applications with high + * performance requirements. These methods are referred to as "unsafe" due to the fact that they + * potentially expose the backing buffer of a {@link ByteString} to the application. + * + *

DISCLAIMER: The methods in this class should only be called if it is + * guaranteed that the buffer backing the {@link ByteString} will never change! Mutation of a {@link + * ByteString} can lead to unexpected and undesirable consequences in your application, and will + * likely be difficult to debug. Proceed with caution! + * + *

This can have a number of significant side affects that have spooky-action-at-a-distance-like + * behavior. In particular, if the bytes value changes out from under a Protocol Buffer: + * + *

    + *
  • serialization may throw + *
  • serialization may succeed but the wrong bytes may be written out + *
  • messages are no longer threadsafe + *
  • hashCode may be incorrect + *
      + *
    • can result in a permanent memory leak when used as a key in a long-lived HashMap + *
    • the semantics of many programs may be violated if this is the case + *
    + *
+ * + * Each of these issues will occur in parts of the code base that are entirely distinct from the + * parts of the code base modifying the buffer. In fact, both parts of the code base may be correct + * - it is the bridging with the unsafe operations that was in error! + */ +@ExperimentalApi +public final class UnsafeByteOperations { + private UnsafeByteOperations() {} + + /** + * An unsafe operation that returns a {@link ByteString} that is backed by the provided buffer. + * + * @param buffer the buffer to be wrapped + * @return a {@link ByteString} backed by the provided buffer + */ + public static ByteString unsafeWrap(byte[] buffer) { + return ByteString.wrap(buffer); + } + + /** + * An unsafe operation that returns a {@link ByteString} that is backed by a subregion of the + * provided buffer. + * + * @param buffer the buffer to be wrapped + * @param offset the offset of the wrapped region + * @param length the number of bytes of the wrapped region + * @return a {@link ByteString} backed by the provided buffer + */ + public static ByteString unsafeWrap(byte[] buffer, int offset, int length) { + return ByteString.wrap(buffer, offset, length); + } + + /** + * An unsafe operation that returns a {@link ByteString} that is backed by the provided buffer. + * + * @param buffer the Java NIO buffer to be wrapped + * @return a {@link ByteString} backed by the provided buffer + */ + public static ByteString unsafeWrap(ByteBuffer buffer) { + return ByteString.wrap(buffer); + } + + /** + * Writes the given {@link ByteString} to the provided {@link ByteOutput}. Calling this method may + * result in multiple operations on the target {@link ByteOutput} (i.e. for roped {@link + * ByteString}s). + * + *

This method exposes the internal backing buffer(s) of the {@link ByteString} to the {@link + * ByteOutput} in order to avoid additional copying overhead. It would be possible for a malicious + * {@link ByteOutput} to corrupt the {@link ByteString}. Use with caution! + * + *

NOTE: The {@link ByteOutput} MUST NOT modify the provided buffers. Doing so + * may result in corrupted data, which would be difficult to debug. + * + * @param bytes the {@link ByteString} to be written + * @param output the output to receive the bytes + * @throws IOException if an I/O error occurs + */ + public static void unsafeWriteTo(ByteString bytes, ByteOutput output) throws IOException { + bytes.writeTo(output); + } + +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java new file mode 100644 index 0000000..dd459f0 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java @@ -0,0 +1,1036 @@ +// 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. + +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; +import java.util.logging.Logger; + +/** Utility class for working with unsafe operations. */ +final class UnsafeUtil { + private static final sun.misc.Unsafe UNSAFE = getUnsafe(); + private static final Class MEMORY_CLASS = Android.getMemoryClass(); + private static final boolean IS_ANDROID_64 = determineAndroidSupportByAddressSize(long.class); + private static final boolean IS_ANDROID_32 = determineAndroidSupportByAddressSize(int.class); + private static final MemoryAccessor MEMORY_ACCESSOR = getMemoryAccessor(); + private static final boolean HAS_UNSAFE_BYTEBUFFER_OPERATIONS = + supportsUnsafeByteBufferOperations(); + private static final boolean HAS_UNSAFE_ARRAY_OPERATIONS = supportsUnsafeArrayOperations(); + + static final long BYTE_ARRAY_BASE_OFFSET = arrayBaseOffset(byte[].class); + // Micro-optimization: we can assume a scale of 1 and skip the multiply + // private static final long BYTE_ARRAY_INDEX_SCALE = 1; + + private static final long BOOLEAN_ARRAY_BASE_OFFSET = arrayBaseOffset(boolean[].class); + private static final long BOOLEAN_ARRAY_INDEX_SCALE = arrayIndexScale(boolean[].class); + + private static final long INT_ARRAY_BASE_OFFSET = arrayBaseOffset(int[].class); + private static final long INT_ARRAY_INDEX_SCALE = arrayIndexScale(int[].class); + + private static final long LONG_ARRAY_BASE_OFFSET = arrayBaseOffset(long[].class); + private static final long LONG_ARRAY_INDEX_SCALE = arrayIndexScale(long[].class); + + private static final long FLOAT_ARRAY_BASE_OFFSET = arrayBaseOffset(float[].class); + private static final long FLOAT_ARRAY_INDEX_SCALE = arrayIndexScale(float[].class); + + private static final long DOUBLE_ARRAY_BASE_OFFSET = arrayBaseOffset(double[].class); + private static final long DOUBLE_ARRAY_INDEX_SCALE = arrayIndexScale(double[].class); + + private static final long OBJECT_ARRAY_BASE_OFFSET = arrayBaseOffset(Object[].class); + private static final long OBJECT_ARRAY_INDEX_SCALE = arrayIndexScale(Object[].class); + + private static final long BUFFER_ADDRESS_OFFSET = fieldOffset(bufferAddressField()); + + private static final int STRIDE = 8; + private static final int STRIDE_ALIGNMENT_MASK = STRIDE - 1; + private static final int BYTE_ARRAY_ALIGNMENT = + (int) (BYTE_ARRAY_BASE_OFFSET & STRIDE_ALIGNMENT_MASK); + + static final boolean IS_BIG_ENDIAN = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN; + + private UnsafeUtil() {} + + static boolean hasUnsafeArrayOperations() { + return HAS_UNSAFE_ARRAY_OPERATIONS; + } + + static boolean hasUnsafeByteBufferOperations() { + return HAS_UNSAFE_BYTEBUFFER_OPERATIONS; + } + + static boolean isAndroid64() { + return IS_ANDROID_64; + } + + @SuppressWarnings("unchecked") // safe by method contract + static T allocateInstance(Class clazz) { + try { + return (T) UNSAFE.allocateInstance(clazz); + } catch (InstantiationException e) { + throw new IllegalStateException(e); + } + } + + static long objectFieldOffset(Field field) { + return MEMORY_ACCESSOR.objectFieldOffset(field); + } + + private static int arrayBaseOffset(Class clazz) { + return HAS_UNSAFE_ARRAY_OPERATIONS ? MEMORY_ACCESSOR.arrayBaseOffset(clazz) : -1; + } + + private static int arrayIndexScale(Class clazz) { + return HAS_UNSAFE_ARRAY_OPERATIONS ? MEMORY_ACCESSOR.arrayIndexScale(clazz) : -1; + } + + static byte getByte(Object target, long offset) { + return MEMORY_ACCESSOR.getByte(target, offset); + } + + static void putByte(Object target, long offset, byte value) { + MEMORY_ACCESSOR.putByte(target, offset, value); + } + + static int getInt(Object target, long offset) { + return MEMORY_ACCESSOR.getInt(target, offset); + } + + static void putInt(Object target, long offset, int value) { + MEMORY_ACCESSOR.putInt(target, offset, value); + } + + static long getLong(Object target, long offset) { + return MEMORY_ACCESSOR.getLong(target, offset); + } + + static void putLong(Object target, long offset, long value) { + MEMORY_ACCESSOR.putLong(target, offset, value); + } + + static boolean getBoolean(Object target, long offset) { + return MEMORY_ACCESSOR.getBoolean(target, offset); + } + + static void putBoolean(Object target, long offset, boolean value) { + MEMORY_ACCESSOR.putBoolean(target, offset, value); + } + + static float getFloat(Object target, long offset) { + return MEMORY_ACCESSOR.getFloat(target, offset); + } + + static void putFloat(Object target, long offset, float value) { + MEMORY_ACCESSOR.putFloat(target, offset, value); + } + + static double getDouble(Object target, long offset) { + return MEMORY_ACCESSOR.getDouble(target, offset); + } + + static void putDouble(Object target, long offset, double value) { + MEMORY_ACCESSOR.putDouble(target, offset, value); + } + + static Object getObject(Object target, long offset) { + return MEMORY_ACCESSOR.getObject(target, offset); + } + + static void putObject(Object target, long offset, Object value) { + MEMORY_ACCESSOR.putObject(target, offset, value); + } + + static byte getByte(byte[] target, long index) { + return MEMORY_ACCESSOR.getByte(target, BYTE_ARRAY_BASE_OFFSET + index); + } + + static void putByte(byte[] target, long index, byte value) { + MEMORY_ACCESSOR.putByte(target, BYTE_ARRAY_BASE_OFFSET + index, value); + } + + static int getInt(int[] target, long index) { + return MEMORY_ACCESSOR.getInt(target, INT_ARRAY_BASE_OFFSET + (index * INT_ARRAY_INDEX_SCALE)); + } + + static void putInt(int[] target, long index, int value) { + MEMORY_ACCESSOR.putInt(target, INT_ARRAY_BASE_OFFSET + (index * INT_ARRAY_INDEX_SCALE), value); + } + + static long getLong(long[] target, long index) { + return MEMORY_ACCESSOR.getLong( + target, LONG_ARRAY_BASE_OFFSET + (index * LONG_ARRAY_INDEX_SCALE)); + } + + static void putLong(long[] target, long index, long value) { + MEMORY_ACCESSOR.putLong( + target, LONG_ARRAY_BASE_OFFSET + (index * LONG_ARRAY_INDEX_SCALE), value); + } + + static boolean getBoolean(boolean[] target, long index) { + return MEMORY_ACCESSOR.getBoolean( + target, BOOLEAN_ARRAY_BASE_OFFSET + (index * BOOLEAN_ARRAY_INDEX_SCALE)); + } + + static void putBoolean(boolean[] target, long index, boolean value) { + MEMORY_ACCESSOR.putBoolean( + target, BOOLEAN_ARRAY_BASE_OFFSET + (index * BOOLEAN_ARRAY_INDEX_SCALE), value); + } + + static float getFloat(float[] target, long index) { + return MEMORY_ACCESSOR.getFloat( + target, FLOAT_ARRAY_BASE_OFFSET + (index * FLOAT_ARRAY_INDEX_SCALE)); + } + + static void putFloat(float[] target, long index, float value) { + MEMORY_ACCESSOR.putFloat( + target, FLOAT_ARRAY_BASE_OFFSET + (index * FLOAT_ARRAY_INDEX_SCALE), value); + } + + static double getDouble(double[] target, long index) { + return MEMORY_ACCESSOR.getDouble( + target, DOUBLE_ARRAY_BASE_OFFSET + (index * DOUBLE_ARRAY_INDEX_SCALE)); + } + + static void putDouble(double[] target, long index, double value) { + MEMORY_ACCESSOR.putDouble( + target, DOUBLE_ARRAY_BASE_OFFSET + (index * DOUBLE_ARRAY_INDEX_SCALE), value); + } + + static Object getObject(Object[] target, long index) { + return MEMORY_ACCESSOR.getObject( + target, OBJECT_ARRAY_BASE_OFFSET + (index * OBJECT_ARRAY_INDEX_SCALE)); + } + + static void putObject(Object[] target, long index, Object value) { + MEMORY_ACCESSOR.putObject( + target, OBJECT_ARRAY_BASE_OFFSET + (index * OBJECT_ARRAY_INDEX_SCALE), value); + } + + static void copyMemory(byte[] src, long srcIndex, long targetOffset, long length) { + MEMORY_ACCESSOR.copyMemory(src, srcIndex, targetOffset, length); + } + + static void copyMemory(long srcOffset, byte[] target, long targetIndex, long length) { + MEMORY_ACCESSOR.copyMemory(srcOffset, target, targetIndex, length); + } + + static void copyMemory(byte[] src, long srcIndex, byte[] target, long targetIndex, long length) { + System.arraycopy(src, (int) srcIndex, target, (int) targetIndex, (int) length); + } + + static byte getByte(long address) { + return MEMORY_ACCESSOR.getByte(address); + } + + static void putByte(long address, byte value) { + MEMORY_ACCESSOR.putByte(address, value); + } + + static int getInt(long address) { + return MEMORY_ACCESSOR.getInt(address); + } + + static void putInt(long address, int value) { + MEMORY_ACCESSOR.putInt(address, value); + } + + static long getLong(long address) { + return MEMORY_ACCESSOR.getLong(address); + } + + static void putLong(long address, long value) { + MEMORY_ACCESSOR.putLong(address, value); + } + + /** Gets the offset of the {@code address} field of the given direct {@link ByteBuffer}. */ + static long addressOffset(ByteBuffer buffer) { + return MEMORY_ACCESSOR.getLong(buffer, BUFFER_ADDRESS_OFFSET); + } + + static Object getStaticObject(Field field) { + return MEMORY_ACCESSOR.getStaticObject(field); + } + + /** + * Gets the {@code sun.misc.Unsafe} instance, or {@code null} if not available on this platform. + */ + static sun.misc.Unsafe getUnsafe() { + sun.misc.Unsafe unsafe = null; + try { + unsafe = + AccessController.doPrivileged( + new PrivilegedExceptionAction() { + @Override + public sun.misc.Unsafe run() throws Exception { + Class k = sun.misc.Unsafe.class; + + for (Field f : k.getDeclaredFields()) { + f.setAccessible(true); + Object x = f.get(null); + if (k.isInstance(x)) { + return k.cast(x); + } + } + // The sun.misc.Unsafe field does not exist. + return null; + } + }); + } catch (Throwable e) { + // Catching Throwable here due to the fact that Google AppEngine raises NoClassDefFoundError + // for Unsafe. + } + return unsafe; + } + + /** Get a {@link MemoryAccessor} appropriate for the platform, or null if not supported. */ + private static MemoryAccessor getMemoryAccessor() { + if (UNSAFE == null) { + return null; + } + if (Android.isOnAndroidDevice()) { + if (IS_ANDROID_64) { + return new Android64MemoryAccessor(UNSAFE); + } else if (IS_ANDROID_32) { + return new Android32MemoryAccessor(UNSAFE); + } else { + return null; + } + } + + return new JvmMemoryAccessor(UNSAFE); + } + + private static boolean supportsUnsafeArrayOperations() { + if (MEMORY_ACCESSOR == null) { + return false; + } + return MEMORY_ACCESSOR.supportsUnsafeArrayOperations(); + } + + private static boolean supportsUnsafeByteBufferOperations() { + if (MEMORY_ACCESSOR == null) { + return false; + } + return MEMORY_ACCESSOR.supportsUnsafeByteBufferOperations(); + } + + static boolean determineAndroidSupportByAddressSize(Class addressClass) { + if (!Android.isOnAndroidDevice()) { + return false; + } + try { + Class clazz = MEMORY_CLASS; + clazz.getMethod("peekLong", addressClass, boolean.class); + clazz.getMethod("pokeLong", addressClass, long.class, boolean.class); + clazz.getMethod("pokeInt", addressClass, int.class, boolean.class); + clazz.getMethod("peekInt", addressClass, boolean.class); + clazz.getMethod("pokeByte", addressClass, byte.class); + clazz.getMethod("peekByte", addressClass); + clazz.getMethod("pokeByteArray", addressClass, byte[].class, int.class, int.class); + clazz.getMethod("peekByteArray", addressClass, byte[].class, int.class, int.class); + return true; + } catch (Throwable t) { + return false; + } + } + + /** Finds the address field within a direct {@link Buffer}. */ + private static Field bufferAddressField() { + if (Android.isOnAndroidDevice()) { + // Old versions of Android had renamed the address field to 'effectiveDirectAddress', but + // recent versions of Android (>M?) use the OpenJDK implementation. Fall through in that case. + Field field = field(Buffer.class, "effectiveDirectAddress"); + if (field != null) { + return field; + } + } + Field field = field(Buffer.class, "address"); + return field != null && field.getType() == long.class ? field : null; + } + + /** + * Returns the index of the first byte where left and right differ, in the range [0, 8]. If {@code + * left == right}, the result will be 8, otherwise less than 8. + * + *

This counts from the *first* byte, which may be the most or least significant byte depending + * on the system endianness. + */ + private static int firstDifferingByteIndexNativeEndian(long left, long right) { + int n = + IS_BIG_ENDIAN + ? Long.numberOfLeadingZeros(left ^ right) + : Long.numberOfTrailingZeros(left ^ right); + return n >> 3; + } + + /** + * Returns the lowest {@code index} such that {@code 0 <= index < length} and {@code left[leftOff + * + index] != right[rightOff + index]}. If no such value exists -- if {@code left} and {@code + * right} match up to {@code length} bytes from their respective offsets -- returns -1. + * + *

{@code leftOff + length} must be less than or equal to {@code left.length}, and the same for + * {@code right}. + */ + static int mismatch(byte[] left, int leftOff, byte[] right, int rightOff, int length) { + if (leftOff < 0 + || rightOff < 0 + || length < 0 + || leftOff + length > left.length + || rightOff + length > right.length) { + throw new IndexOutOfBoundsException(); + } + + int index = 0; + if (HAS_UNSAFE_ARRAY_OPERATIONS) { + int leftAlignment = (BYTE_ARRAY_ALIGNMENT + leftOff) & STRIDE_ALIGNMENT_MASK; + + // Most CPUs handle getting chunks of bytes better on addresses that are a multiple of 4 + // or 8. + // We walk one byte at a time until the left address, at least, is a multiple of 8. + // If the right address is, too, so much the better. + for (; + index < length && (leftAlignment & STRIDE_ALIGNMENT_MASK) != 0; + index++, leftAlignment++) { + if (left[leftOff + index] != right[rightOff + index]) { + return index; + } + } + + // Stride! Grab eight bytes at a time from left and right and check them for equality. + + int strideLength = ((length - index) & ~STRIDE_ALIGNMENT_MASK) + index; + // strideLength is the point where we want to stop striding: it differs from index by + // a multiple of STRIDE, and it's the largest such number <= length. + + for (; index < strideLength; index += STRIDE) { + long leftLongWord = getLong(left, BYTE_ARRAY_BASE_OFFSET + leftOff + index); + long rightLongWord = getLong(right, BYTE_ARRAY_BASE_OFFSET + rightOff + index); + if (leftLongWord != rightLongWord) { + // one of these eight bytes differ! use a helper to find out which one + return index + firstDifferingByteIndexNativeEndian(leftLongWord, rightLongWord); + } + } + } + + // If we were able to stride, there are at most STRIDE - 1 bytes left to compare. + // If we weren't, then this loop covers the whole thing. + for (; index < length; index++) { + if (left[leftOff + index] != right[rightOff + index]) { + return index; + } + } + return -1; + } + + /** + * Returns the offset of the provided field, or {@code -1} if {@code sun.misc.Unsafe} is not + * available. + */ + private static long fieldOffset(Field field) { + return field == null || MEMORY_ACCESSOR == null ? -1 : MEMORY_ACCESSOR.objectFieldOffset(field); + } + + /** + * Gets the field with the given name within the class, or {@code null} if not found. + */ + private static Field field(Class clazz, String fieldName) { + Field field; + try { + field = clazz.getDeclaredField(fieldName); + } catch (Throwable t) { + // Failed to access the fields. + field = null; + } + return field; + } + + private abstract static class MemoryAccessor { + + sun.misc.Unsafe unsafe; + + MemoryAccessor(sun.misc.Unsafe unsafe) { + this.unsafe = unsafe; + } + + public final long objectFieldOffset(Field field) { + return unsafe.objectFieldOffset(field); + } + + public final int arrayBaseOffset(Class clazz) { + return unsafe.arrayBaseOffset(clazz); + } + + public final int arrayIndexScale(Class clazz) { + return unsafe.arrayIndexScale(clazz); + } + + public abstract Object getStaticObject(Field field); + + // Relative Address Operations --------------------------------------------- + + // Indicates whether the following relative address operations are supported + // by this memory accessor. + public boolean supportsUnsafeArrayOperations() { + if (unsafe == null) { + return false; + } + try { + Class clazz = unsafe.getClass(); + clazz.getMethod("objectFieldOffset", Field.class); + clazz.getMethod("arrayBaseOffset", Class.class); + clazz.getMethod("arrayIndexScale", Class.class); + clazz.getMethod("getInt", Object.class, long.class); + clazz.getMethod("putInt", Object.class, long.class, int.class); + clazz.getMethod("getLong", Object.class, long.class); + clazz.getMethod("putLong", Object.class, long.class, long.class); + clazz.getMethod("getObject", Object.class, long.class); + clazz.getMethod("putObject", Object.class, long.class, Object.class); + + return true; + } catch (Throwable e) { + logMissingMethod(e); + } + return false; + } + + public abstract byte getByte(Object target, long offset); + + public abstract void putByte(Object target, long offset, byte value); + + public final int getInt(Object target, long offset) { + return unsafe.getInt(target, offset); + } + + public final void putInt(Object target, long offset, int value) { + unsafe.putInt(target, offset, value); + } + + public final long getLong(Object target, long offset) { + return unsafe.getLong(target, offset); + } + + public final void putLong(Object target, long offset, long value) { + unsafe.putLong(target, offset, value); + } + + public abstract boolean getBoolean(Object target, long offset); + + public abstract void putBoolean(Object target, long offset, boolean value); + + public abstract float getFloat(Object target, long offset); + + public abstract void putFloat(Object target, long offset, float value); + + public abstract double getDouble(Object target, long offset); + + public abstract void putDouble(Object target, long offset, double value); + + public final Object getObject(Object target, long offset) { + return unsafe.getObject(target, offset); + } + + public final void putObject(Object target, long offset, Object value) { + unsafe.putObject(target, offset, value); + } + + // Absolute Address Operations -------------------------------------------- + + // Indicates whether the following absolute address operations are + // supported by this memory accessor. + public boolean supportsUnsafeByteBufferOperations() { + if (unsafe == null) { + return false; + } + try { + Class clazz = unsafe.getClass(); + // Methods for getting direct buffer address. + clazz.getMethod("objectFieldOffset", Field.class); + clazz.getMethod("getLong", Object.class, long.class); + + if (bufferAddressField() == null) { + return false; + } + + return true; + } catch (Throwable e) { + logMissingMethod(e); + } + return false; + } + + public abstract byte getByte(long address); + + public abstract void putByte(long address, byte value); + + public abstract int getInt(long address); + + public abstract void putInt(long address, int value); + + public abstract long getLong(long address); + + public abstract void putLong(long address, long value); + + public abstract void copyMemory(long srcOffset, byte[] target, long targetIndex, long length); + + public abstract void copyMemory(byte[] src, long srcIndex, long targetOffset, long length); + } + + private static final class JvmMemoryAccessor extends MemoryAccessor { + + JvmMemoryAccessor(sun.misc.Unsafe unsafe) { + super(unsafe); + } + + @Override + public Object getStaticObject(Field field) { + return getObject(unsafe.staticFieldBase(field), unsafe.staticFieldOffset(field)); + } + + @Override + public boolean supportsUnsafeArrayOperations() { + if (!super.supportsUnsafeArrayOperations()) { + return false; + } + + try { + Class clazz = unsafe.getClass(); + clazz.getMethod("getByte", Object.class, long.class); + clazz.getMethod("putByte", Object.class, long.class, byte.class); + clazz.getMethod("getBoolean", Object.class, long.class); + clazz.getMethod("putBoolean", Object.class, long.class, boolean.class); + clazz.getMethod("getFloat", Object.class, long.class); + clazz.getMethod("putFloat", Object.class, long.class, float.class); + clazz.getMethod("getDouble", Object.class, long.class); + clazz.getMethod("putDouble", Object.class, long.class, double.class); + + return true; + } catch (Throwable e) { + logMissingMethod(e); + } + return false; + } + + @Override + public byte getByte(Object target, long offset) { + return unsafe.getByte(target, offset); + } + + @Override + public void putByte(Object target, long offset, byte value) { + unsafe.putByte(target, offset, value); + } + + @Override + public boolean getBoolean(Object target, long offset) { + return unsafe.getBoolean(target, offset); + } + + @Override + public void putBoolean(Object target, long offset, boolean value) { + unsafe.putBoolean(target, offset, value); + } + + @Override + public float getFloat(Object target, long offset) { + return unsafe.getFloat(target, offset); + } + + @Override + public void putFloat(Object target, long offset, float value) { + unsafe.putFloat(target, offset, value); + } + + @Override + public double getDouble(Object target, long offset) { + return unsafe.getDouble(target, offset); + } + + @Override + public void putDouble(Object target, long offset, double value) { + unsafe.putDouble(target, offset, value); + } + + @Override + public boolean supportsUnsafeByteBufferOperations() { + if (!super.supportsUnsafeByteBufferOperations()) { + return false; + } + + try { + Class clazz = unsafe.getClass(); + clazz.getMethod("getByte", long.class); + clazz.getMethod("putByte", long.class, byte.class); + clazz.getMethod("getInt", long.class); + clazz.getMethod("putInt", long.class, int.class); + clazz.getMethod("getLong", long.class); + clazz.getMethod("putLong", long.class, long.class); + clazz.getMethod("copyMemory", long.class, long.class, long.class); + clazz.getMethod( + "copyMemory", Object.class, long.class, Object.class, long.class, long.class); + return true; + } catch (Throwable e) { + logMissingMethod(e); + } + return false; + } + + @Override + public byte getByte(long address) { + return unsafe.getByte(address); + } + + @Override + public void putByte(long address, byte value) { + unsafe.putByte(address, value); + } + + @Override + public int getInt(long address) { + return unsafe.getInt(address); + } + + @Override + public void putInt(long address, int value) { + unsafe.putInt(address, value); + } + + @Override + public long getLong(long address) { + return unsafe.getLong(address); + } + + @Override + public void putLong(long address, long value) { + unsafe.putLong(address, value); + } + + @Override + public void copyMemory(long srcOffset, byte[] target, long targetIndex, long length) { + unsafe.copyMemory(null, srcOffset, target, BYTE_ARRAY_BASE_OFFSET + targetIndex, length); + } + + @Override + public void copyMemory(byte[] src, long srcIndex, long targetOffset, long length) { + unsafe.copyMemory(src, BYTE_ARRAY_BASE_OFFSET + srcIndex, null, targetOffset, length); + } + } + + private static final class Android64MemoryAccessor extends MemoryAccessor { + + Android64MemoryAccessor(sun.misc.Unsafe unsafe) { + super(unsafe); + } + + @Override + public Object getStaticObject(Field field) { + try { + return field.get(null); + } catch (IllegalAccessException e) { + return null; + } + } + + @Override + public byte getByte(Object target, long offset) { + if (IS_BIG_ENDIAN) { + return getByteBigEndian(target, offset); + } else { + return getByteLittleEndian(target, offset); + } + } + + @Override + public void putByte(Object target, long offset, byte value) { + if (IS_BIG_ENDIAN) { + putByteBigEndian(target, offset, value); + } else { + putByteLittleEndian(target, offset, value); + } + } + + @Override + public boolean getBoolean(Object target, long offset) { + if (IS_BIG_ENDIAN) { + return getBooleanBigEndian(target, offset); + } else { + return getBooleanLittleEndian(target, offset); + } + } + + @Override + public void putBoolean(Object target, long offset, boolean value) { + if (IS_BIG_ENDIAN) { + putBooleanBigEndian(target, offset, value); + } else { + putBooleanLittleEndian(target, offset, value); + } + } + + @Override + public float getFloat(Object target, long offset) { + return Float.intBitsToFloat(getInt(target, offset)); + } + + @Override + public void putFloat(Object target, long offset, float value) { + putInt(target, offset, Float.floatToIntBits(value)); + } + + @Override + public double getDouble(Object target, long offset) { + return Double.longBitsToDouble(getLong(target, offset)); + } + + @Override + public void putDouble(Object target, long offset, double value) { + putLong(target, offset, Double.doubleToLongBits(value)); + } + + @Override + public boolean supportsUnsafeByteBufferOperations() { + return false; + } + + @Override + public byte getByte(long address) { + throw new UnsupportedOperationException(); + } + + @Override + public void putByte(long address, byte value) { + throw new UnsupportedOperationException(); + } + + @Override + public int getInt(long address) { + throw new UnsupportedOperationException(); + } + + @Override + public void putInt(long address, int value) { + throw new UnsupportedOperationException(); + } + + @Override + public long getLong(long address) { + throw new UnsupportedOperationException(); + } + + @Override + public void putLong(long address, long value) { + throw new UnsupportedOperationException(); + } + + @Override + public void copyMemory(long srcOffset, byte[] target, long targetIndex, long length) { + throw new UnsupportedOperationException(); + } + + @Override + public void copyMemory(byte[] src, long srcIndex, long targetOffset, long length) { + throw new UnsupportedOperationException(); + } + } + + private static final class Android32MemoryAccessor extends MemoryAccessor { + + /** Mask used to convert a 64 bit memory address to a 32 bit address. */ + private static final long SMALL_ADDRESS_MASK = 0x00000000FFFFFFFF; + + /** Truncate a {@code long} address into a short {@code int} address. */ + private static int smallAddress(long address) { + return (int) (SMALL_ADDRESS_MASK & address); + } + + Android32MemoryAccessor(sun.misc.Unsafe unsafe) { + super(unsafe); + } + + @Override + public Object getStaticObject(Field field) { + try { + return field.get(null); + } catch (IllegalAccessException e) { + return null; + } + } + + @Override + public byte getByte(Object target, long offset) { + if (IS_BIG_ENDIAN) { + return getByteBigEndian(target, offset); + } else { + return getByteLittleEndian(target, offset); + } + } + + @Override + public void putByte(Object target, long offset, byte value) { + if (IS_BIG_ENDIAN) { + putByteBigEndian(target, offset, value); + } else { + putByteLittleEndian(target, offset, value); + } + } + + @Override + public boolean getBoolean(Object target, long offset) { + if (IS_BIG_ENDIAN) { + return getBooleanBigEndian(target, offset); + } else { + return getBooleanLittleEndian(target, offset); + } + } + + @Override + public void putBoolean(Object target, long offset, boolean value) { + if (IS_BIG_ENDIAN) { + putBooleanBigEndian(target, offset, value); + } else { + putBooleanLittleEndian(target, offset, value); + } + } + + @Override + public float getFloat(Object target, long offset) { + return Float.intBitsToFloat(getInt(target, offset)); + } + + @Override + public void putFloat(Object target, long offset, float value) { + putInt(target, offset, Float.floatToIntBits(value)); + } + + @Override + public double getDouble(Object target, long offset) { + return Double.longBitsToDouble(getLong(target, offset)); + } + + @Override + public void putDouble(Object target, long offset, double value) { + putLong(target, offset, Double.doubleToLongBits(value)); + } + + @Override + public boolean supportsUnsafeByteBufferOperations() { + return false; + } + + @Override + public byte getByte(long address) { + throw new UnsupportedOperationException(); + } + + @Override + public void putByte(long address, byte value) { + throw new UnsupportedOperationException(); + } + + @Override + public int getInt(long address) { + throw new UnsupportedOperationException(); + } + + @Override + public void putInt(long address, int value) { + throw new UnsupportedOperationException(); + } + + @Override + public long getLong(long address) { + throw new UnsupportedOperationException(); + } + + @Override + public void putLong(long address, long value) { + throw new UnsupportedOperationException(); + } + + @Override + public void copyMemory(long srcOffset, byte[] target, long targetIndex, long length) { + throw new UnsupportedOperationException(); + } + + @Override + public void copyMemory(byte[] src, long srcIndex, long targetOffset, long length) { + throw new UnsupportedOperationException(); + } + } + + private static byte getByteBigEndian(Object target, long offset) { + return (byte) ((getInt(target, offset & ~3) >>> ((~offset & 3) << 3)) & 0xFF); + } + + private static byte getByteLittleEndian(Object target, long offset) { + return (byte) ((getInt(target, offset & ~3) >>> ((offset & 3) << 3)) & 0xFF); + } + + private static void putByteBigEndian(Object target, long offset, byte value) { + int intValue = getInt(target, offset & ~3); + int shift = ((~(int) offset) & 3) << 3; + int output = (intValue & ~(0xFF << shift)) | ((0xFF & value) << shift); + putInt(target, offset & ~3, output); + } + + private static void putByteLittleEndian(Object target, long offset, byte value) { + int intValue = getInt(target, offset & ~3); + int shift = (((int) offset) & 3) << 3; + int output = (intValue & ~(0xFF << shift)) | ((0xFF & value) << shift); + putInt(target, offset & ~3, output); + } + + private static boolean getBooleanBigEndian(Object target, long offset) { + return getByteBigEndian(target, offset) != 0; + } + + private static boolean getBooleanLittleEndian(Object target, long offset) { + return getByteLittleEndian(target, offset) != 0; + } + + private static void putBooleanBigEndian(Object target, long offset, boolean value) { + putByteBigEndian(target, offset, (byte) (value ? 1 : 0)); + } + + private static void putBooleanLittleEndian(Object target, long offset, boolean value) { + putByteLittleEndian(target, offset, (byte) (value ? 1 : 0)); + } + + private static void logMissingMethod(Throwable e) { + Logger.getLogger(UnsafeUtil.class.getName()) + .log( + Level.WARNING, + "platform method missing - proto runtime falling back to safer methods: " + e); + } +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java b/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java new file mode 100644 index 0000000..fac6949 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java @@ -0,0 +1,84 @@ +// 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. + +package com.google.protobuf; + +import static com.google.common.truth.Truth.assertWithMessage; + +import protobuf_unittest.UnittestProto.TestDeprecatedFields; +import java.lang.reflect.AnnotatedElement; +import java.lang.reflect.Method; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Test field deprecation. */ +@RunWith(JUnit4.class) +public class DeprecatedFieldTest { + private final String[] deprecatedGetterNames = {"hasDeprecatedInt32", "getDeprecatedInt32"}; + + private final String[] deprecatedBuilderGetterNames = { + "hasDeprecatedInt32", "getDeprecatedInt32", "clearDeprecatedInt32" + }; + + private final String[] deprecatedBuilderSetterNames = {"setDeprecatedInt32"}; + + @Test + public void testDeprecatedField() throws Exception { + Class deprecatedFields = TestDeprecatedFields.class; + Class deprecatedFieldsBuilder = TestDeprecatedFields.Builder.class; + for (String name : deprecatedGetterNames) { + Method method = deprecatedFields.getMethod(name); + assertWithMessage("Method %s should be deprecated", name).that(isDeprecated(method)).isTrue(); + } + for (String name : deprecatedBuilderGetterNames) { + Method method = deprecatedFieldsBuilder.getMethod(name); + assertWithMessage("Method %s should be deprecated", name).that(isDeprecated(method)).isTrue(); + } + for (String name : deprecatedBuilderSetterNames) { + Method method = deprecatedFieldsBuilder.getMethod(name, int.class); + assertWithMessage("Method %s should be deprecated", name).that(isDeprecated(method)).isTrue(); + } + } + + @Test + public void testDeprecatedFieldInOneof() throws Exception { + Class oneofCase = TestDeprecatedFields.OneofFieldsCase.class; + String name = "DEPRECATED_INT32_IN_ONEOF"; + java.lang.reflect.Field enumValue = oneofCase.getField(name); + assertWithMessage("Enum value %s should be deprecated.", name) + .that(isDeprecated(enumValue)) + .isTrue(); + } + + private boolean isDeprecated(AnnotatedElement annotated) { + return annotated.isAnnotationPresent(Deprecated.class); + } +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java b/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java new file mode 100644 index 0000000..8fe8508 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java @@ -0,0 +1,586 @@ +// 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. + +package com.google.protobuf; + +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; +import static java.util.Arrays.asList; + +import com.google.protobuf.Internal.FloatList; +import java.util.Collections; +import java.util.ConcurrentModificationException; +import java.util.Iterator; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for {@link FloatArrayList}. */ +@RunWith(JUnit4.class) +public class FloatArrayListTest { + + private static final FloatArrayList UNARY_LIST = newImmutableFloatArrayList(1); + private static final FloatArrayList TERTIARY_LIST = newImmutableFloatArrayList(1, 2, 3); + + private FloatArrayList list; + + @Before + public void setUp() throws Exception { + list = new FloatArrayList(); + } + + @Test + public void testEmptyListReturnsSameInstance() { + assertThat(FloatArrayList.emptyList()).isSameInstanceAs(FloatArrayList.emptyList()); + } + + @Test + public void testEmptyListIsImmutable() { + assertImmutable(FloatArrayList.emptyList()); + } + + @Test + public void testMakeImmutable() { + list.addFloat(3); + list.addFloat(4); + list.addFloat(5); + list.addFloat(7); + list.makeImmutable(); + assertImmutable(list); + } + + @Test + public void testModificationWithIteration() { + list.addAll(asList(1F, 2F, 3F, 4F)); + Iterator iterator = list.iterator(); + assertThat(list).hasSize(4); + assertThat((float) list.get(0)).isEqualTo(1F); + assertThat((float) iterator.next()).isEqualTo(1F); + list.set(0, 1F); + assertThat((float) iterator.next()).isEqualTo(2F); + + list.remove(0); + try { + iterator.next(); + assertWithMessage("expected exception").fail(); + } catch (ConcurrentModificationException e) { + // expected + } + + iterator = list.iterator(); + list.add(0, 0F); + try { + iterator.next(); + assertWithMessage("expected exception").fail(); + } catch (ConcurrentModificationException e) { + // expected + } + } + + @Test + public void testGet() { + assertThat((float) TERTIARY_LIST.get(0)).isEqualTo(1F); + assertThat((float) TERTIARY_LIST.get(1)).isEqualTo(2F); + assertThat((float) TERTIARY_LIST.get(2)).isEqualTo(3F); + + try { + TERTIARY_LIST.get(-1); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + TERTIARY_LIST.get(3); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + @Test + public void testGetFloat() { + assertThat(TERTIARY_LIST.getFloat(0)).isEqualTo(1F); + assertThat(TERTIARY_LIST.getFloat(1)).isEqualTo(2F); + assertThat(TERTIARY_LIST.getFloat(2)).isEqualTo(3F); + + try { + TERTIARY_LIST.get(-1); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + TERTIARY_LIST.get(3); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + @Test + public void testIndexOf_nullElement() { + assertThat(TERTIARY_LIST.indexOf(null)).isEqualTo(-1); + } + + @Test + public void testIndexOf_incompatibleElementType() { + assertThat(TERTIARY_LIST.indexOf(new Object())).isEqualTo(-1); + } + + @Test + public void testIndexOf_notInList() { + assertThat(UNARY_LIST.indexOf(2F)).isEqualTo(-1); + } + + @Test + public void testIndexOf_notInListWithDuplicates() { + FloatArrayList listWithDupes = newImmutableFloatArrayList(1F, 1F); + assertThat(listWithDupes.indexOf(2F)).isEqualTo(-1); + } + + @Test + public void testIndexOf_inList() { + assertThat(TERTIARY_LIST.indexOf(2F)).isEqualTo(1); + } + + @Test + public void testIndexOf_inListWithDuplicates_matchAtHead() { + FloatArrayList listWithDupes = newImmutableFloatArrayList(1F, 1F, 2F); + assertThat(listWithDupes.indexOf(1F)).isEqualTo(0); + } + + @Test + public void testIndexOf_inListWithDuplicates_matchMidList() { + FloatArrayList listWithDupes = newImmutableFloatArrayList(2F, 1F, 1F, 2F); + assertThat(listWithDupes.indexOf(1F)).isEqualTo(1); + } + + @Test + public void testContains_nullElement() { + assertThat(TERTIARY_LIST).doesNotContain(null); + } + + @Test + public void testContains_incompatibleElementType() { + assertThat(TERTIARY_LIST).doesNotContain(new Object()); + } + + @Test + public void testContains_notInList() { + assertThat(UNARY_LIST).doesNotContain(2F); + } + + @Test + public void testContains_notInListWithDuplicates() { + FloatArrayList listWithDupes = newImmutableFloatArrayList(1F, 1F); + assertThat(listWithDupes).doesNotContain(2F); + } + + @Test + public void testContains_inList() { + assertThat(TERTIARY_LIST).contains(2F); + } + + @Test + public void testContains_inListWithDuplicates_matchAtHead() { + FloatArrayList listWithDupes = newImmutableFloatArrayList(1F, 1F, 2F); + assertThat(listWithDupes).contains(1F); + } + + @Test + public void testContains_inListWithDuplicates_matchMidList() { + FloatArrayList listWithDupes = newImmutableFloatArrayList(2F, 1F, 1F, 2F); + assertThat(listWithDupes).contains(1F); + } + + @Test + public void testSize() { + assertThat(FloatArrayList.emptyList()).isEmpty(); + assertThat(UNARY_LIST).hasSize(1); + assertThat(TERTIARY_LIST).hasSize(3); + + list.addFloat(3); + list.addFloat(4); + list.addFloat(6); + list.addFloat(8); + assertThat(list).hasSize(4); + + list.remove(0); + assertThat(list).hasSize(3); + + list.add(17F); + assertThat(list).hasSize(4); + } + + @Test + public void testSet() { + list.addFloat(2); + list.addFloat(4); + + assertThat((float) list.set(0, 3F)).isEqualTo(2F); + assertThat(list.getFloat(0)).isEqualTo(3F); + + assertThat((float) list.set(1, 0F)).isEqualTo(4F); + assertThat(list.getFloat(1)).isEqualTo(0F); + + try { + list.set(-1, 0F); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + list.set(2, 0F); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + @Test + public void testSetFloat() { + list.addFloat(1); + list.addFloat(3); + + assertThat(list.setFloat(0, 0)).isEqualTo(1F); + assertThat(list.getFloat(0)).isEqualTo(0F); + + assertThat(list.setFloat(1, 0)).isEqualTo(3F); + assertThat(list.getFloat(1)).isEqualTo(0F); + + try { + list.setFloat(-1, 0); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + list.setFloat(2, 0); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + @Test + public void testAdd() { + assertThat(list).isEmpty(); + + assertThat(list.add(2F)).isTrue(); + assertThat(list).containsExactly(2F); + + assertThat(list.add(3F)).isTrue(); + list.add(0, 4F); + assertThat(list).containsExactly(4F, 2F, 3F).inOrder(); + + list.add(0, 1F); + list.add(0, 0F); + // Force a resize by getting up to 11 elements. + for (int i = 0; i < 6; i++) { + list.add(Float.valueOf(5 + i)); + } + assertThat(list).containsExactly(0F, 1F, 4F, 2F, 3F, 5F, 6F, 7F, 8F, 9F, 10F).inOrder(); + + try { + list.add(-1, 5F); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + list.add(4, 5F); + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + @Test + public void testAddFloat() { + assertThat(list).isEmpty(); + + list.addFloat(2); + assertThat(list).containsExactly(2F); + + list.addFloat(3); + assertThat(list).containsExactly(2F, 3F).inOrder(); + } + + @Test + public void testAddAll() { + assertThat(list).isEmpty(); + + assertThat(list.addAll(Collections.singleton(1F))).isTrue(); + assertThat(list).hasSize(1); + assertThat((float) list.get(0)).isEqualTo(1F); + assertThat(list.getFloat(0)).isEqualTo(1F); + + assertThat(list.addAll(asList(2F, 3F, 4F, 5F, 6F))).isTrue(); + assertThat(list).containsExactly(1F, 2F, 3F, 4F, 5F, 6F).inOrder(); + + assertThat(list.addAll(TERTIARY_LIST)).isTrue(); + assertThat(list).containsExactly(1F, 2F, 3F, 4F, 5F, 6F, 1F, 2F, 3F).inOrder(); + + assertThat(list.addAll(Collections.emptyList())).isFalse(); + assertThat(list.addAll(FloatArrayList.emptyList())).isFalse(); + } + + @Test + public void testEquals() { + FloatArrayList list1 = new FloatArrayList(); + FloatArrayList list2 = new FloatArrayList(); + + list1.addFloat(Float.intBitsToFloat(0xff800001)); + list2.addFloat(Float.intBitsToFloat(0xff800002)); + assertThat(list1).isEqualTo(list2); + } + + @Test + public void testRemove() { + list.addAll(TERTIARY_LIST); + assertThat((float) list.remove(0)).isEqualTo(1F); + assertThat(list).containsExactly(2F, 3F).inOrder(); + + assertThat(list.remove(Float.valueOf(3))).isTrue(); + assertThat(list).containsExactly(2F); + + assertThat(list.remove(Float.valueOf(3))).isFalse(); + assertThat(list).containsExactly(2F); + + assertThat((float) list.remove(0)).isEqualTo(2F); + assertThat(list).isEmpty(); + + try { + list.remove(-1); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + list.remove(0); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + @Test + public void testRemoveEnd_listAtCapacity() { + FloatList toRemove = FloatArrayList.emptyList().mutableCopyWithCapacity(1); + toRemove.addFloat(3); + toRemove.remove(0); + assertThat(toRemove).isEmpty(); + } + + @Test + public void testRemove_listAtCapacity() { + FloatList toRemove = FloatArrayList.emptyList().mutableCopyWithCapacity(2); + toRemove.addFloat(3); + toRemove.addFloat(4); + toRemove.remove(0); + assertThat(toRemove).hasSize(1); + assertThat((float) toRemove.get(0)).isEqualTo(4F); + } + + @Test + public void testSublistRemoveEndOfCapacity() { + FloatList toRemove = FloatArrayList.emptyList().mutableCopyWithCapacity(1); + toRemove.addFloat(3); + toRemove.subList(0, 1).clear(); + assertThat(toRemove).isEmpty(); + } + + private void assertImmutable(FloatList list) { + if (list.contains(1F)) { + throw new RuntimeException("Cannot test the immutability of lists that contain 1."); + } + + try { + list.add(1F); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.add(0, 1F); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addAll(Collections.emptyList()); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addAll(Collections.singletonList(1F)); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addAll(new FloatArrayList()); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addAll(UNARY_LIST); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addAll(0, Collections.singleton(1F)); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addAll(0, UNARY_LIST); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addAll(0, Collections.emptyList()); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addFloat(0); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.clear(); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.remove(1); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.remove(new Object()); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.removeAll(Collections.emptyList()); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.removeAll(Collections.singleton(1F)); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.removeAll(UNARY_LIST); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.retainAll(Collections.emptyList()); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.retainAll(Collections.singleton(1F)); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.retainAll(UNARY_LIST); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.set(0, 0F); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.setFloat(0, 0); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + } + + private static FloatArrayList newImmutableFloatArrayList(float... elements) { + FloatArrayList list = new FloatArrayList(); + for (float element : elements) { + list.addFloat(element); + } + list.makeImmutable(); + return list; + } +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java b/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java new file mode 100644 index 0000000..15bbda9 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java @@ -0,0 +1,584 @@ +// 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. + +package com.google.protobuf; + +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; +import static java.util.Arrays.asList; + +import com.google.protobuf.Internal.IntList; +import java.util.Collections; +import java.util.ConcurrentModificationException; +import java.util.Iterator; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for {@link IntArrayList}. */ +@RunWith(JUnit4.class) +public class IntArrayListTest { + + private static final IntArrayList UNARY_LIST = newImmutableIntArrayList(1); + private static final IntArrayList TERTIARY_LIST = newImmutableIntArrayList(1, 2, 3); + + private IntArrayList list; + + @Before + public void setUp() throws Exception { + list = new IntArrayList(); + } + + @Test + public void testEmptyListReturnsSameInstance() { + assertThat(IntArrayList.emptyList()).isSameInstanceAs(IntArrayList.emptyList()); + } + + @Test + public void testEmptyListIsImmutable() { + assertImmutable(IntArrayList.emptyList()); + } + + @Test + public void testMakeImmutable() { + list.addInt(3); + list.addInt(4); + list.addInt(5); + list.addInt(7); + list.makeImmutable(); + assertImmutable(list); + } + + @Test + public void testModificationWithIteration() { + list.addAll(asList(1, 2, 3, 4)); + Iterator iterator = list.iterator(); + assertThat(list).hasSize(4); + assertThat((int) list.get(0)).isEqualTo(1); + assertThat((int) iterator.next()).isEqualTo(1); + list.set(0, 1); + assertThat((int) iterator.next()).isEqualTo(2); + + list.remove(0); + try { + iterator.next(); + assertWithMessage("expected exception").fail(); + } catch (ConcurrentModificationException e) { + // expected + } + + iterator = list.iterator(); + list.add(0, 0); + try { + iterator.next(); + assertWithMessage("expected exception").fail(); + } catch (ConcurrentModificationException e) { + // expected + } + } + + @Test + public void testGet() { + assertThat((int) TERTIARY_LIST.get(0)).isEqualTo(1); + assertThat((int) TERTIARY_LIST.get(1)).isEqualTo(2); + assertThat((int) TERTIARY_LIST.get(2)).isEqualTo(3); + + try { + TERTIARY_LIST.get(-1); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + TERTIARY_LIST.get(3); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + @Test + public void testGetInt() { + assertThat(TERTIARY_LIST.getInt(0)).isEqualTo(1); + assertThat(TERTIARY_LIST.getInt(1)).isEqualTo(2); + assertThat(TERTIARY_LIST.getInt(2)).isEqualTo(3); + + try { + TERTIARY_LIST.get(-1); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + TERTIARY_LIST.get(3); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + @Test + public void testIndexOf_nullElement() { + assertThat(TERTIARY_LIST.indexOf(null)).isEqualTo(-1); + } + + @Test + public void testIndexOf_incompatibleElementType() { + assertThat(TERTIARY_LIST.indexOf(new Object())).isEqualTo(-1); + } + + @Test + public void testIndexOf_notInList() { + assertThat(UNARY_LIST.indexOf(2)).isEqualTo(-1); + } + + @Test + public void testIndexOf_notInListWithDuplicates() { + IntArrayList listWithDupes = newImmutableIntArrayList(1, 1); + assertThat(listWithDupes.indexOf(2)).isEqualTo(-1); + } + + @Test + public void testIndexOf_inList() { + assertThat(TERTIARY_LIST.indexOf(2)).isEqualTo(1); + } + + @Test + public void testIndexOf_inListWithDuplicates_matchAtHead() { + IntArrayList listWithDupes = newImmutableIntArrayList(1, 1, 2); + assertThat(listWithDupes.indexOf(1)).isEqualTo(0); + } + + @Test + public void testIndexOf_inListWithDuplicates_matchMidList() { + IntArrayList listWithDupes = newImmutableIntArrayList(2, 1, 1, 2); + assertThat(listWithDupes.indexOf(1)).isEqualTo(1); + } + + @Test + public void testContains_nullElement() { + assertThat(TERTIARY_LIST).doesNotContain(null); + } + + @Test + public void testContains_incompatibleElementType() { + assertThat(TERTIARY_LIST).doesNotContain(new Object()); + } + + @Test + public void testContains_notInList() { + assertThat(UNARY_LIST).doesNotContain(2); + } + + @Test + public void testContains_notInListWithDuplicates() { + IntArrayList listWithDupes = newImmutableIntArrayList(1, 1); + assertThat(listWithDupes).doesNotContain(2); + } + + @Test + public void testContains_inList() { + assertThat(TERTIARY_LIST).contains(2); + } + + @Test + public void testContains_inListWithDuplicates_matchAtHead() { + IntArrayList listWithDupes = newImmutableIntArrayList(1, 1, 2); + assertThat(listWithDupes).contains(1); + } + + @Test + public void testContains_inListWithDuplicates_matchMidList() { + IntArrayList listWithDupes = newImmutableIntArrayList(2, 1, 1, 2); + assertThat(listWithDupes).contains(1); + } + + @Test + public void testSize() { + assertThat(IntArrayList.emptyList()).isEmpty(); + assertThat(UNARY_LIST).hasSize(1); + assertThat(TERTIARY_LIST).hasSize(3); + + list.addInt(3); + list.addInt(4); + list.addInt(6); + list.addInt(8); + assertThat(list).hasSize(4); + + list.remove(0); + assertThat(list).hasSize(3); + + list.add(17); + assertThat(list).hasSize(4); + } + + @Test + public void testSet() { + list.addInt(2); + list.addInt(4); + + assertThat((int) list.set(0, 3)).isEqualTo(2); + assertThat(list.getInt(0)).isEqualTo(3); + + assertThat((int) list.set(1, 0)).isEqualTo(4); + assertThat(list.getInt(1)).isEqualTo(0); + + try { + list.set(-1, 0); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + list.set(2, 0); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + @Test + public void testSetInt() { + list.addInt(1); + list.addInt(3); + + assertThat(list.setInt(0, 0)).isEqualTo(1); + assertThat(list.getInt(0)).isEqualTo(0); + + assertThat(list.setInt(1, 0)).isEqualTo(3); + assertThat(list.getInt(1)).isEqualTo(0); + + try { + list.setInt(-1, 0); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + list.setInt(2, 0); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + @Test + public void testAdd() { + assertThat(list).isEmpty(); + + assertThat(list.add(2)).isTrue(); + assertThat(list).containsExactly(2); + + assertThat(list.add(3)).isTrue(); + list.add(0, 4); + assertThat(list).containsExactly(4, 2, 3).inOrder(); + + list.add(0, 1); + list.add(0, 0); + // Force a resize by getting up to 11 elements. + for (int i = 0; i < 6; i++) { + list.add(Integer.valueOf(5 + i)); + } + assertThat(list).containsExactly(0, 1, 4, 2, 3, 5, 6, 7, 8, 9, 10).inOrder(); + + try { + list.add(-1, 5); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + list.add(4, 5); + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + @Test + public void testAddInt() { + assertThat(list).isEmpty(); + + list.addInt(2); + assertThat(list).containsExactly(2); + + list.addInt(3); + assertThat(list).containsExactly(2, 3).inOrder(); + } + + @Test + public void testAddAll() { + assertThat(list).isEmpty(); + + assertThat(list.addAll(Collections.singleton(1))).isTrue(); + assertThat(list).hasSize(1); + assertThat((int) list.get(0)).isEqualTo(1); + assertThat(list.getInt(0)).isEqualTo(1); + + assertThat(list.addAll(asList(2, 3, 4, 5, 6))).isTrue(); + assertThat(list).containsExactly(1, 2, 3, 4, 5, 6).inOrder(); + + assertThat(list.addAll(TERTIARY_LIST)).isTrue(); + assertThat(list).containsExactly(1, 2, 3, 4, 5, 6, 1, 2, 3).inOrder(); + + assertThat(list.addAll(Collections.emptyList())).isFalse(); + assertThat(list.addAll(IntArrayList.emptyList())).isFalse(); + } + + @Test + public void testEquals() { + IntArrayList list1 = new IntArrayList(); + IntArrayList list2 = new IntArrayList(); + + assertThat(list1).isEqualTo(list2); + } + + @Test + public void testRemove() { + list.addAll(TERTIARY_LIST); + assertThat((int) list.remove(0)).isEqualTo(1); + assertThat(list).containsExactly(2, 3).inOrder(); + + assertThat(list.remove(Integer.valueOf(3))).isTrue(); + assertThat(list).containsExactly(2); + + assertThat(list.remove(Integer.valueOf(3))).isFalse(); + assertThat(list).containsExactly(2); + + assertThat((int) list.remove(0)).isEqualTo(2); + assertThat(list).isEmpty(); + + try { + list.remove(-1); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + list.remove(0); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + @Test + public void testRemoveEnd_listAtCapacity() { + IntList toRemove = IntArrayList.emptyList().mutableCopyWithCapacity(1); + toRemove.addInt(3); + toRemove.remove(0); + assertThat(toRemove).isEmpty(); + } + + @Test + public void testRemove_listAtCapacity() { + IntList toRemove = IntArrayList.emptyList().mutableCopyWithCapacity(2); + toRemove.addInt(3); + toRemove.addInt(4); + toRemove.remove(0); + assertThat(toRemove).hasSize(1); + assertThat((int) toRemove.get(0)).isEqualTo(4); + } + + @Test + public void testSublistRemoveEndOfCapacity() { + IntList toRemove = IntArrayList.emptyList().mutableCopyWithCapacity(1); + toRemove.addInt(3); + toRemove.subList(0, 1).clear(); + assertThat(toRemove).isEmpty(); + } + + private void assertImmutable(IntList list) { + if (list.contains(1)) { + throw new RuntimeException("Cannot test the immutability of lists that contain 1."); + } + + try { + list.add(1); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.add(0, 1); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addAll(Collections.emptyList()); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addAll(Collections.singletonList(1)); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addAll(new IntArrayList()); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addAll(UNARY_LIST); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addAll(0, Collections.singleton(1)); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addAll(0, UNARY_LIST); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addAll(0, Collections.emptyList()); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addInt(0); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.clear(); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.remove(1); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.remove(new Object()); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.removeAll(Collections.emptyList()); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.removeAll(Collections.singleton(1)); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.removeAll(UNARY_LIST); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.retainAll(Collections.emptyList()); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.retainAll(Collections.singleton(1)); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.retainAll(UNARY_LIST); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.set(0, 0); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.setInt(0, 0); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + } + + private static IntArrayList newImmutableIntArrayList(int... elements) { + IntArrayList list = new IntArrayList(); + for (int element : elements) { + list.addInt(element); + } + list.makeImmutable(); + return list; + } +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/ParserLiteTest.java b/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/ParserLiteTest.java new file mode 100644 index 0000000..fd0bf45 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/ParserLiteTest.java @@ -0,0 +1,203 @@ +// 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. + +package com.google.protobuf; + +import static com.google.common.truth.Truth.assertThat; + +import com.google.protobuf.UnittestLite.TestAllTypesLite; +import com.google.protobuf.UnittestLite.TestPackedExtensionsLite; +import com.google.protobuf.UnittestLite.TestParsingMergeLite; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class ParserLiteTest { + + private void assertRoundTripEquals(MessageLite message, ExtensionRegistryLite registry) + throws Exception { + final byte[] data = message.toByteArray(); + final int offset = 20; + final int length = data.length; + final int padding = 30; + Parser parser = message.getParserForType(); + assertThat(message).isEqualTo(parser.parseFrom(data, registry)); + assertThat(message) + .isEqualTo( + parser.parseFrom( + generatePaddingArray(data, offset, padding), offset, length, registry)); + assertThat(message).isEqualTo(parser.parseFrom(message.toByteString(), registry)); + assertThat(message).isEqualTo(parser.parseFrom(new ByteArrayInputStream(data), registry)); + assertThat(message).isEqualTo(parser.parseFrom(CodedInputStream.newInstance(data), registry)); + assertThat(message) + .isEqualTo(parser.parseFrom(message.toByteString().asReadOnlyByteBuffer(), registry)); + } + + @SuppressWarnings("unchecked") + private void assertRoundTripEquals(MessageLite message) throws Exception { + final byte[] data = message.toByteArray(); + final int offset = 20; + final int length = data.length; + final int padding = 30; + + Parser parser = (Parser) message.getParserForType(); + assertThat(message).isEqualTo(parser.parseFrom(data)); + assertThat(message) + .isEqualTo(parser.parseFrom(generatePaddingArray(data, offset, padding), offset, length)); + assertThat(message).isEqualTo(parser.parseFrom(message.toByteString())); + assertThat(message).isEqualTo(parser.parseFrom(new ByteArrayInputStream(data))); + assertThat(message).isEqualTo(parser.parseFrom(CodedInputStream.newInstance(data))); + assertThat(message).isEqualTo(parser.parseFrom(message.toByteString().asReadOnlyByteBuffer())); + } + + private byte[] generatePaddingArray(byte[] data, int offset, int padding) { + byte[] result = new byte[offset + data.length + padding]; + System.arraycopy(data, 0, result, offset, data.length); + return result; + } + + @Test + public void testParseExtensionsLite() throws Exception { + assertRoundTripEquals( + TestUtilLite.getAllLiteExtensionsSet(), TestUtilLite.getExtensionRegistryLite()); + } + + @Test + public void testParsePacked() throws Exception { + assertRoundTripEquals(TestUtil.getPackedSet()); + assertRoundTripEquals(TestUtil.getPackedExtensionsSet(), TestUtil.getExtensionRegistry()); + } + + @Test + public void testParsePackedLite() throws Exception { + assertRoundTripEquals( + TestUtilLite.getLitePackedExtensionsSet(), TestUtilLite.getExtensionRegistryLite()); + } + + @Test + public void testParseDelimitedToLite() throws Exception { + // Write MessageLite with packed extension fields. + TestPackedExtensionsLite packedMessage = TestUtilLite.getLitePackedExtensionsSet(); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + packedMessage.writeDelimitedTo(output); + packedMessage.writeDelimitedTo(output); + + InputStream input = new ByteArrayInputStream(output.toByteArray()); + assertThat(packedMessage) + .isEqualTo( + packedMessage + .getParserForType() + .parseDelimitedFrom(input, TestUtilLite.getExtensionRegistryLite())); + assertThat(packedMessage) + .isEqualTo( + packedMessage + .getParserForType() + .parseDelimitedFrom(input, TestUtilLite.getExtensionRegistryLite())); + } + + /** Helper method for {@link #testParsingMergeLite()}. */ + private void assertMessageMerged(TestAllTypesLite allTypes) throws Exception { + assertThat(allTypes.getOptionalInt32()).isEqualTo(3); + assertThat(allTypes.getOptionalInt64()).isEqualTo(2); + assertThat(allTypes.getOptionalString()).isEqualTo("hello"); + } + + @Test + public void testParsingMergeLite() throws Exception { + // Build messages. + TestAllTypesLite.Builder builder = TestAllTypesLite.newBuilder(); + TestAllTypesLite msg1 = builder.setOptionalInt32(1).build(); + builder.clear(); + TestAllTypesLite msg2 = builder.setOptionalInt64(2).build(); + builder.clear(); + TestAllTypesLite msg3 = builder.setOptionalInt32(3).setOptionalString("hello").build(); + + // Build groups. + TestParsingMergeLite.RepeatedFieldsGenerator.Group1 optionalG1 = + TestParsingMergeLite.RepeatedFieldsGenerator.Group1.newBuilder().setField1(msg1).build(); + TestParsingMergeLite.RepeatedFieldsGenerator.Group1 optionalG2 = + TestParsingMergeLite.RepeatedFieldsGenerator.Group1.newBuilder().setField1(msg2).build(); + TestParsingMergeLite.RepeatedFieldsGenerator.Group1 optionalG3 = + TestParsingMergeLite.RepeatedFieldsGenerator.Group1.newBuilder().setField1(msg3).build(); + TestParsingMergeLite.RepeatedFieldsGenerator.Group2 repeatedG1 = + TestParsingMergeLite.RepeatedFieldsGenerator.Group2.newBuilder().setField1(msg1).build(); + TestParsingMergeLite.RepeatedFieldsGenerator.Group2 repeatedG2 = + TestParsingMergeLite.RepeatedFieldsGenerator.Group2.newBuilder().setField1(msg2).build(); + TestParsingMergeLite.RepeatedFieldsGenerator.Group2 repeatedG3 = + TestParsingMergeLite.RepeatedFieldsGenerator.Group2.newBuilder().setField1(msg3).build(); + + // Assign and serialize RepeatedFieldsGenerator. + ByteString data = + TestParsingMergeLite.RepeatedFieldsGenerator.newBuilder() + .addField1(msg1) + .addField1(msg2) + .addField1(msg3) + .addField2(msg1) + .addField2(msg2) + .addField2(msg3) + .addField3(msg1) + .addField3(msg2) + .addField3(msg3) + .addGroup1(optionalG1) + .addGroup1(optionalG2) + .addGroup1(optionalG3) + .addGroup2(repeatedG1) + .addGroup2(repeatedG2) + .addGroup2(repeatedG3) + .addExt1(msg1) + .addExt1(msg2) + .addExt1(msg3) + .addExt2(msg1) + .addExt2(msg2) + .addExt2(msg3) + .build() + .toByteString(); + + // Parse TestParsingMergeLite. + ExtensionRegistryLite registry = ExtensionRegistryLite.newInstance(); + UnittestLite.registerAllExtensions(registry); + TestParsingMergeLite parsingMerge = TestParsingMergeLite.parser().parseFrom(data, registry); + + // Required and optional fields should be merged. + assertMessageMerged(parsingMerge.getRequiredAllTypes()); + assertMessageMerged(parsingMerge.getOptionalAllTypes()); + assertMessageMerged(parsingMerge.getOptionalGroup().getOptionalGroupAllTypes()); + assertMessageMerged(parsingMerge.getExtension(TestParsingMergeLite.optionalExt)); + + // Repeated fields should not be merged. + assertThat(parsingMerge.getRepeatedAllTypesCount()).isEqualTo(3); + assertThat(parsingMerge.getRepeatedGroupCount()).isEqualTo(3); + assertThat(parsingMerge.getExtensionCount(TestParsingMergeLite.repeatedExt)).isEqualTo(3); + } +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/ParserTest.java b/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/ParserTest.java new file mode 100644 index 0000000..e78c671 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/ParserTest.java @@ -0,0 +1,334 @@ +// 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. + +package com.google.protobuf; + +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; + +import protobuf_unittest.UnittestOptimizeFor; +import protobuf_unittest.UnittestOptimizeFor.TestOptimizedForSize; +import protobuf_unittest.UnittestOptimizeFor.TestRequiredOptimizedForSize; +import protobuf_unittest.UnittestProto; +import protobuf_unittest.UnittestProto.ForeignMessage; +import protobuf_unittest.UnittestProto.TestAllTypes; +import protobuf_unittest.UnittestProto.TestEmptyMessage; +import protobuf_unittest.UnittestProto.TestParsingMerge; +import protobuf_unittest.UnittestProto.TestRequired; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InterruptedIOException; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit test for {@link Parser}. */ +@RunWith(JUnit4.class) +public class ParserTest { + + @Test + public void testGeneratedMessageParserSingleton() throws Exception { + for (int i = 0; i < 10; i++) { + assertThat(TestUtil.getAllSet().getParserForType()).isEqualTo(TestAllTypes.parser()); + } + } + + private void assertRoundTripEquals(MessageLite message, ExtensionRegistryLite registry) + throws Exception { + final byte[] data = message.toByteArray(); + final int offset = 20; + final int length = data.length; + final int padding = 30; + Parser parser = message.getParserForType(); + assertMessageEquals(message, parser.parseFrom(data, registry)); + assertMessageEquals( + message, + parser.parseFrom(generatePaddingArray(data, offset, padding), offset, length, registry)); + assertMessageEquals(message, parser.parseFrom(message.toByteString(), registry)); + assertMessageEquals(message, parser.parseFrom(new ByteArrayInputStream(data), registry)); + assertMessageEquals(message, parser.parseFrom(CodedInputStream.newInstance(data), registry)); + assertMessageEquals( + message, parser.parseFrom(message.toByteString().asReadOnlyByteBuffer(), registry)); + } + + @SuppressWarnings("unchecked") + private void assertRoundTripEquals(MessageLite message) throws Exception { + final byte[] data = message.toByteArray(); + final int offset = 20; + final int length = data.length; + final int padding = 30; + + Parser parser = (Parser) message.getParserForType(); + assertMessageEquals(message, parser.parseFrom(data)); + assertMessageEquals( + message, parser.parseFrom(generatePaddingArray(data, offset, padding), offset, length)); + assertMessageEquals(message, parser.parseFrom(message.toByteString())); + assertMessageEquals(message, parser.parseFrom(new ByteArrayInputStream(data))); + assertMessageEquals(message, parser.parseFrom(CodedInputStream.newInstance(data))); + assertMessageEquals(message, parser.parseFrom(message.toByteString().asReadOnlyByteBuffer())); + } + + private void assertMessageEquals(MessageLite expected, MessageLite actual) throws Exception { + if (expected instanceof Message) { + assertThat(actual).isEqualTo(expected); + } else { + assertThat(actual.toByteString()).isEqualTo(expected.toByteString()); + } + } + + private byte[] generatePaddingArray(byte[] data, int offset, int padding) { + byte[] result = new byte[offset + data.length + padding]; + System.arraycopy(data, 0, result, offset, data.length); + return result; + } + + @Test + public void testNormalMessage() throws Exception { + assertRoundTripEquals(TestUtil.getAllSet()); + } + + + @Test + public void testParsePartial() throws Exception { + assertParsePartial(TestRequired.parser(), TestRequired.newBuilder().setA(1).buildPartial()); + } + + private void assertParsePartial(Parser parser, T partialMessage) + throws Exception { + final String errorString = "Should throw exceptions when the parsed message isn't initialized."; + + // parsePartialFrom should pass. + byte[] data = partialMessage.toByteArray(); + assertThat(parser.parsePartialFrom(data)).isEqualTo(partialMessage); + assertThat(parser.parsePartialFrom(partialMessage.toByteString())).isEqualTo(partialMessage); + assertThat(parser.parsePartialFrom(new ByteArrayInputStream(data))).isEqualTo(partialMessage); + assertThat(parser.parsePartialFrom(CodedInputStream.newInstance(data))) + .isEqualTo(partialMessage); + + // parseFrom(ByteArray) + try { + parser.parseFrom(partialMessage.toByteArray()); + assertWithMessage(errorString).fail(); + } catch (InvalidProtocolBufferException e) { + // pass. + } + + // parseFrom(ByteString) + try { + parser.parseFrom(partialMessage.toByteString()); + assertWithMessage(errorString).fail(); + } catch (InvalidProtocolBufferException e) { + // pass. + } + + // parseFrom(InputStream) + try { + parser.parseFrom(new ByteArrayInputStream(partialMessage.toByteArray())); + assertWithMessage(errorString).fail(); + } catch (IOException e) { + // pass. + } + + // parseFrom(CodedInputStream) + try { + parser.parseFrom(CodedInputStream.newInstance(partialMessage.toByteArray())); + assertWithMessage(errorString).fail(); + } catch (IOException e) { + // pass. + } + } + + @Test + public void testParseExtensions() throws Exception { + assertRoundTripEquals(TestUtil.getAllExtensionsSet(), TestUtil.getExtensionRegistry()); + } + + @Test + public void testParsePacked() throws Exception { + assertRoundTripEquals(TestUtil.getPackedSet()); + assertRoundTripEquals(TestUtil.getPackedExtensionsSet(), TestUtil.getExtensionRegistry()); + } + + @Test + public void testParseDelimitedTo() throws Exception { + // Write normal Message. + TestAllTypes normalMessage = TestUtil.getAllSet(); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + normalMessage.writeDelimitedTo(output); + normalMessage.writeDelimitedTo(output); + + InputStream input = new ByteArrayInputStream(output.toByteArray()); + assertMessageEquals(normalMessage, normalMessage.getParserForType().parseDelimitedFrom(input)); + assertMessageEquals(normalMessage, normalMessage.getParserForType().parseDelimitedFrom(input)); + } + + @Test + public void testParseUnknownFields() throws Exception { + // All fields will be treated as unknown fields in emptyMessage. + TestEmptyMessage emptyMessage = + TestEmptyMessage.parser().parseFrom(TestUtil.getAllSet().toByteString()); + assertThat(emptyMessage.toByteString()).isEqualTo(TestUtil.getAllSet().toByteString()); + } + + + @Test + public void testOptimizeForSize() throws Exception { + TestOptimizedForSize.Builder builder = TestOptimizedForSize.newBuilder(); + builder.setI(12).setMsg(ForeignMessage.newBuilder().setC(34).build()); + builder.setExtension(TestOptimizedForSize.testExtension, 56); + builder.setExtension( + TestOptimizedForSize.testExtension2, + TestRequiredOptimizedForSize.newBuilder().setX(78).build()); + + TestOptimizedForSize message = builder.build(); + ExtensionRegistry registry = ExtensionRegistry.newInstance(); + UnittestOptimizeFor.registerAllExtensions(registry); + + assertRoundTripEquals(message, registry); + } + + /** Helper method for {@link #testParsingMerge()}. */ + private void assertMessageMerged(TestAllTypes allTypes) throws Exception { + assertThat(allTypes.getOptionalInt32()).isEqualTo(3); + assertThat(allTypes.getOptionalInt64()).isEqualTo(2); + assertThat(allTypes.getOptionalString()).isEqualTo("hello"); + } + + @Test + public void testParsingMerge() throws Exception { + // Build messages. + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + TestAllTypes msg1 = builder.setOptionalInt32(1).build(); + builder.clear(); + TestAllTypes msg2 = builder.setOptionalInt64(2).build(); + builder.clear(); + TestAllTypes msg3 = builder.setOptionalInt32(3).setOptionalString("hello").build(); + + // Build groups. + TestParsingMerge.RepeatedFieldsGenerator.Group1 optionalG1 = + TestParsingMerge.RepeatedFieldsGenerator.Group1.newBuilder().setField1(msg1).build(); + TestParsingMerge.RepeatedFieldsGenerator.Group1 optionalG2 = + TestParsingMerge.RepeatedFieldsGenerator.Group1.newBuilder().setField1(msg2).build(); + TestParsingMerge.RepeatedFieldsGenerator.Group1 optionalG3 = + TestParsingMerge.RepeatedFieldsGenerator.Group1.newBuilder().setField1(msg3).build(); + TestParsingMerge.RepeatedFieldsGenerator.Group2 repeatedG1 = + TestParsingMerge.RepeatedFieldsGenerator.Group2.newBuilder().setField1(msg1).build(); + TestParsingMerge.RepeatedFieldsGenerator.Group2 repeatedG2 = + TestParsingMerge.RepeatedFieldsGenerator.Group2.newBuilder().setField1(msg2).build(); + TestParsingMerge.RepeatedFieldsGenerator.Group2 repeatedG3 = + TestParsingMerge.RepeatedFieldsGenerator.Group2.newBuilder().setField1(msg3).build(); + + // Assign and serialize RepeatedFieldsGenerator. + ByteString data = + TestParsingMerge.RepeatedFieldsGenerator.newBuilder() + .addField1(msg1) + .addField1(msg2) + .addField1(msg3) + .addField2(msg1) + .addField2(msg2) + .addField2(msg3) + .addField3(msg1) + .addField3(msg2) + .addField3(msg3) + .addGroup1(optionalG1) + .addGroup1(optionalG2) + .addGroup1(optionalG3) + .addGroup2(repeatedG1) + .addGroup2(repeatedG2) + .addGroup2(repeatedG3) + .addExt1(msg1) + .addExt1(msg2) + .addExt1(msg3) + .addExt2(msg1) + .addExt2(msg2) + .addExt2(msg3) + .build() + .toByteString(); + + // Parse TestParsingMerge. + ExtensionRegistry registry = ExtensionRegistry.newInstance(); + UnittestProto.registerAllExtensions(registry); + TestParsingMerge parsingMerge = TestParsingMerge.parser().parseFrom(data, registry); + + // Required and optional fields should be merged. + assertMessageMerged(parsingMerge.getRequiredAllTypes()); + assertMessageMerged(parsingMerge.getOptionalAllTypes()); + assertMessageMerged(parsingMerge.getOptionalGroup().getOptionalGroupAllTypes()); + assertMessageMerged(parsingMerge.getExtension(TestParsingMerge.optionalExt)); + + // Repeated fields should not be merged. + assertThat(parsingMerge.getRepeatedAllTypesCount()).isEqualTo(3); + assertThat(parsingMerge.getRepeatedGroupCount()).isEqualTo(3); + assertThat(parsingMerge.getExtensionCount(TestParsingMerge.repeatedExt)).isEqualTo(3); + } + + @Test + public void testParseDelimitedFrom_firstByteInterrupted_preservesCause() { + try { + TestAllTypes.parseDelimitedFrom( + new InputStream() { + @Override + public int read() throws IOException { + throw new InterruptedIOException(); + } + }); + assertWithMessage("Expected InterruptedIOException").fail(); + } catch (Exception e) { + assertThat(e.getClass()).isEqualTo(InterruptedIOException.class); + } + } + + @Test + public void testParseDelimitedFrom_secondByteInterrupted_preservesCause() { + try { + TestAllTypes.parseDelimitedFrom( + new InputStream() { + private int i; + + @Override + public int read() throws IOException { + switch (i++) { + case 0: + return 1; + case 1: + throw new InterruptedIOException(); + default: + throw new AssertionError(); + } + } + }); + assertWithMessage("Expected InterruptedIOException").fail(); + } catch (Exception e) { + assertThat(e.getClass()).isEqualTo(InterruptedIOException.class); + } + } +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/Proto3SchemaTest.java b/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/Proto3SchemaTest.java new file mode 100644 index 0000000..5cd145b --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/Proto3SchemaTest.java @@ -0,0 +1,48 @@ +// 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. + +package com.google.protobuf; + +import com.google.protobuf.testing.Proto3Testing.Proto3Message; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class Proto3SchemaTest extends AbstractProto3SchemaTest { + @Override + protected void registerSchemas() { + TestSchemas.registerGenericProto3Schemas(); + } + + @Override + protected Schema schema() { + return TestSchemas.genericProto3Schema; + } +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java b/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java new file mode 100644 index 0000000..bb95e2a --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java @@ -0,0 +1,191 @@ +// 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. + +package com.google.protobuf; + +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; + +import protobuf_unittest.UnittestProto.TestAllTypes; +import protobuf_unittest.UnittestProto.TestAllTypesOrBuilder; +import java.util.Collections; +import java.util.List; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for {@link RepeatedFieldBuilderV3}. This tests basic functionality. More extensive testing is + * provided via other tests that exercise the builder. + */ +@RunWith(JUnit4.class) +public class RepeatedFieldBuilderV3Test { + + @Test + public void testBasicUse() { + TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent(); + RepeatedFieldBuilderV3 builder = + newRepeatedFieldBuilderV3(mockParent); + builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(0).build()); + builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build()); + assertThat(builder.getMessage(0).getOptionalInt32()).isEqualTo(0); + assertThat(builder.getMessage(1).getOptionalInt32()).isEqualTo(1); + + List list = builder.build(); + assertThat(list).hasSize(2); + assertThat(list.get(0).getOptionalInt32()).isEqualTo(0); + assertThat(list.get(1).getOptionalInt32()).isEqualTo(1); + assertIsUnmodifiable(list); + + // Make sure it doesn't change. + List list2 = builder.build(); + assertThat(list).isSameInstanceAs(list2); + assertThat(mockParent.getInvalidationCount()).isEqualTo(0); + } + + @Test + public void testGoingBackAndForth() { + TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent(); + RepeatedFieldBuilderV3 builder = + newRepeatedFieldBuilderV3(mockParent); + builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(0).build()); + builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build()); + assertThat(builder.getMessage(0).getOptionalInt32()).isEqualTo(0); + assertThat(builder.getMessage(1).getOptionalInt32()).isEqualTo(1); + + // Convert to list + List list = builder.build(); + assertThat(list).hasSize(2); + assertThat(list.get(0).getOptionalInt32()).isEqualTo(0); + assertThat(list.get(1).getOptionalInt32()).isEqualTo(1); + assertIsUnmodifiable(list); + + // Update 0th item + assertThat(mockParent.getInvalidationCount()).isEqualTo(0); + builder.getBuilder(0).setOptionalString("foo"); + assertThat(mockParent.getInvalidationCount()).isEqualTo(1); + list = builder.build(); + assertThat(list).hasSize(2); + assertThat(list.get(0).getOptionalInt32()).isEqualTo(0); + assertThat(list.get(0).getOptionalString()).isEqualTo("foo"); + assertThat(list.get(1).getOptionalInt32()).isEqualTo(1); + assertIsUnmodifiable(list); + assertThat(mockParent.getInvalidationCount()).isEqualTo(1); + } + + @Test + public void testVariousMethods() { + TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent(); + RepeatedFieldBuilderV3 builder = + newRepeatedFieldBuilderV3(mockParent); + builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build()); + builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(2).build()); + builder.addBuilder(0, TestAllTypes.getDefaultInstance()).setOptionalInt32(0); + builder.addBuilder(TestAllTypes.getDefaultInstance()).setOptionalInt32(3); + + assertThat(builder.getMessage(0).getOptionalInt32()).isEqualTo(0); + assertThat(builder.getMessage(1).getOptionalInt32()).isEqualTo(1); + assertThat(builder.getMessage(2).getOptionalInt32()).isEqualTo(2); + assertThat(builder.getMessage(3).getOptionalInt32()).isEqualTo(3); + + assertThat(mockParent.getInvalidationCount()).isEqualTo(0); + List messages = builder.build(); + assertThat(messages).hasSize(4); + assertThat(messages).isSameInstanceAs(builder.build()); // expect same list + + // Remove a message. + builder.remove(2); + assertThat(mockParent.getInvalidationCount()).isEqualTo(1); + assertThat(builder.getCount()).isEqualTo(3); + assertThat(builder.getMessage(0).getOptionalInt32()).isEqualTo(0); + assertThat(builder.getMessage(1).getOptionalInt32()).isEqualTo(1); + assertThat(builder.getMessage(2).getOptionalInt32()).isEqualTo(3); + + // Remove a builder. + builder.remove(0); + assertThat(mockParent.getInvalidationCount()).isEqualTo(1); + assertThat(builder.getCount()).isEqualTo(2); + assertThat(builder.getMessage(0).getOptionalInt32()).isEqualTo(1); + assertThat(builder.getMessage(1).getOptionalInt32()).isEqualTo(3); + + // Test clear. + builder.clear(); + assertThat(mockParent.getInvalidationCount()).isEqualTo(1); + assertThat(builder.getCount()).isEqualTo(0); + assertThat(builder.isEmpty()).isTrue(); + } + + @Test + public void testLists() { + TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent(); + RepeatedFieldBuilderV3 builder = + newRepeatedFieldBuilderV3(mockParent); + builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build()); + builder.addMessage(0, TestAllTypes.newBuilder().setOptionalInt32(0).build()); + assertThat(builder.getMessage(0).getOptionalInt32()).isEqualTo(0); + assertThat(builder.getMessage(1).getOptionalInt32()).isEqualTo(1); + + // Use list of builders. + List builders = builder.getBuilderList(); + assertThat(builders.get(0).getOptionalInt32()).isEqualTo(0); + assertThat(builders.get(1).getOptionalInt32()).isEqualTo(1); + builders.get(0).setOptionalInt32(10); + builders.get(1).setOptionalInt32(11); + + // Use list of protos + List protos = builder.getMessageList(); + assertThat(protos.get(0).getOptionalInt32()).isEqualTo(10); + assertThat(protos.get(1).getOptionalInt32()).isEqualTo(11); + + // Add an item to the builders and verify it's updated in both + builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(12).build()); + assertThat(builders).hasSize(3); + assertThat(protos).hasSize(3); + } + + private void assertIsUnmodifiable(List list) { + if (list == Collections.emptyList()) { + // OKAY -- Need to check this b/c EmptyList allows you to call clear. + } else { + try { + list.clear(); + assertWithMessage("List wasn't immutable").fail(); + } catch (UnsupportedOperationException e) { + // good + } + } + } + + private RepeatedFieldBuilderV3 + newRepeatedFieldBuilderV3(AbstractMessage.BuilderParent parent) { + return new RepeatedFieldBuilderV3( + Collections.emptyList(), false, parent, false); + } +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/TestUtil.java b/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/TestUtil.java new file mode 100644 index 0000000..b409268 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/TestUtil.java @@ -0,0 +1,3900 @@ +// 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. + +package com.google.protobuf; + +import static com.google.protobuf.UnittestLite.defaultBoolExtensionLite; +import static com.google.protobuf.UnittestLite.defaultBytesExtensionLite; +import static com.google.protobuf.UnittestLite.defaultCordExtensionLite; +import static com.google.protobuf.UnittestLite.defaultDoubleExtensionLite; +import static com.google.protobuf.UnittestLite.defaultFixed32ExtensionLite; +import static com.google.protobuf.UnittestLite.defaultFixed64ExtensionLite; +import static com.google.protobuf.UnittestLite.defaultFloatExtensionLite; +import static com.google.protobuf.UnittestLite.defaultForeignEnumExtensionLite; +import static com.google.protobuf.UnittestLite.defaultImportEnumExtensionLite; +import static com.google.protobuf.UnittestLite.defaultInt32ExtensionLite; +import static com.google.protobuf.UnittestLite.defaultInt64ExtensionLite; +import static com.google.protobuf.UnittestLite.defaultNestedEnumExtensionLite; +import static com.google.protobuf.UnittestLite.defaultSfixed32ExtensionLite; +import static com.google.protobuf.UnittestLite.defaultSfixed64ExtensionLite; +import static com.google.protobuf.UnittestLite.defaultSint32ExtensionLite; +import static com.google.protobuf.UnittestLite.defaultSint64ExtensionLite; +import static com.google.protobuf.UnittestLite.defaultStringExtensionLite; +import static com.google.protobuf.UnittestLite.defaultStringPieceExtensionLite; +import static com.google.protobuf.UnittestLite.defaultUint32ExtensionLite; +import static com.google.protobuf.UnittestLite.defaultUint64ExtensionLite; +import static com.google.protobuf.UnittestLite.oneofBytesExtensionLite; +import static com.google.protobuf.UnittestLite.oneofNestedMessageExtensionLite; +import static com.google.protobuf.UnittestLite.oneofStringExtensionLite; +import static com.google.protobuf.UnittestLite.oneofUint32ExtensionLite; +import static com.google.protobuf.UnittestLite.optionalBoolExtensionLite; +import static com.google.protobuf.UnittestLite.optionalBytesExtensionLite; +import static com.google.protobuf.UnittestLite.optionalCordExtensionLite; +import static com.google.protobuf.UnittestLite.optionalDoubleExtensionLite; +import static com.google.protobuf.UnittestLite.optionalFixed32ExtensionLite; +import static com.google.protobuf.UnittestLite.optionalFixed64ExtensionLite; +import static com.google.protobuf.UnittestLite.optionalFloatExtensionLite; +import static com.google.protobuf.UnittestLite.optionalForeignEnumExtensionLite; +import static com.google.protobuf.UnittestLite.optionalForeignMessageExtensionLite; +import static com.google.protobuf.UnittestLite.optionalGroupExtensionLite; +import static com.google.protobuf.UnittestLite.optionalImportEnumExtensionLite; +import static com.google.protobuf.UnittestLite.optionalImportMessageExtensionLite; +import static com.google.protobuf.UnittestLite.optionalInt32ExtensionLite; +import static com.google.protobuf.UnittestLite.optionalInt64ExtensionLite; +import static com.google.protobuf.UnittestLite.optionalLazyMessageExtensionLite; +import static com.google.protobuf.UnittestLite.optionalNestedEnumExtensionLite; +import static com.google.protobuf.UnittestLite.optionalNestedMessageExtensionLite; +import static com.google.protobuf.UnittestLite.optionalPublicImportMessageExtensionLite; +import static com.google.protobuf.UnittestLite.optionalSfixed32ExtensionLite; +import static com.google.protobuf.UnittestLite.optionalSfixed64ExtensionLite; +import static com.google.protobuf.UnittestLite.optionalSint32ExtensionLite; +import static com.google.protobuf.UnittestLite.optionalSint64ExtensionLite; +import static com.google.protobuf.UnittestLite.optionalStringExtensionLite; +import static com.google.protobuf.UnittestLite.optionalStringPieceExtensionLite; +import static com.google.protobuf.UnittestLite.optionalUint32ExtensionLite; +import static com.google.protobuf.UnittestLite.optionalUint64ExtensionLite; +import static com.google.protobuf.UnittestLite.packedBoolExtensionLite; +import static com.google.protobuf.UnittestLite.packedDoubleExtensionLite; +import static com.google.protobuf.UnittestLite.packedEnumExtensionLite; +import static com.google.protobuf.UnittestLite.packedFixed32ExtensionLite; +import static com.google.protobuf.UnittestLite.packedFixed64ExtensionLite; +import static com.google.protobuf.UnittestLite.packedFloatExtensionLite; +import static com.google.protobuf.UnittestLite.packedInt32ExtensionLite; +import static com.google.protobuf.UnittestLite.packedInt64ExtensionLite; +import static com.google.protobuf.UnittestLite.packedSfixed32ExtensionLite; +import static com.google.protobuf.UnittestLite.packedSfixed64ExtensionLite; +import static com.google.protobuf.UnittestLite.packedSint32ExtensionLite; +import static com.google.protobuf.UnittestLite.packedSint64ExtensionLite; +import static com.google.protobuf.UnittestLite.packedUint32ExtensionLite; +import static com.google.protobuf.UnittestLite.packedUint64ExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedBoolExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedBytesExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedCordExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedDoubleExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedFixed32ExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedFixed64ExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedFloatExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedForeignEnumExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedForeignMessageExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedGroupExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedImportEnumExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedImportMessageExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedInt32ExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedInt64ExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedLazyMessageExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedNestedEnumExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedNestedMessageExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedSfixed32ExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedSfixed64ExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedSint32ExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedSint64ExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedStringExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedStringPieceExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedUint32ExtensionLite; +import static com.google.protobuf.UnittestLite.repeatedUint64ExtensionLite; +import static protobuf_unittest.UnittestProto.defaultBoolExtension; +import static protobuf_unittest.UnittestProto.defaultBytesExtension; +import static protobuf_unittest.UnittestProto.defaultCordExtension; +import static protobuf_unittest.UnittestProto.defaultDoubleExtension; +import static protobuf_unittest.UnittestProto.defaultFixed32Extension; +import static protobuf_unittest.UnittestProto.defaultFixed64Extension; +import static protobuf_unittest.UnittestProto.defaultFloatExtension; +import static protobuf_unittest.UnittestProto.defaultForeignEnumExtension; +import static protobuf_unittest.UnittestProto.defaultImportEnumExtension; +import static protobuf_unittest.UnittestProto.defaultInt32Extension; +import static protobuf_unittest.UnittestProto.defaultInt64Extension; +import static protobuf_unittest.UnittestProto.defaultNestedEnumExtension; +import static protobuf_unittest.UnittestProto.defaultSfixed32Extension; +import static protobuf_unittest.UnittestProto.defaultSfixed64Extension; +import static protobuf_unittest.UnittestProto.defaultSint32Extension; +import static protobuf_unittest.UnittestProto.defaultSint64Extension; +import static protobuf_unittest.UnittestProto.defaultStringExtension; +import static protobuf_unittest.UnittestProto.defaultStringPieceExtension; +import static protobuf_unittest.UnittestProto.defaultUint32Extension; +import static protobuf_unittest.UnittestProto.defaultUint64Extension; +import static protobuf_unittest.UnittestProto.oneofBytesExtension; +import static protobuf_unittest.UnittestProto.oneofNestedMessageExtension; +import static protobuf_unittest.UnittestProto.oneofStringExtension; +import static protobuf_unittest.UnittestProto.oneofUint32Extension; +import static protobuf_unittest.UnittestProto.optionalBoolExtension; +import static protobuf_unittest.UnittestProto.optionalBytesExtension; +import static protobuf_unittest.UnittestProto.optionalCordExtension; +import static protobuf_unittest.UnittestProto.optionalDoubleExtension; +import static protobuf_unittest.UnittestProto.optionalFixed32Extension; +import static protobuf_unittest.UnittestProto.optionalFixed64Extension; +import static protobuf_unittest.UnittestProto.optionalFloatExtension; +import static protobuf_unittest.UnittestProto.optionalForeignEnumExtension; +import static protobuf_unittest.UnittestProto.optionalForeignMessageExtension; +import static protobuf_unittest.UnittestProto.optionalGroupExtension; +import static protobuf_unittest.UnittestProto.optionalImportEnumExtension; +import static protobuf_unittest.UnittestProto.optionalImportMessageExtension; +import static protobuf_unittest.UnittestProto.optionalInt32Extension; +import static protobuf_unittest.UnittestProto.optionalInt64Extension; +import static protobuf_unittest.UnittestProto.optionalLazyMessageExtension; +import static protobuf_unittest.UnittestProto.optionalNestedEnumExtension; +import static protobuf_unittest.UnittestProto.optionalNestedMessageExtension; +import static protobuf_unittest.UnittestProto.optionalPublicImportMessageExtension; +import static protobuf_unittest.UnittestProto.optionalSfixed32Extension; +import static protobuf_unittest.UnittestProto.optionalSfixed64Extension; +import static protobuf_unittest.UnittestProto.optionalSint32Extension; +import static protobuf_unittest.UnittestProto.optionalSint64Extension; +import static protobuf_unittest.UnittestProto.optionalStringExtension; +import static protobuf_unittest.UnittestProto.optionalStringPieceExtension; +import static protobuf_unittest.UnittestProto.optionalUint32Extension; +import static protobuf_unittest.UnittestProto.optionalUint64Extension; +import static protobuf_unittest.UnittestProto.packedBoolExtension; +import static protobuf_unittest.UnittestProto.packedDoubleExtension; +import static protobuf_unittest.UnittestProto.packedEnumExtension; +import static protobuf_unittest.UnittestProto.packedFixed32Extension; +import static protobuf_unittest.UnittestProto.packedFixed64Extension; +import static protobuf_unittest.UnittestProto.packedFloatExtension; +import static protobuf_unittest.UnittestProto.packedInt32Extension; +import static protobuf_unittest.UnittestProto.packedInt64Extension; +import static protobuf_unittest.UnittestProto.packedSfixed32Extension; +import static protobuf_unittest.UnittestProto.packedSfixed64Extension; +import static protobuf_unittest.UnittestProto.packedSint32Extension; +import static protobuf_unittest.UnittestProto.packedSint64Extension; +import static protobuf_unittest.UnittestProto.packedUint32Extension; +import static protobuf_unittest.UnittestProto.packedUint64Extension; +import static protobuf_unittest.UnittestProto.repeatedBoolExtension; +import static protobuf_unittest.UnittestProto.repeatedBytesExtension; +import static protobuf_unittest.UnittestProto.repeatedCordExtension; +import static protobuf_unittest.UnittestProto.repeatedDoubleExtension; +import static protobuf_unittest.UnittestProto.repeatedFixed32Extension; +import static protobuf_unittest.UnittestProto.repeatedFixed64Extension; +import static protobuf_unittest.UnittestProto.repeatedFloatExtension; +import static protobuf_unittest.UnittestProto.repeatedForeignEnumExtension; +import static protobuf_unittest.UnittestProto.repeatedForeignMessageExtension; +import static protobuf_unittest.UnittestProto.repeatedGroupExtension; +import static protobuf_unittest.UnittestProto.repeatedImportEnumExtension; +import static protobuf_unittest.UnittestProto.repeatedImportMessageExtension; +import static protobuf_unittest.UnittestProto.repeatedInt32Extension; +import static protobuf_unittest.UnittestProto.repeatedInt64Extension; +import static protobuf_unittest.UnittestProto.repeatedLazyMessageExtension; +import static protobuf_unittest.UnittestProto.repeatedNestedEnumExtension; +import static protobuf_unittest.UnittestProto.repeatedNestedMessageExtension; +import static protobuf_unittest.UnittestProto.repeatedSfixed32Extension; +import static protobuf_unittest.UnittestProto.repeatedSfixed64Extension; +import static protobuf_unittest.UnittestProto.repeatedSint32Extension; +import static protobuf_unittest.UnittestProto.repeatedSint64Extension; +import static protobuf_unittest.UnittestProto.repeatedStringExtension; +import static protobuf_unittest.UnittestProto.repeatedStringPieceExtension; +import static protobuf_unittest.UnittestProto.repeatedUint32Extension; +import static protobuf_unittest.UnittestProto.repeatedUint64Extension; + +import com.google.protobuf.UnittestImportLite.ImportEnumLite; +import com.google.protobuf.UnittestLite.ForeignEnumLite; +import com.google.protobuf.UnittestLite.TestAllExtensionsLiteOrBuilder; +import com.google.protobuf.UnittestLite.TestAllTypesLite; +import com.google.protobuf.UnittestLite.TestPackedExtensionsLite; +import com.google.protobuf.test.UnittestImport.ImportEnum; +import com.google.protobuf.test.UnittestImport.ImportMessage; +import com.google.protobuf.test.UnittestImportPublic.PublicImportMessage; +import protobuf_unittest.UnittestProto; +import protobuf_unittest.UnittestProto.ForeignEnum; +import protobuf_unittest.UnittestProto.ForeignMessage; +import protobuf_unittest.UnittestProto.OptionalGroup_extension; +import protobuf_unittest.UnittestProto.RepeatedGroup_extension; +import protobuf_unittest.UnittestProto.TestAllExtensions; +import protobuf_unittest.UnittestProto.TestAllExtensionsOrBuilder; +import protobuf_unittest.UnittestProto.TestAllTypes; +import protobuf_unittest.UnittestProto.TestAllTypesOrBuilder; +import protobuf_unittest.UnittestProto.TestOneof2; +import protobuf_unittest.UnittestProto.TestPackedExtensions; +import protobuf_unittest.UnittestProto.TestPackedTypes; +import protobuf_unittest.UnittestProto.TestRequired; +import protobuf_unittest.UnittestProto.TestUnpackedTypes; +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.logging.Handler; +import java.util.logging.LogRecord; +import junit.framework.Assert; + +/** + * Contains methods for setting all fields of {@code TestAllTypes} to some values as well as + * checking that all the fields are set to those values. These are useful for testing various + * protocol message features, e.g. set all fields of a message, serialize it, parse it, and check + * that all fields are set. + * + *

This code is not to be used outside of {@code com.google.protobuf} and subpackages. + * + * @author kenton@google.com Kenton Varda + */ +public final class TestUtil { + private TestUtil() {} + + public static final TestRequired TEST_REQUIRED_UNINITIALIZED = + TestRequired.newBuilder().setA(1).buildPartial(); + public static final TestRequired TEST_REQUIRED_INITIALIZED = + TestRequired.newBuilder().setA(1).setB(2).setC(3).build(); + + /** Helper to convert a String to ByteString. */ + public static ByteString toBytes(String str) { + return ByteString.copyFromUtf8(str); + } + + // BEGIN FULL-RUNTIME + /** Dirties the message by resetting the momoized serialized size. */ + public static void resetMemoizedSize(AbstractMessage message) { + message.memoizedSize = -1; + } + // END FULL-RUNTIME + + /** + * Get a {@code TestAllTypes} with all fields set as they would be by {@link + * #setAllFields(TestAllTypes.Builder)}. + */ + public static TestAllTypes getAllSet() { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + setAllFields(builder); + return builder.build(); + } + + /** + * Get a {@code TestAllTypes.Builder} with all fields set as they would be by {@link + * #setAllFields(TestAllTypes.Builder)}. + */ + public static TestAllTypes.Builder getAllSetBuilder() { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + setAllFields(builder); + return builder; + } + + /** + * Get a {@code TestAllExtensions} with all fields set as they would be by {@link + * #setAllExtensions(TestAllExtensions.Builder)}. + */ + public static TestAllExtensions getAllExtensionsSet() { + TestAllExtensions.Builder builder = TestAllExtensions.newBuilder(); + setAllExtensions(builder); + return builder.build(); + } + + public static TestPackedTypes getPackedSet() { + TestPackedTypes.Builder builder = TestPackedTypes.newBuilder(); + setPackedFields(builder); + return builder.build(); + } + + public static TestUnpackedTypes getUnpackedSet() { + TestUnpackedTypes.Builder builder = TestUnpackedTypes.newBuilder(); + setUnpackedFields(builder); + return builder.build(); + } + + public static TestPackedExtensions getPackedExtensionsSet() { + TestPackedExtensions.Builder builder = TestPackedExtensions.newBuilder(); + setPackedExtensions(builder); + return builder.build(); + } + + /** Set every field of {@code message} to the values expected by {@code assertAllFieldsSet()}. */ + public static void setAllFields(TestAllTypes.Builder message) { + message.setOptionalInt32(101); + message.setOptionalInt64(102); + message.setOptionalUint32(103); + message.setOptionalUint64(104); + message.setOptionalSint32(105); + message.setOptionalSint64(106); + message.setOptionalFixed32(107); + message.setOptionalFixed64(108); + message.setOptionalSfixed32(109); + message.setOptionalSfixed64(110); + message.setOptionalFloat(111); + message.setOptionalDouble(112); + message.setOptionalBool(true); + message.setOptionalString("115"); + message.setOptionalBytes(toBytes("116")); + + message.setOptionalGroup(TestAllTypes.OptionalGroup.newBuilder().setA(117).build()); + message.setOptionalNestedMessage(TestAllTypes.NestedMessage.newBuilder().setBb(118).build()); + message.setOptionalForeignMessage(ForeignMessage.newBuilder().setC(119).build()); + message.setOptionalImportMessage(ImportMessage.newBuilder().setD(120).build()); + message.setOptionalPublicImportMessage(PublicImportMessage.newBuilder().setE(126).build()); + message.setOptionalLazyMessage(TestAllTypes.NestedMessage.newBuilder().setBb(127).build()); + + message.setOptionalNestedEnum(TestAllTypes.NestedEnum.BAZ); + message.setOptionalForeignEnum(ForeignEnum.FOREIGN_BAZ); + message.setOptionalImportEnum(ImportEnum.IMPORT_BAZ); + + message.setOptionalStringPiece("124"); + message.setOptionalCord("125"); + + // ----------------------------------------------------------------- + + message.addRepeatedInt32(201); + message.addRepeatedInt64(202); + message.addRepeatedUint32(203); + message.addRepeatedUint64(204); + message.addRepeatedSint32(205); + message.addRepeatedSint64(206); + message.addRepeatedFixed32(207); + message.addRepeatedFixed64(208); + message.addRepeatedSfixed32(209); + message.addRepeatedSfixed64(210); + message.addRepeatedFloat(211); + message.addRepeatedDouble(212); + message.addRepeatedBool(true); + message.addRepeatedString("215"); + message.addRepeatedBytes(toBytes("216")); + + message.addRepeatedGroup(TestAllTypes.RepeatedGroup.newBuilder().setA(217).build()); + message.addRepeatedNestedMessage(TestAllTypes.NestedMessage.newBuilder().setBb(218).build()); + message.addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(219).build()); + message.addRepeatedImportMessage(ImportMessage.newBuilder().setD(220).build()); + message.addRepeatedLazyMessage(TestAllTypes.NestedMessage.newBuilder().setBb(227).build()); + + message.addRepeatedNestedEnum(TestAllTypes.NestedEnum.BAR); + message.addRepeatedForeignEnum(ForeignEnum.FOREIGN_BAR); + message.addRepeatedImportEnum(ImportEnum.IMPORT_BAR); + + message.addRepeatedStringPiece("224"); + message.addRepeatedCord("225"); + + // Add a second one of each field. + message.addRepeatedInt32(301); + message.addRepeatedInt64(302); + message.addRepeatedUint32(303); + message.addRepeatedUint64(304); + message.addRepeatedSint32(305); + message.addRepeatedSint64(306); + message.addRepeatedFixed32(307); + message.addRepeatedFixed64(308); + message.addRepeatedSfixed32(309); + message.addRepeatedSfixed64(310); + message.addRepeatedFloat(311); + message.addRepeatedDouble(312); + message.addRepeatedBool(false); + message.addRepeatedString("315"); + message.addRepeatedBytes(toBytes("316")); + + message.addRepeatedGroup(TestAllTypes.RepeatedGroup.newBuilder().setA(317).build()); + message.addRepeatedNestedMessage(TestAllTypes.NestedMessage.newBuilder().setBb(318).build()); + message.addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(319).build()); + message.addRepeatedImportMessage(ImportMessage.newBuilder().setD(320).build()); + message.addRepeatedLazyMessage(TestAllTypes.NestedMessage.newBuilder().setBb(327).build()); + + message.addRepeatedNestedEnum(TestAllTypes.NestedEnum.BAZ); + message.addRepeatedForeignEnum(ForeignEnum.FOREIGN_BAZ); + message.addRepeatedImportEnum(ImportEnum.IMPORT_BAZ); + + message.addRepeatedStringPiece("324"); + message.addRepeatedCord("325"); + + // ----------------------------------------------------------------- + + message.setDefaultInt32(401); + message.setDefaultInt64(402); + message.setDefaultUint32(403); + message.setDefaultUint64(404); + message.setDefaultSint32(405); + message.setDefaultSint64(406); + message.setDefaultFixed32(407); + message.setDefaultFixed64(408); + message.setDefaultSfixed32(409); + message.setDefaultSfixed64(410); + message.setDefaultFloat(411); + message.setDefaultDouble(412); + message.setDefaultBool(false); + message.setDefaultString("415"); + message.setDefaultBytes(toBytes("416")); + + message.setDefaultNestedEnum(TestAllTypes.NestedEnum.FOO); + message.setDefaultForeignEnum(ForeignEnum.FOREIGN_FOO); + message.setDefaultImportEnum(ImportEnum.IMPORT_FOO); + + message.setDefaultStringPiece("424"); + message.setDefaultCord("425"); + + message.setOneofUint32(601); + message.setOneofNestedMessage(TestAllTypes.NestedMessage.newBuilder().setBb(602).build()); + message.setOneofString("603"); + message.setOneofBytes(toBytes("604")); + } + + // ------------------------------------------------------------------- + + /** + * Modify the repeated fields of {@code message} to contain the values expected by {@code + * assertRepeatedFieldsModified()}. + */ + public static void modifyRepeatedFields(TestAllTypes.Builder message) { + message.setRepeatedInt32(1, 501); + message.setRepeatedInt64(1, 502); + message.setRepeatedUint32(1, 503); + message.setRepeatedUint64(1, 504); + message.setRepeatedSint32(1, 505); + message.setRepeatedSint64(1, 506); + message.setRepeatedFixed32(1, 507); + message.setRepeatedFixed64(1, 508); + message.setRepeatedSfixed32(1, 509); + message.setRepeatedSfixed64(1, 510); + message.setRepeatedFloat(1, 511); + message.setRepeatedDouble(1, 512); + message.setRepeatedBool(1, true); + message.setRepeatedString(1, "515"); + message.setRepeatedBytes(1, toBytes("516")); + + message.setRepeatedGroup(1, TestAllTypes.RepeatedGroup.newBuilder().setA(517).build()); + message.setRepeatedNestedMessage(1, TestAllTypes.NestedMessage.newBuilder().setBb(518).build()); + message.setRepeatedForeignMessage(1, ForeignMessage.newBuilder().setC(519).build()); + message.setRepeatedImportMessage(1, ImportMessage.newBuilder().setD(520).build()); + message.setRepeatedLazyMessage(1, TestAllTypes.NestedMessage.newBuilder().setBb(527).build()); + + message.setRepeatedNestedEnum(1, TestAllTypes.NestedEnum.FOO); + message.setRepeatedForeignEnum(1, ForeignEnum.FOREIGN_FOO); + message.setRepeatedImportEnum(1, ImportEnum.IMPORT_FOO); + + message.setRepeatedStringPiece(1, "524"); + message.setRepeatedCord(1, "525"); + } + + // ------------------------------------------------------------------- + + /** + * Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are set to the + * values assigned by {@code setAllFields}. + */ + public static void assertAllFieldsSet(TestAllTypesOrBuilder message) { + Assert.assertTrue(message.hasOptionalInt32()); + Assert.assertTrue(message.hasOptionalInt64()); + Assert.assertTrue(message.hasOptionalUint32()); + Assert.assertTrue(message.hasOptionalUint64()); + Assert.assertTrue(message.hasOptionalSint32()); + Assert.assertTrue(message.hasOptionalSint64()); + Assert.assertTrue(message.hasOptionalFixed32()); + Assert.assertTrue(message.hasOptionalFixed64()); + Assert.assertTrue(message.hasOptionalSfixed32()); + Assert.assertTrue(message.hasOptionalSfixed64()); + Assert.assertTrue(message.hasOptionalFloat()); + Assert.assertTrue(message.hasOptionalDouble()); + Assert.assertTrue(message.hasOptionalBool()); + Assert.assertTrue(message.hasOptionalString()); + Assert.assertTrue(message.hasOptionalBytes()); + + Assert.assertTrue(message.hasOptionalGroup()); + Assert.assertTrue(message.hasOptionalNestedMessage()); + Assert.assertTrue(message.hasOptionalForeignMessage()); + Assert.assertTrue(message.hasOptionalImportMessage()); + + Assert.assertTrue(message.getOptionalGroup().hasA()); + Assert.assertTrue(message.getOptionalNestedMessage().hasBb()); + Assert.assertTrue(message.getOptionalForeignMessage().hasC()); + Assert.assertTrue(message.getOptionalImportMessage().hasD()); + + Assert.assertTrue(message.hasOptionalNestedEnum()); + Assert.assertTrue(message.hasOptionalForeignEnum()); + Assert.assertTrue(message.hasOptionalImportEnum()); + + Assert.assertTrue(message.hasOptionalStringPiece()); + Assert.assertTrue(message.hasOptionalCord()); + + Assert.assertEquals(101, message.getOptionalInt32()); + Assert.assertEquals(102, message.getOptionalInt64()); + Assert.assertEquals(103, message.getOptionalUint32()); + Assert.assertEquals(104, message.getOptionalUint64()); + Assert.assertEquals(105, message.getOptionalSint32()); + Assert.assertEquals(106, message.getOptionalSint64()); + Assert.assertEquals(107, message.getOptionalFixed32()); + Assert.assertEquals(108, message.getOptionalFixed64()); + Assert.assertEquals(109, message.getOptionalSfixed32()); + Assert.assertEquals(110, message.getOptionalSfixed64()); + Assert.assertEquals(111, message.getOptionalFloat(), 0.0); + Assert.assertEquals(112, message.getOptionalDouble(), 0.0); + Assert.assertEquals(true, message.getOptionalBool()); + Assert.assertEquals("115", message.getOptionalString()); + Assert.assertEquals(toBytes("116"), message.getOptionalBytes()); + + Assert.assertEquals(117, message.getOptionalGroup().getA()); + Assert.assertEquals(118, message.getOptionalNestedMessage().getBb()); + Assert.assertEquals(119, message.getOptionalForeignMessage().getC()); + Assert.assertEquals(120, message.getOptionalImportMessage().getD()); + Assert.assertEquals(126, message.getOptionalPublicImportMessage().getE()); + Assert.assertEquals(127, message.getOptionalLazyMessage().getBb()); + + Assert.assertEquals(TestAllTypes.NestedEnum.BAZ, message.getOptionalNestedEnum()); + Assert.assertEquals(ForeignEnum.FOREIGN_BAZ, message.getOptionalForeignEnum()); + Assert.assertEquals(ImportEnum.IMPORT_BAZ, message.getOptionalImportEnum()); + + Assert.assertEquals("124", message.getOptionalStringPiece()); + Assert.assertEquals("125", message.getOptionalCord()); + + // ----------------------------------------------------------------- + + Assert.assertEquals(2, message.getRepeatedInt32Count()); + Assert.assertEquals(2, message.getRepeatedInt64Count()); + Assert.assertEquals(2, message.getRepeatedUint32Count()); + Assert.assertEquals(2, message.getRepeatedUint64Count()); + Assert.assertEquals(2, message.getRepeatedSint32Count()); + Assert.assertEquals(2, message.getRepeatedSint64Count()); + Assert.assertEquals(2, message.getRepeatedFixed32Count()); + Assert.assertEquals(2, message.getRepeatedFixed64Count()); + Assert.assertEquals(2, message.getRepeatedSfixed32Count()); + Assert.assertEquals(2, message.getRepeatedSfixed64Count()); + Assert.assertEquals(2, message.getRepeatedFloatCount()); + Assert.assertEquals(2, message.getRepeatedDoubleCount()); + Assert.assertEquals(2, message.getRepeatedBoolCount()); + Assert.assertEquals(2, message.getRepeatedStringCount()); + Assert.assertEquals(2, message.getRepeatedBytesCount()); + + Assert.assertEquals(2, message.getRepeatedGroupCount()); + Assert.assertEquals(2, message.getRepeatedNestedMessageCount()); + Assert.assertEquals(2, message.getRepeatedForeignMessageCount()); + Assert.assertEquals(2, message.getRepeatedImportMessageCount()); + Assert.assertEquals(2, message.getRepeatedLazyMessageCount()); + Assert.assertEquals(2, message.getRepeatedNestedEnumCount()); + Assert.assertEquals(2, message.getRepeatedForeignEnumCount()); + Assert.assertEquals(2, message.getRepeatedImportEnumCount()); + + Assert.assertEquals(2, message.getRepeatedStringPieceCount()); + Assert.assertEquals(2, message.getRepeatedCordCount()); + + Assert.assertEquals(201, message.getRepeatedInt32(0)); + Assert.assertEquals(202, message.getRepeatedInt64(0)); + Assert.assertEquals(203, message.getRepeatedUint32(0)); + Assert.assertEquals(204, message.getRepeatedUint64(0)); + Assert.assertEquals(205, message.getRepeatedSint32(0)); + Assert.assertEquals(206, message.getRepeatedSint64(0)); + Assert.assertEquals(207, message.getRepeatedFixed32(0)); + Assert.assertEquals(208, message.getRepeatedFixed64(0)); + Assert.assertEquals(209, message.getRepeatedSfixed32(0)); + Assert.assertEquals(210, message.getRepeatedSfixed64(0)); + Assert.assertEquals(211, message.getRepeatedFloat(0), 0.0); + Assert.assertEquals(212, message.getRepeatedDouble(0), 0.0); + Assert.assertEquals(true, message.getRepeatedBool(0)); + Assert.assertEquals("215", message.getRepeatedString(0)); + Assert.assertEquals(toBytes("216"), message.getRepeatedBytes(0)); + + Assert.assertEquals(217, message.getRepeatedGroup(0).getA()); + Assert.assertEquals(218, message.getRepeatedNestedMessage(0).getBb()); + Assert.assertEquals(219, message.getRepeatedForeignMessage(0).getC()); + Assert.assertEquals(220, message.getRepeatedImportMessage(0).getD()); + Assert.assertEquals(227, message.getRepeatedLazyMessage(0).getBb()); + + Assert.assertEquals(TestAllTypes.NestedEnum.BAR, message.getRepeatedNestedEnum(0)); + Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getRepeatedForeignEnum(0)); + Assert.assertEquals(ImportEnum.IMPORT_BAR, message.getRepeatedImportEnum(0)); + + Assert.assertEquals("224", message.getRepeatedStringPiece(0)); + Assert.assertEquals("225", message.getRepeatedCord(0)); + + Assert.assertEquals(301, message.getRepeatedInt32(1)); + Assert.assertEquals(302, message.getRepeatedInt64(1)); + Assert.assertEquals(303, message.getRepeatedUint32(1)); + Assert.assertEquals(304, message.getRepeatedUint64(1)); + Assert.assertEquals(305, message.getRepeatedSint32(1)); + Assert.assertEquals(306, message.getRepeatedSint64(1)); + Assert.assertEquals(307, message.getRepeatedFixed32(1)); + Assert.assertEquals(308, message.getRepeatedFixed64(1)); + Assert.assertEquals(309, message.getRepeatedSfixed32(1)); + Assert.assertEquals(310, message.getRepeatedSfixed64(1)); + Assert.assertEquals(311, message.getRepeatedFloat(1), 0.0); + Assert.assertEquals(312, message.getRepeatedDouble(1), 0.0); + Assert.assertEquals(false, message.getRepeatedBool(1)); + Assert.assertEquals("315", message.getRepeatedString(1)); + Assert.assertEquals(toBytes("316"), message.getRepeatedBytes(1)); + + Assert.assertEquals(317, message.getRepeatedGroup(1).getA()); + Assert.assertEquals(318, message.getRepeatedNestedMessage(1).getBb()); + Assert.assertEquals(319, message.getRepeatedForeignMessage(1).getC()); + Assert.assertEquals(320, message.getRepeatedImportMessage(1).getD()); + Assert.assertEquals(327, message.getRepeatedLazyMessage(1).getBb()); + + Assert.assertEquals(TestAllTypes.NestedEnum.BAZ, message.getRepeatedNestedEnum(1)); + Assert.assertEquals(ForeignEnum.FOREIGN_BAZ, message.getRepeatedForeignEnum(1)); + Assert.assertEquals(ImportEnum.IMPORT_BAZ, message.getRepeatedImportEnum(1)); + + Assert.assertEquals("324", message.getRepeatedStringPiece(1)); + Assert.assertEquals("325", message.getRepeatedCord(1)); + + // ----------------------------------------------------------------- + + Assert.assertTrue(message.hasDefaultInt32()); + Assert.assertTrue(message.hasDefaultInt64()); + Assert.assertTrue(message.hasDefaultUint32()); + Assert.assertTrue(message.hasDefaultUint64()); + Assert.assertTrue(message.hasDefaultSint32()); + Assert.assertTrue(message.hasDefaultSint64()); + Assert.assertTrue(message.hasDefaultFixed32()); + Assert.assertTrue(message.hasDefaultFixed64()); + Assert.assertTrue(message.hasDefaultSfixed32()); + Assert.assertTrue(message.hasDefaultSfixed64()); + Assert.assertTrue(message.hasDefaultFloat()); + Assert.assertTrue(message.hasDefaultDouble()); + Assert.assertTrue(message.hasDefaultBool()); + Assert.assertTrue(message.hasDefaultString()); + Assert.assertTrue(message.hasDefaultBytes()); + + Assert.assertTrue(message.hasDefaultNestedEnum()); + Assert.assertTrue(message.hasDefaultForeignEnum()); + Assert.assertTrue(message.hasDefaultImportEnum()); + + Assert.assertTrue(message.hasDefaultStringPiece()); + Assert.assertTrue(message.hasDefaultCord()); + + Assert.assertEquals(401, message.getDefaultInt32()); + Assert.assertEquals(402, message.getDefaultInt64()); + Assert.assertEquals(403, message.getDefaultUint32()); + Assert.assertEquals(404, message.getDefaultUint64()); + Assert.assertEquals(405, message.getDefaultSint32()); + Assert.assertEquals(406, message.getDefaultSint64()); + Assert.assertEquals(407, message.getDefaultFixed32()); + Assert.assertEquals(408, message.getDefaultFixed64()); + Assert.assertEquals(409, message.getDefaultSfixed32()); + Assert.assertEquals(410, message.getDefaultSfixed64()); + Assert.assertEquals(411, message.getDefaultFloat(), 0.0); + Assert.assertEquals(412, message.getDefaultDouble(), 0.0); + Assert.assertEquals(false, message.getDefaultBool()); + Assert.assertEquals("415", message.getDefaultString()); + Assert.assertEquals(toBytes("416"), message.getDefaultBytes()); + + Assert.assertEquals(TestAllTypes.NestedEnum.FOO, message.getDefaultNestedEnum()); + Assert.assertEquals(ForeignEnum.FOREIGN_FOO, message.getDefaultForeignEnum()); + Assert.assertEquals(ImportEnum.IMPORT_FOO, message.getDefaultImportEnum()); + + Assert.assertEquals("424", message.getDefaultStringPiece()); + Assert.assertEquals("425", message.getDefaultCord()); + + Assert.assertEquals(TestAllTypes.OneofFieldCase.ONEOF_BYTES, message.getOneofFieldCase()); + Assert.assertFalse(message.hasOneofUint32()); + Assert.assertFalse(message.hasOneofNestedMessage()); + Assert.assertFalse(message.hasOneofString()); + Assert.assertTrue(message.hasOneofBytes()); + + Assert.assertEquals(toBytes("604"), message.getOneofBytes()); + } + + // ------------------------------------------------------------------- + /** + * Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are cleared, + * and that getting the fields returns their default values. + */ + public static void assertClear(TestAllTypesOrBuilder message) { + // hasBlah() should initially be false for all optional fields. + Assert.assertFalse(message.hasOptionalInt32()); + Assert.assertFalse(message.hasOptionalInt64()); + Assert.assertFalse(message.hasOptionalUint32()); + Assert.assertFalse(message.hasOptionalUint64()); + Assert.assertFalse(message.hasOptionalSint32()); + Assert.assertFalse(message.hasOptionalSint64()); + Assert.assertFalse(message.hasOptionalFixed32()); + Assert.assertFalse(message.hasOptionalFixed64()); + Assert.assertFalse(message.hasOptionalSfixed32()); + Assert.assertFalse(message.hasOptionalSfixed64()); + Assert.assertFalse(message.hasOptionalFloat()); + Assert.assertFalse(message.hasOptionalDouble()); + Assert.assertFalse(message.hasOptionalBool()); + Assert.assertFalse(message.hasOptionalString()); + Assert.assertFalse(message.hasOptionalBytes()); + + Assert.assertFalse(message.hasOptionalGroup()); + Assert.assertFalse(message.hasOptionalNestedMessage()); + Assert.assertFalse(message.hasOptionalForeignMessage()); + Assert.assertFalse(message.hasOptionalImportMessage()); + + Assert.assertFalse(message.hasOptionalNestedEnum()); + Assert.assertFalse(message.hasOptionalForeignEnum()); + Assert.assertFalse(message.hasOptionalImportEnum()); + + Assert.assertFalse(message.hasOptionalStringPiece()); + Assert.assertFalse(message.hasOptionalCord()); + + // Optional fields without defaults are set to zero or something like it. + Assert.assertEquals(0, message.getOptionalInt32()); + Assert.assertEquals(0, message.getOptionalInt64()); + Assert.assertEquals(0, message.getOptionalUint32()); + Assert.assertEquals(0, message.getOptionalUint64()); + Assert.assertEquals(0, message.getOptionalSint32()); + Assert.assertEquals(0, message.getOptionalSint64()); + Assert.assertEquals(0, message.getOptionalFixed32()); + Assert.assertEquals(0, message.getOptionalFixed64()); + Assert.assertEquals(0, message.getOptionalSfixed32()); + Assert.assertEquals(0, message.getOptionalSfixed64()); + Assert.assertEquals(0, message.getOptionalFloat(), 0.0); + Assert.assertEquals(0, message.getOptionalDouble(), 0.0); + Assert.assertEquals(false, message.getOptionalBool()); + Assert.assertEquals("", message.getOptionalString()); + Assert.assertEquals(ByteString.EMPTY, message.getOptionalBytes()); + + // Embedded messages should also be clear. + Assert.assertFalse(message.getOptionalGroup().hasA()); + Assert.assertFalse(message.getOptionalNestedMessage().hasBb()); + Assert.assertFalse(message.getOptionalForeignMessage().hasC()); + Assert.assertFalse(message.getOptionalImportMessage().hasD()); + Assert.assertFalse(message.getOptionalPublicImportMessage().hasE()); + Assert.assertFalse(message.getOptionalLazyMessage().hasBb()); + + Assert.assertEquals(0, message.getOptionalGroup().getA()); + Assert.assertEquals(0, message.getOptionalNestedMessage().getBb()); + Assert.assertEquals(0, message.getOptionalForeignMessage().getC()); + Assert.assertEquals(0, message.getOptionalImportMessage().getD()); + Assert.assertEquals(0, message.getOptionalPublicImportMessage().getE()); + Assert.assertEquals(0, message.getOptionalLazyMessage().getBb()); + + // Enums without defaults are set to the first value in the enum. + Assert.assertEquals(TestAllTypes.NestedEnum.FOO, message.getOptionalNestedEnum()); + Assert.assertEquals(ForeignEnum.FOREIGN_FOO, message.getOptionalForeignEnum()); + Assert.assertEquals(ImportEnum.IMPORT_FOO, message.getOptionalImportEnum()); + + Assert.assertEquals("", message.getOptionalStringPiece()); + Assert.assertEquals("", message.getOptionalCord()); + + // Repeated fields are empty. + Assert.assertEquals(0, message.getRepeatedInt32Count()); + Assert.assertEquals(0, message.getRepeatedInt64Count()); + Assert.assertEquals(0, message.getRepeatedUint32Count()); + Assert.assertEquals(0, message.getRepeatedUint64Count()); + Assert.assertEquals(0, message.getRepeatedSint32Count()); + Assert.assertEquals(0, message.getRepeatedSint64Count()); + Assert.assertEquals(0, message.getRepeatedFixed32Count()); + Assert.assertEquals(0, message.getRepeatedFixed64Count()); + Assert.assertEquals(0, message.getRepeatedSfixed32Count()); + Assert.assertEquals(0, message.getRepeatedSfixed64Count()); + Assert.assertEquals(0, message.getRepeatedFloatCount()); + Assert.assertEquals(0, message.getRepeatedDoubleCount()); + Assert.assertEquals(0, message.getRepeatedBoolCount()); + Assert.assertEquals(0, message.getRepeatedStringCount()); + Assert.assertEquals(0, message.getRepeatedBytesCount()); + + Assert.assertEquals(0, message.getRepeatedGroupCount()); + Assert.assertEquals(0, message.getRepeatedNestedMessageCount()); + Assert.assertEquals(0, message.getRepeatedForeignMessageCount()); + Assert.assertEquals(0, message.getRepeatedImportMessageCount()); + Assert.assertEquals(0, message.getRepeatedLazyMessageCount()); + Assert.assertEquals(0, message.getRepeatedNestedEnumCount()); + Assert.assertEquals(0, message.getRepeatedForeignEnumCount()); + Assert.assertEquals(0, message.getRepeatedImportEnumCount()); + + Assert.assertEquals(0, message.getRepeatedStringPieceCount()); + Assert.assertEquals(0, message.getRepeatedCordCount()); + + // hasBlah() should also be false for all default fields. + Assert.assertFalse(message.hasDefaultInt32()); + Assert.assertFalse(message.hasDefaultInt64()); + Assert.assertFalse(message.hasDefaultUint32()); + Assert.assertFalse(message.hasDefaultUint64()); + Assert.assertFalse(message.hasDefaultSint32()); + Assert.assertFalse(message.hasDefaultSint64()); + Assert.assertFalse(message.hasDefaultFixed32()); + Assert.assertFalse(message.hasDefaultFixed64()); + Assert.assertFalse(message.hasDefaultSfixed32()); + Assert.assertFalse(message.hasDefaultSfixed64()); + Assert.assertFalse(message.hasDefaultFloat()); + Assert.assertFalse(message.hasDefaultDouble()); + Assert.assertFalse(message.hasDefaultBool()); + Assert.assertFalse(message.hasDefaultString()); + Assert.assertFalse(message.hasDefaultBytes()); + + Assert.assertFalse(message.hasDefaultNestedEnum()); + Assert.assertFalse(message.hasDefaultForeignEnum()); + Assert.assertFalse(message.hasDefaultImportEnum()); + + Assert.assertFalse(message.hasDefaultStringPiece()); + Assert.assertFalse(message.hasDefaultCord()); + + // Fields with defaults have their default values (duh). + Assert.assertEquals(41, message.getDefaultInt32()); + Assert.assertEquals(42, message.getDefaultInt64()); + Assert.assertEquals(43, message.getDefaultUint32()); + Assert.assertEquals(44, message.getDefaultUint64()); + Assert.assertEquals(-45, message.getDefaultSint32()); + Assert.assertEquals(46, message.getDefaultSint64()); + Assert.assertEquals(47, message.getDefaultFixed32()); + Assert.assertEquals(48, message.getDefaultFixed64()); + Assert.assertEquals(49, message.getDefaultSfixed32()); + Assert.assertEquals(-50, message.getDefaultSfixed64()); + Assert.assertEquals(51.5, message.getDefaultFloat(), 0.0); + Assert.assertEquals(52e3, message.getDefaultDouble(), 0.0); + Assert.assertEquals(true, message.getDefaultBool()); + Assert.assertEquals("hello", message.getDefaultString()); + Assert.assertEquals(toBytes("world"), message.getDefaultBytes()); + + Assert.assertEquals(TestAllTypes.NestedEnum.BAR, message.getDefaultNestedEnum()); + Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getDefaultForeignEnum()); + Assert.assertEquals(ImportEnum.IMPORT_BAR, message.getDefaultImportEnum()); + + Assert.assertEquals("abc", message.getDefaultStringPiece()); + Assert.assertEquals("123", message.getDefaultCord()); + + Assert.assertFalse(message.hasOneofUint32()); + Assert.assertFalse(message.hasOneofNestedMessage()); + Assert.assertFalse(message.hasOneofString()); + Assert.assertFalse(message.hasOneofBytes()); + } + + // ------------------------------------------------------------------- + + /** + * Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are set to the + * values assigned by {@code setAllFields} followed by {@code modifyRepeatedFields}. + */ + public static void assertRepeatedFieldsModified(TestAllTypesOrBuilder 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.assertEquals(2, message.getRepeatedInt32Count()); + Assert.assertEquals(2, message.getRepeatedInt64Count()); + Assert.assertEquals(2, message.getRepeatedUint32Count()); + Assert.assertEquals(2, message.getRepeatedUint64Count()); + Assert.assertEquals(2, message.getRepeatedSint32Count()); + Assert.assertEquals(2, message.getRepeatedSint64Count()); + Assert.assertEquals(2, message.getRepeatedFixed32Count()); + Assert.assertEquals(2, message.getRepeatedFixed64Count()); + Assert.assertEquals(2, message.getRepeatedSfixed32Count()); + Assert.assertEquals(2, message.getRepeatedSfixed64Count()); + Assert.assertEquals(2, message.getRepeatedFloatCount()); + Assert.assertEquals(2, message.getRepeatedDoubleCount()); + Assert.assertEquals(2, message.getRepeatedBoolCount()); + Assert.assertEquals(2, message.getRepeatedStringCount()); + Assert.assertEquals(2, message.getRepeatedBytesCount()); + + Assert.assertEquals(2, message.getRepeatedGroupCount()); + Assert.assertEquals(2, message.getRepeatedNestedMessageCount()); + Assert.assertEquals(2, message.getRepeatedForeignMessageCount()); + Assert.assertEquals(2, message.getRepeatedImportMessageCount()); + Assert.assertEquals(2, message.getRepeatedLazyMessageCount()); + Assert.assertEquals(2, message.getRepeatedNestedEnumCount()); + Assert.assertEquals(2, message.getRepeatedForeignEnumCount()); + Assert.assertEquals(2, message.getRepeatedImportEnumCount()); + + Assert.assertEquals(2, message.getRepeatedStringPieceCount()); + Assert.assertEquals(2, message.getRepeatedCordCount()); + + Assert.assertEquals(201, message.getRepeatedInt32(0)); + Assert.assertEquals(202L, message.getRepeatedInt64(0)); + Assert.assertEquals(203, message.getRepeatedUint32(0)); + Assert.assertEquals(204L, message.getRepeatedUint64(0)); + Assert.assertEquals(205, message.getRepeatedSint32(0)); + Assert.assertEquals(206L, message.getRepeatedSint64(0)); + Assert.assertEquals(207, message.getRepeatedFixed32(0)); + Assert.assertEquals(208L, message.getRepeatedFixed64(0)); + Assert.assertEquals(209, message.getRepeatedSfixed32(0)); + Assert.assertEquals(210L, message.getRepeatedSfixed64(0)); + Assert.assertEquals(211F, message.getRepeatedFloat(0)); + Assert.assertEquals(212D, message.getRepeatedDouble(0)); + Assert.assertEquals(true, message.getRepeatedBool(0)); + Assert.assertEquals("215", message.getRepeatedString(0)); + Assert.assertEquals(toBytes("216"), message.getRepeatedBytes(0)); + + Assert.assertEquals(217, message.getRepeatedGroup(0).getA()); + Assert.assertEquals(218, message.getRepeatedNestedMessage(0).getBb()); + Assert.assertEquals(219, message.getRepeatedForeignMessage(0).getC()); + Assert.assertEquals(220, message.getRepeatedImportMessage(0).getD()); + Assert.assertEquals(227, message.getRepeatedLazyMessage(0).getBb()); + + Assert.assertEquals(TestAllTypes.NestedEnum.BAR, message.getRepeatedNestedEnum(0)); + Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getRepeatedForeignEnum(0)); + Assert.assertEquals(ImportEnum.IMPORT_BAR, message.getRepeatedImportEnum(0)); + + Assert.assertEquals("224", message.getRepeatedStringPiece(0)); + Assert.assertEquals("225", message.getRepeatedCord(0)); + + // Actually verify the second (modified) elements now. + Assert.assertEquals(501, message.getRepeatedInt32(1)); + Assert.assertEquals(502L, message.getRepeatedInt64(1)); + Assert.assertEquals(503, message.getRepeatedUint32(1)); + Assert.assertEquals(504L, message.getRepeatedUint64(1)); + Assert.assertEquals(505, message.getRepeatedSint32(1)); + Assert.assertEquals(506L, message.getRepeatedSint64(1)); + Assert.assertEquals(507, message.getRepeatedFixed32(1)); + Assert.assertEquals(508L, message.getRepeatedFixed64(1)); + Assert.assertEquals(509, message.getRepeatedSfixed32(1)); + Assert.assertEquals(510L, message.getRepeatedSfixed64(1)); + Assert.assertEquals(511F, message.getRepeatedFloat(1)); + Assert.assertEquals(512D, message.getRepeatedDouble(1)); + Assert.assertEquals(true, message.getRepeatedBool(1)); + Assert.assertEquals("515", message.getRepeatedString(1)); + Assert.assertEquals(toBytes("516"), message.getRepeatedBytes(1)); + + Assert.assertEquals(517, message.getRepeatedGroup(1).getA()); + Assert.assertEquals(518, message.getRepeatedNestedMessage(1).getBb()); + Assert.assertEquals(519, message.getRepeatedForeignMessage(1).getC()); + Assert.assertEquals(520, message.getRepeatedImportMessage(1).getD()); + Assert.assertEquals(527, message.getRepeatedLazyMessage(1).getBb()); + + Assert.assertEquals(TestAllTypes.NestedEnum.FOO, message.getRepeatedNestedEnum(1)); + Assert.assertEquals(ForeignEnum.FOREIGN_FOO, message.getRepeatedForeignEnum(1)); + Assert.assertEquals(ImportEnum.IMPORT_FOO, message.getRepeatedImportEnum(1)); + + Assert.assertEquals("524", message.getRepeatedStringPiece(1)); + Assert.assertEquals("525", message.getRepeatedCord(1)); + } + + /** Set every field of {@code message} to a unique value. */ + public static void setPackedFields(TestPackedTypes.Builder message) { + message.addPackedInt32(601); + message.addPackedInt64(602); + message.addPackedUint32(603); + message.addPackedUint64(604); + message.addPackedSint32(605); + message.addPackedSint64(606); + message.addPackedFixed32(607); + message.addPackedFixed64(608); + message.addPackedSfixed32(609); + message.addPackedSfixed64(610); + message.addPackedFloat(611); + message.addPackedDouble(612); + message.addPackedBool(true); + message.addPackedEnum(ForeignEnum.FOREIGN_BAR); + // Add a second one of each field. + message.addPackedInt32(701); + message.addPackedInt64(702); + message.addPackedUint32(703); + message.addPackedUint64(704); + message.addPackedSint32(705); + message.addPackedSint64(706); + message.addPackedFixed32(707); + message.addPackedFixed64(708); + message.addPackedSfixed32(709); + message.addPackedSfixed64(710); + message.addPackedFloat(711); + message.addPackedDouble(712); + message.addPackedBool(false); + message.addPackedEnum(ForeignEnum.FOREIGN_BAZ); + } + + /** + * Set every field of {@code message} to a unique value. Must correspond with the values applied + * by {@code setPackedFields}. + */ + public static void setUnpackedFields(TestUnpackedTypes.Builder message) { + message.addUnpackedInt32(601); + message.addUnpackedInt64(602); + message.addUnpackedUint32(603); + message.addUnpackedUint64(604); + message.addUnpackedSint32(605); + message.addUnpackedSint64(606); + message.addUnpackedFixed32(607); + message.addUnpackedFixed64(608); + message.addUnpackedSfixed32(609); + message.addUnpackedSfixed64(610); + message.addUnpackedFloat(611); + message.addUnpackedDouble(612); + message.addUnpackedBool(true); + message.addUnpackedEnum(ForeignEnum.FOREIGN_BAR); + // Add a second one of each field. + message.addUnpackedInt32(701); + message.addUnpackedInt64(702); + message.addUnpackedUint32(703); + message.addUnpackedUint64(704); + message.addUnpackedSint32(705); + message.addUnpackedSint64(706); + message.addUnpackedFixed32(707); + message.addUnpackedFixed64(708); + message.addUnpackedSfixed32(709); + message.addUnpackedSfixed64(710); + message.addUnpackedFloat(711); + message.addUnpackedDouble(712); + message.addUnpackedBool(false); + message.addUnpackedEnum(ForeignEnum.FOREIGN_BAZ); + } + + /** + * Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are set to the + * values assigned by {@code setPackedFields}. + */ + public static void assertPackedFieldsSet(TestPackedTypes message) { + Assert.assertEquals(2, message.getPackedInt32Count()); + Assert.assertEquals(2, message.getPackedInt64Count()); + Assert.assertEquals(2, message.getPackedUint32Count()); + Assert.assertEquals(2, message.getPackedUint64Count()); + Assert.assertEquals(2, message.getPackedSint32Count()); + Assert.assertEquals(2, message.getPackedSint64Count()); + Assert.assertEquals(2, message.getPackedFixed32Count()); + Assert.assertEquals(2, message.getPackedFixed64Count()); + Assert.assertEquals(2, message.getPackedSfixed32Count()); + Assert.assertEquals(2, message.getPackedSfixed64Count()); + Assert.assertEquals(2, message.getPackedFloatCount()); + Assert.assertEquals(2, message.getPackedDoubleCount()); + Assert.assertEquals(2, message.getPackedBoolCount()); + Assert.assertEquals(2, message.getPackedEnumCount()); + Assert.assertEquals(601, message.getPackedInt32(0)); + Assert.assertEquals(602, message.getPackedInt64(0)); + Assert.assertEquals(603, message.getPackedUint32(0)); + Assert.assertEquals(604, message.getPackedUint64(0)); + Assert.assertEquals(605, message.getPackedSint32(0)); + Assert.assertEquals(606, message.getPackedSint64(0)); + Assert.assertEquals(607, message.getPackedFixed32(0)); + Assert.assertEquals(608, message.getPackedFixed64(0)); + Assert.assertEquals(609, message.getPackedSfixed32(0)); + Assert.assertEquals(610, message.getPackedSfixed64(0)); + Assert.assertEquals(611, message.getPackedFloat(0), 0.0); + Assert.assertEquals(612, message.getPackedDouble(0), 0.0); + Assert.assertEquals(true, message.getPackedBool(0)); + Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getPackedEnum(0)); + Assert.assertEquals(701, message.getPackedInt32(1)); + Assert.assertEquals(702, message.getPackedInt64(1)); + Assert.assertEquals(703, message.getPackedUint32(1)); + Assert.assertEquals(704, message.getPackedUint64(1)); + Assert.assertEquals(705, message.getPackedSint32(1)); + Assert.assertEquals(706, message.getPackedSint64(1)); + Assert.assertEquals(707, message.getPackedFixed32(1)); + Assert.assertEquals(708, message.getPackedFixed64(1)); + Assert.assertEquals(709, message.getPackedSfixed32(1)); + Assert.assertEquals(710, message.getPackedSfixed64(1)); + Assert.assertEquals(711, message.getPackedFloat(1), 0.0); + Assert.assertEquals(712, message.getPackedDouble(1), 0.0); + Assert.assertEquals(false, message.getPackedBool(1)); + Assert.assertEquals(ForeignEnum.FOREIGN_BAZ, message.getPackedEnum(1)); + } + + /** + * Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are set to the + * values assigned by {@code setUnpackedFields}. + */ + public static void assertUnpackedFieldsSet(TestUnpackedTypes message) { + Assert.assertEquals(2, message.getUnpackedInt32Count()); + Assert.assertEquals(2, message.getUnpackedInt64Count()); + Assert.assertEquals(2, message.getUnpackedUint32Count()); + Assert.assertEquals(2, message.getUnpackedUint64Count()); + Assert.assertEquals(2, message.getUnpackedSint32Count()); + Assert.assertEquals(2, message.getUnpackedSint64Count()); + Assert.assertEquals(2, message.getUnpackedFixed32Count()); + Assert.assertEquals(2, message.getUnpackedFixed64Count()); + Assert.assertEquals(2, message.getUnpackedSfixed32Count()); + Assert.assertEquals(2, message.getUnpackedSfixed64Count()); + Assert.assertEquals(2, message.getUnpackedFloatCount()); + Assert.assertEquals(2, message.getUnpackedDoubleCount()); + Assert.assertEquals(2, message.getUnpackedBoolCount()); + Assert.assertEquals(2, message.getUnpackedEnumCount()); + Assert.assertEquals(601, message.getUnpackedInt32(0)); + Assert.assertEquals(602, message.getUnpackedInt64(0)); + Assert.assertEquals(603, message.getUnpackedUint32(0)); + Assert.assertEquals(604, message.getUnpackedUint64(0)); + Assert.assertEquals(605, message.getUnpackedSint32(0)); + Assert.assertEquals(606, message.getUnpackedSint64(0)); + Assert.assertEquals(607, message.getUnpackedFixed32(0)); + Assert.assertEquals(608, message.getUnpackedFixed64(0)); + Assert.assertEquals(609, message.getUnpackedSfixed32(0)); + Assert.assertEquals(610, message.getUnpackedSfixed64(0)); + Assert.assertEquals(611, message.getUnpackedFloat(0), 0.0); + Assert.assertEquals(612, message.getUnpackedDouble(0), 0.0); + Assert.assertEquals(true, message.getUnpackedBool(0)); + Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getUnpackedEnum(0)); + Assert.assertEquals(701, message.getUnpackedInt32(1)); + Assert.assertEquals(702, message.getUnpackedInt64(1)); + Assert.assertEquals(703, message.getUnpackedUint32(1)); + Assert.assertEquals(704, message.getUnpackedUint64(1)); + Assert.assertEquals(705, message.getUnpackedSint32(1)); + Assert.assertEquals(706, message.getUnpackedSint64(1)); + Assert.assertEquals(707, message.getUnpackedFixed32(1)); + Assert.assertEquals(708, message.getUnpackedFixed64(1)); + Assert.assertEquals(709, message.getUnpackedSfixed32(1)); + Assert.assertEquals(710, message.getUnpackedSfixed64(1)); + Assert.assertEquals(711, message.getUnpackedFloat(1), 0.0); + Assert.assertEquals(712, message.getUnpackedDouble(1), 0.0); + Assert.assertEquals(false, message.getUnpackedBool(1)); + Assert.assertEquals(ForeignEnum.FOREIGN_BAZ, message.getUnpackedEnum(1)); + } + + // =================================================================== + // Like above, but for extensions + + // Java gets confused with things like assertEquals(int, Integer): it can't + // decide whether to call assertEquals(int, int) or assertEquals(Object, + // Object). So we define these methods to help it. + private static void assertEqualsExactType(int a, int b) { + Assert.assertEquals(a, b); + } + + private static void assertEqualsExactType(long a, long b) { + Assert.assertEquals(a, b); + } + + private static void assertEqualsExactType(float a, float b) { + Assert.assertEquals(a, b, 0.0); + } + + private static void assertEqualsExactType(double a, double b) { + Assert.assertEquals(a, b, 0.0); + } + + private static void assertEqualsExactType(boolean a, boolean b) { + Assert.assertEquals(a, b); + } + + private static void assertEqualsExactType(String a, String b) { + Assert.assertEquals(a, b); + } + + private static void assertEqualsExactType(ByteString a, ByteString b) { + Assert.assertEquals(a, b); + } + + private static void assertEqualsExactType(TestAllTypes.NestedEnum a, TestAllTypes.NestedEnum b) { + Assert.assertEquals(a, b); + } + + private static void assertEqualsExactType(ForeignEnum a, ForeignEnum b) { + Assert.assertEquals(a, b); + } + + private static void assertEqualsExactType(ImportEnum a, ImportEnum b) { + Assert.assertEquals(a, b); + } + + private static void assertEqualsExactType( + TestAllTypesLite.NestedEnum a, TestAllTypesLite.NestedEnum b) { + Assert.assertEquals(a, b); + } + + private static void assertEqualsExactType(ForeignEnumLite a, ForeignEnumLite b) { + Assert.assertEquals(a, b); + } + + private static void assertEqualsExactType(ImportEnumLite a, ImportEnumLite b) { + Assert.assertEquals(a, b); + } + + /** + * Get an unmodifiable {@link ExtensionRegistry} containing all the extensions of {@code + * TestAllExtensions}. + */ + public static ExtensionRegistryLite getExtensionRegistry() { + ExtensionRegistryLite registry = ExtensionRegistryLite.newInstance(); + registerAllExtensions(registry); + return registry.getUnmodifiable(); + } + + // BEGIN FULL-RUNTIME + /** + * Get an unmodifiable {@link ExtensionRegistry} containing all the extensions of {@code + * TestAllExtensions}. + */ + public static ExtensionRegistry getFullExtensionRegistry() { + ExtensionRegistry registry = ExtensionRegistry.newInstance(); + registerAllExtensions(registry); + return registry.getUnmodifiable(); + } + // END FULL-RUNTIME + + /** + * Register all of {@code TestAllExtensions}'s extensions with the given {@link + * ExtensionRegistry}. + */ + public static void registerAllExtensions(ExtensionRegistryLite registry) { + UnittestProto.registerAllExtensions(registry); + TestUtilLite.registerAllExtensionsLite(registry); + } + + /** + * Set every field of {@code message} to the values expected by {@code assertAllExtensionsSet()}. + */ + public static void setAllExtensions(TestAllExtensions.Builder message) { + message.setExtension(optionalInt32Extension, 101); + message.setExtension(optionalInt64Extension, 102L); + message.setExtension(optionalUint32Extension, 103); + message.setExtension(optionalUint64Extension, 104L); + message.setExtension(optionalSint32Extension, 105); + message.setExtension(optionalSint64Extension, 106L); + message.setExtension(optionalFixed32Extension, 107); + message.setExtension(optionalFixed64Extension, 108L); + message.setExtension(optionalSfixed32Extension, 109); + message.setExtension(optionalSfixed64Extension, 110L); + message.setExtension(optionalFloatExtension, 111F); + message.setExtension(optionalDoubleExtension, 112D); + message.setExtension(optionalBoolExtension, true); + message.setExtension(optionalStringExtension, "115"); + message.setExtension(optionalBytesExtension, toBytes("116")); + + message.setExtension( + optionalGroupExtension, OptionalGroup_extension.newBuilder().setA(117).build()); + message.setExtension( + optionalNestedMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(118).build()); + message.setExtension( + optionalForeignMessageExtension, ForeignMessage.newBuilder().setC(119).build()); + message.setExtension( + optionalImportMessageExtension, ImportMessage.newBuilder().setD(120).build()); + message.setExtension( + optionalPublicImportMessageExtension, PublicImportMessage.newBuilder().setE(126).build()); + message.setExtension( + optionalLazyMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(127).build()); + + message.setExtension(optionalNestedEnumExtension, TestAllTypes.NestedEnum.BAZ); + message.setExtension(optionalForeignEnumExtension, ForeignEnum.FOREIGN_BAZ); + message.setExtension(optionalImportEnumExtension, ImportEnum.IMPORT_BAZ); + + message.setExtension(optionalStringPieceExtension, "124"); + message.setExtension(optionalCordExtension, "125"); + + // ----------------------------------------------------------------- + + message.addExtension(repeatedInt32Extension, 201); + message.addExtension(repeatedInt64Extension, 202L); + message.addExtension(repeatedUint32Extension, 203); + message.addExtension(repeatedUint64Extension, 204L); + message.addExtension(repeatedSint32Extension, 205); + message.addExtension(repeatedSint64Extension, 206L); + message.addExtension(repeatedFixed32Extension, 207); + message.addExtension(repeatedFixed64Extension, 208L); + message.addExtension(repeatedSfixed32Extension, 209); + message.addExtension(repeatedSfixed64Extension, 210L); + message.addExtension(repeatedFloatExtension, 211F); + message.addExtension(repeatedDoubleExtension, 212D); + message.addExtension(repeatedBoolExtension, true); + message.addExtension(repeatedStringExtension, "215"); + message.addExtension(repeatedBytesExtension, toBytes("216")); + + message.addExtension( + repeatedGroupExtension, RepeatedGroup_extension.newBuilder().setA(217).build()); + message.addExtension( + repeatedNestedMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(218).build()); + message.addExtension( + repeatedForeignMessageExtension, ForeignMessage.newBuilder().setC(219).build()); + message.addExtension( + repeatedImportMessageExtension, ImportMessage.newBuilder().setD(220).build()); + message.addExtension( + repeatedLazyMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(227).build()); + + message.addExtension(repeatedNestedEnumExtension, TestAllTypes.NestedEnum.BAR); + message.addExtension(repeatedForeignEnumExtension, ForeignEnum.FOREIGN_BAR); + message.addExtension(repeatedImportEnumExtension, ImportEnum.IMPORT_BAR); + + message.addExtension(repeatedStringPieceExtension, "224"); + message.addExtension(repeatedCordExtension, "225"); + + // Add a second one of each field. + message.addExtension(repeatedInt32Extension, 301); + message.addExtension(repeatedInt64Extension, 302L); + message.addExtension(repeatedUint32Extension, 303); + message.addExtension(repeatedUint64Extension, 304L); + message.addExtension(repeatedSint32Extension, 305); + message.addExtension(repeatedSint64Extension, 306L); + message.addExtension(repeatedFixed32Extension, 307); + message.addExtension(repeatedFixed64Extension, 308L); + message.addExtension(repeatedSfixed32Extension, 309); + message.addExtension(repeatedSfixed64Extension, 310L); + message.addExtension(repeatedFloatExtension, 311F); + message.addExtension(repeatedDoubleExtension, 312D); + message.addExtension(repeatedBoolExtension, false); + message.addExtension(repeatedStringExtension, "315"); + message.addExtension(repeatedBytesExtension, toBytes("316")); + + message.addExtension( + repeatedGroupExtension, RepeatedGroup_extension.newBuilder().setA(317).build()); + message.addExtension( + repeatedNestedMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(318).build()); + message.addExtension( + repeatedForeignMessageExtension, ForeignMessage.newBuilder().setC(319).build()); + message.addExtension( + repeatedImportMessageExtension, ImportMessage.newBuilder().setD(320).build()); + message.addExtension( + repeatedLazyMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(327).build()); + + message.addExtension(repeatedNestedEnumExtension, TestAllTypes.NestedEnum.BAZ); + message.addExtension(repeatedForeignEnumExtension, ForeignEnum.FOREIGN_BAZ); + message.addExtension(repeatedImportEnumExtension, ImportEnum.IMPORT_BAZ); + + message.addExtension(repeatedStringPieceExtension, "324"); + message.addExtension(repeatedCordExtension, "325"); + + // ----------------------------------------------------------------- + + message.setExtension(defaultInt32Extension, 401); + message.setExtension(defaultInt64Extension, 402L); + message.setExtension(defaultUint32Extension, 403); + message.setExtension(defaultUint64Extension, 404L); + message.setExtension(defaultSint32Extension, 405); + message.setExtension(defaultSint64Extension, 406L); + message.setExtension(defaultFixed32Extension, 407); + message.setExtension(defaultFixed64Extension, 408L); + message.setExtension(defaultSfixed32Extension, 409); + message.setExtension(defaultSfixed64Extension, 410L); + message.setExtension(defaultFloatExtension, 411F); + message.setExtension(defaultDoubleExtension, 412D); + message.setExtension(defaultBoolExtension, false); + message.setExtension(defaultStringExtension, "415"); + message.setExtension(defaultBytesExtension, toBytes("416")); + + message.setExtension(defaultNestedEnumExtension, TestAllTypes.NestedEnum.FOO); + message.setExtension(defaultForeignEnumExtension, ForeignEnum.FOREIGN_FOO); + message.setExtension(defaultImportEnumExtension, ImportEnum.IMPORT_FOO); + + message.setExtension(defaultStringPieceExtension, "424"); + message.setExtension(defaultCordExtension, "425"); + + message.setExtension(oneofUint32Extension, 601); + message.setExtension( + oneofNestedMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(602).build()); + message.setExtension(oneofStringExtension, "603"); + message.setExtension(oneofBytesExtension, toBytes("604")); + } + + // ------------------------------------------------------------------- + + /** + * Modify the repeated extensions of {@code message} to contain the values expected by {@code + * assertRepeatedExtensionsModified()}. + */ + public static void modifyRepeatedExtensions(TestAllExtensions.Builder message) { + message.setExtension(repeatedInt32Extension, 1, 501); + message.setExtension(repeatedInt64Extension, 1, 502L); + message.setExtension(repeatedUint32Extension, 1, 503); + message.setExtension(repeatedUint64Extension, 1, 504L); + message.setExtension(repeatedSint32Extension, 1, 505); + message.setExtension(repeatedSint64Extension, 1, 506L); + message.setExtension(repeatedFixed32Extension, 1, 507); + message.setExtension(repeatedFixed64Extension, 1, 508L); + message.setExtension(repeatedSfixed32Extension, 1, 509); + message.setExtension(repeatedSfixed64Extension, 1, 510L); + message.setExtension(repeatedFloatExtension, 1, 511F); + message.setExtension(repeatedDoubleExtension, 1, 512D); + message.setExtension(repeatedBoolExtension, 1, true); + message.setExtension(repeatedStringExtension, 1, "515"); + message.setExtension(repeatedBytesExtension, 1, toBytes("516")); + + message.setExtension( + repeatedGroupExtension, 1, RepeatedGroup_extension.newBuilder().setA(517).build()); + message.setExtension( + repeatedNestedMessageExtension, + 1, + TestAllTypes.NestedMessage.newBuilder().setBb(518).build()); + message.setExtension( + repeatedForeignMessageExtension, 1, ForeignMessage.newBuilder().setC(519).build()); + message.setExtension( + repeatedImportMessageExtension, 1, ImportMessage.newBuilder().setD(520).build()); + message.setExtension( + repeatedLazyMessageExtension, + 1, + TestAllTypes.NestedMessage.newBuilder().setBb(527).build()); + + message.setExtension(repeatedNestedEnumExtension, 1, TestAllTypes.NestedEnum.FOO); + message.setExtension(repeatedForeignEnumExtension, 1, ForeignEnum.FOREIGN_FOO); + message.setExtension(repeatedImportEnumExtension, 1, ImportEnum.IMPORT_FOO); + + message.setExtension(repeatedStringPieceExtension, 1, "524"); + message.setExtension(repeatedCordExtension, 1, "525"); + } + + // ------------------------------------------------------------------- + + /** + * Assert (using {@code junit.framework.Assert}} that all extensions of {@code message} are set to + * the values assigned by {@code setAllExtensions}. + */ + public static void assertAllExtensionsSet(TestAllExtensionsOrBuilder message) { + Assert.assertTrue(message.hasExtension(optionalInt32Extension)); + Assert.assertTrue(message.hasExtension(optionalInt64Extension)); + Assert.assertTrue(message.hasExtension(optionalUint32Extension)); + Assert.assertTrue(message.hasExtension(optionalUint64Extension)); + Assert.assertTrue(message.hasExtension(optionalSint32Extension)); + Assert.assertTrue(message.hasExtension(optionalSint64Extension)); + Assert.assertTrue(message.hasExtension(optionalFixed32Extension)); + Assert.assertTrue(message.hasExtension(optionalFixed64Extension)); + Assert.assertTrue(message.hasExtension(optionalSfixed32Extension)); + Assert.assertTrue(message.hasExtension(optionalSfixed64Extension)); + Assert.assertTrue(message.hasExtension(optionalFloatExtension)); + Assert.assertTrue(message.hasExtension(optionalDoubleExtension)); + Assert.assertTrue(message.hasExtension(optionalBoolExtension)); + Assert.assertTrue(message.hasExtension(optionalStringExtension)); + Assert.assertTrue(message.hasExtension(optionalBytesExtension)); + + Assert.assertTrue(message.hasExtension(optionalGroupExtension)); + Assert.assertTrue(message.hasExtension(optionalNestedMessageExtension)); + Assert.assertTrue(message.hasExtension(optionalForeignMessageExtension)); + Assert.assertTrue(message.hasExtension(optionalImportMessageExtension)); + + Assert.assertTrue(message.getExtension(optionalGroupExtension).hasA()); + Assert.assertTrue(message.getExtension(optionalNestedMessageExtension).hasBb()); + Assert.assertTrue(message.getExtension(optionalForeignMessageExtension).hasC()); + Assert.assertTrue(message.getExtension(optionalImportMessageExtension).hasD()); + + Assert.assertTrue(message.hasExtension(optionalNestedEnumExtension)); + Assert.assertTrue(message.hasExtension(optionalForeignEnumExtension)); + Assert.assertTrue(message.hasExtension(optionalImportEnumExtension)); + + Assert.assertTrue(message.hasExtension(optionalStringPieceExtension)); + Assert.assertTrue(message.hasExtension(optionalCordExtension)); + + assertEqualsExactType(101, message.getExtension(optionalInt32Extension)); + assertEqualsExactType(102L, message.getExtension(optionalInt64Extension)); + assertEqualsExactType(103, message.getExtension(optionalUint32Extension)); + assertEqualsExactType(104L, message.getExtension(optionalUint64Extension)); + assertEqualsExactType(105, message.getExtension(optionalSint32Extension)); + assertEqualsExactType(106L, message.getExtension(optionalSint64Extension)); + assertEqualsExactType(107, message.getExtension(optionalFixed32Extension)); + assertEqualsExactType(108L, message.getExtension(optionalFixed64Extension)); + assertEqualsExactType(109, message.getExtension(optionalSfixed32Extension)); + assertEqualsExactType(110L, message.getExtension(optionalSfixed64Extension)); + assertEqualsExactType(111F, message.getExtension(optionalFloatExtension)); + assertEqualsExactType(112D, message.getExtension(optionalDoubleExtension)); + assertEqualsExactType(true, message.getExtension(optionalBoolExtension)); + assertEqualsExactType("115", message.getExtension(optionalStringExtension)); + assertEqualsExactType(toBytes("116"), message.getExtension(optionalBytesExtension)); + + assertEqualsExactType(117, message.getExtension(optionalGroupExtension).getA()); + assertEqualsExactType(118, message.getExtension(optionalNestedMessageExtension).getBb()); + assertEqualsExactType(119, message.getExtension(optionalForeignMessageExtension).getC()); + assertEqualsExactType(120, message.getExtension(optionalImportMessageExtension).getD()); + assertEqualsExactType(126, message.getExtension(optionalPublicImportMessageExtension).getE()); + assertEqualsExactType(127, message.getExtension(optionalLazyMessageExtension).getBb()); + + assertEqualsExactType( + TestAllTypes.NestedEnum.BAZ, message.getExtension(optionalNestedEnumExtension)); + assertEqualsExactType( + ForeignEnum.FOREIGN_BAZ, message.getExtension(optionalForeignEnumExtension)); + assertEqualsExactType(ImportEnum.IMPORT_BAZ, message.getExtension(optionalImportEnumExtension)); + + assertEqualsExactType("124", message.getExtension(optionalStringPieceExtension)); + assertEqualsExactType("125", message.getExtension(optionalCordExtension)); + + // ----------------------------------------------------------------- + + Assert.assertEquals(2, message.getExtensionCount(repeatedInt32Extension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedInt64Extension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedUint32Extension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedUint64Extension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedSint32Extension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedSint64Extension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32Extension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64Extension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed32Extension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed64Extension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtension)); + + Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedForeignMessageExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtension)); + + Assert.assertEquals(2, message.getExtensionCount(repeatedStringPieceExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedCordExtension)); + + assertEqualsExactType(201, message.getExtension(repeatedInt32Extension, 0)); + assertEqualsExactType(202L, message.getExtension(repeatedInt64Extension, 0)); + assertEqualsExactType(203, message.getExtension(repeatedUint32Extension, 0)); + assertEqualsExactType(204L, message.getExtension(repeatedUint64Extension, 0)); + assertEqualsExactType(205, message.getExtension(repeatedSint32Extension, 0)); + assertEqualsExactType(206L, message.getExtension(repeatedSint64Extension, 0)); + assertEqualsExactType(207, message.getExtension(repeatedFixed32Extension, 0)); + assertEqualsExactType(208L, message.getExtension(repeatedFixed64Extension, 0)); + assertEqualsExactType(209, message.getExtension(repeatedSfixed32Extension, 0)); + assertEqualsExactType(210L, message.getExtension(repeatedSfixed64Extension, 0)); + assertEqualsExactType(211F, message.getExtension(repeatedFloatExtension, 0)); + assertEqualsExactType(212D, message.getExtension(repeatedDoubleExtension, 0)); + assertEqualsExactType(true, message.getExtension(repeatedBoolExtension, 0)); + assertEqualsExactType("215", message.getExtension(repeatedStringExtension, 0)); + assertEqualsExactType(toBytes("216"), message.getExtension(repeatedBytesExtension, 0)); + + assertEqualsExactType(217, message.getExtension(repeatedGroupExtension, 0).getA()); + assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtension, 0).getBb()); + assertEqualsExactType(219, message.getExtension(repeatedForeignMessageExtension, 0).getC()); + assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtension, 0).getD()); + assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtension, 0).getBb()); + + assertEqualsExactType( + TestAllTypes.NestedEnum.BAR, message.getExtension(repeatedNestedEnumExtension, 0)); + assertEqualsExactType( + ForeignEnum.FOREIGN_BAR, message.getExtension(repeatedForeignEnumExtension, 0)); + assertEqualsExactType( + ImportEnum.IMPORT_BAR, message.getExtension(repeatedImportEnumExtension, 0)); + + assertEqualsExactType("224", message.getExtension(repeatedStringPieceExtension, 0)); + assertEqualsExactType("225", message.getExtension(repeatedCordExtension, 0)); + + assertEqualsExactType(301, message.getExtension(repeatedInt32Extension, 1)); + assertEqualsExactType(302L, message.getExtension(repeatedInt64Extension, 1)); + assertEqualsExactType(303, message.getExtension(repeatedUint32Extension, 1)); + assertEqualsExactType(304L, message.getExtension(repeatedUint64Extension, 1)); + assertEqualsExactType(305, message.getExtension(repeatedSint32Extension, 1)); + assertEqualsExactType(306L, message.getExtension(repeatedSint64Extension, 1)); + assertEqualsExactType(307, message.getExtension(repeatedFixed32Extension, 1)); + assertEqualsExactType(308L, message.getExtension(repeatedFixed64Extension, 1)); + assertEqualsExactType(309, message.getExtension(repeatedSfixed32Extension, 1)); + assertEqualsExactType(310L, message.getExtension(repeatedSfixed64Extension, 1)); + assertEqualsExactType(311F, message.getExtension(repeatedFloatExtension, 1)); + assertEqualsExactType(312D, message.getExtension(repeatedDoubleExtension, 1)); + assertEqualsExactType(false, message.getExtension(repeatedBoolExtension, 1)); + assertEqualsExactType("315", message.getExtension(repeatedStringExtension, 1)); + assertEqualsExactType(toBytes("316"), message.getExtension(repeatedBytesExtension, 1)); + + assertEqualsExactType(317, message.getExtension(repeatedGroupExtension, 1).getA()); + assertEqualsExactType(318, message.getExtension(repeatedNestedMessageExtension, 1).getBb()); + assertEqualsExactType(319, message.getExtension(repeatedForeignMessageExtension, 1).getC()); + assertEqualsExactType(320, message.getExtension(repeatedImportMessageExtension, 1).getD()); + assertEqualsExactType(327, message.getExtension(repeatedLazyMessageExtension, 1).getBb()); + + assertEqualsExactType( + TestAllTypes.NestedEnum.BAZ, message.getExtension(repeatedNestedEnumExtension, 1)); + assertEqualsExactType( + ForeignEnum.FOREIGN_BAZ, message.getExtension(repeatedForeignEnumExtension, 1)); + assertEqualsExactType( + ImportEnum.IMPORT_BAZ, message.getExtension(repeatedImportEnumExtension, 1)); + + assertEqualsExactType("324", message.getExtension(repeatedStringPieceExtension, 1)); + assertEqualsExactType("325", message.getExtension(repeatedCordExtension, 1)); + + // ----------------------------------------------------------------- + + Assert.assertTrue(message.hasExtension(defaultInt32Extension)); + Assert.assertTrue(message.hasExtension(defaultInt64Extension)); + Assert.assertTrue(message.hasExtension(defaultUint32Extension)); + Assert.assertTrue(message.hasExtension(defaultUint64Extension)); + Assert.assertTrue(message.hasExtension(defaultSint32Extension)); + Assert.assertTrue(message.hasExtension(defaultSint64Extension)); + Assert.assertTrue(message.hasExtension(defaultFixed32Extension)); + Assert.assertTrue(message.hasExtension(defaultFixed64Extension)); + Assert.assertTrue(message.hasExtension(defaultSfixed32Extension)); + Assert.assertTrue(message.hasExtension(defaultSfixed64Extension)); + Assert.assertTrue(message.hasExtension(defaultFloatExtension)); + Assert.assertTrue(message.hasExtension(defaultDoubleExtension)); + Assert.assertTrue(message.hasExtension(defaultBoolExtension)); + Assert.assertTrue(message.hasExtension(defaultStringExtension)); + Assert.assertTrue(message.hasExtension(defaultBytesExtension)); + + Assert.assertTrue(message.hasExtension(defaultNestedEnumExtension)); + Assert.assertTrue(message.hasExtension(defaultForeignEnumExtension)); + Assert.assertTrue(message.hasExtension(defaultImportEnumExtension)); + + Assert.assertTrue(message.hasExtension(defaultStringPieceExtension)); + Assert.assertTrue(message.hasExtension(defaultCordExtension)); + + assertEqualsExactType(401, message.getExtension(defaultInt32Extension)); + assertEqualsExactType(402L, message.getExtension(defaultInt64Extension)); + assertEqualsExactType(403, message.getExtension(defaultUint32Extension)); + assertEqualsExactType(404L, message.getExtension(defaultUint64Extension)); + assertEqualsExactType(405, message.getExtension(defaultSint32Extension)); + assertEqualsExactType(406L, message.getExtension(defaultSint64Extension)); + assertEqualsExactType(407, message.getExtension(defaultFixed32Extension)); + assertEqualsExactType(408L, message.getExtension(defaultFixed64Extension)); + assertEqualsExactType(409, message.getExtension(defaultSfixed32Extension)); + assertEqualsExactType(410L, message.getExtension(defaultSfixed64Extension)); + assertEqualsExactType(411F, message.getExtension(defaultFloatExtension)); + assertEqualsExactType(412D, message.getExtension(defaultDoubleExtension)); + assertEqualsExactType(false, message.getExtension(defaultBoolExtension)); + assertEqualsExactType("415", message.getExtension(defaultStringExtension)); + assertEqualsExactType(toBytes("416"), message.getExtension(defaultBytesExtension)); + + assertEqualsExactType( + TestAllTypes.NestedEnum.FOO, message.getExtension(defaultNestedEnumExtension)); + assertEqualsExactType( + ForeignEnum.FOREIGN_FOO, message.getExtension(defaultForeignEnumExtension)); + assertEqualsExactType(ImportEnum.IMPORT_FOO, message.getExtension(defaultImportEnumExtension)); + + assertEqualsExactType("424", message.getExtension(defaultStringPieceExtension)); + assertEqualsExactType("425", message.getExtension(defaultCordExtension)); + + Assert.assertTrue(message.hasExtension(oneofBytesExtension)); + + assertEqualsExactType(toBytes("604"), message.getExtension(oneofBytesExtension)); + } + + // ------------------------------------------------------------------- + + /** + * Assert (using {@code junit.framework.Assert}} that all extensions of {@code message} are + * cleared, and that getting the extensions returns their default values. + */ + public static void assertExtensionsClear(TestAllExtensionsOrBuilder message) { + // hasBlah() should initially be false for all optional fields. + Assert.assertFalse(message.hasExtension(optionalInt32Extension)); + Assert.assertFalse(message.hasExtension(optionalInt64Extension)); + Assert.assertFalse(message.hasExtension(optionalUint32Extension)); + Assert.assertFalse(message.hasExtension(optionalUint64Extension)); + Assert.assertFalse(message.hasExtension(optionalSint32Extension)); + Assert.assertFalse(message.hasExtension(optionalSint64Extension)); + Assert.assertFalse(message.hasExtension(optionalFixed32Extension)); + Assert.assertFalse(message.hasExtension(optionalFixed64Extension)); + Assert.assertFalse(message.hasExtension(optionalSfixed32Extension)); + Assert.assertFalse(message.hasExtension(optionalSfixed64Extension)); + Assert.assertFalse(message.hasExtension(optionalFloatExtension)); + Assert.assertFalse(message.hasExtension(optionalDoubleExtension)); + Assert.assertFalse(message.hasExtension(optionalBoolExtension)); + Assert.assertFalse(message.hasExtension(optionalStringExtension)); + Assert.assertFalse(message.hasExtension(optionalBytesExtension)); + + Assert.assertFalse(message.hasExtension(optionalGroupExtension)); + Assert.assertFalse(message.hasExtension(optionalNestedMessageExtension)); + Assert.assertFalse(message.hasExtension(optionalForeignMessageExtension)); + Assert.assertFalse(message.hasExtension(optionalImportMessageExtension)); + + Assert.assertFalse(message.hasExtension(optionalNestedEnumExtension)); + Assert.assertFalse(message.hasExtension(optionalForeignEnumExtension)); + Assert.assertFalse(message.hasExtension(optionalImportEnumExtension)); + + Assert.assertFalse(message.hasExtension(optionalStringPieceExtension)); + Assert.assertFalse(message.hasExtension(optionalCordExtension)); + + // Optional fields without defaults are set to zero or something like it. + assertEqualsExactType(0, message.getExtension(optionalInt32Extension)); + assertEqualsExactType(0L, message.getExtension(optionalInt64Extension)); + assertEqualsExactType(0, message.getExtension(optionalUint32Extension)); + assertEqualsExactType(0L, message.getExtension(optionalUint64Extension)); + assertEqualsExactType(0, message.getExtension(optionalSint32Extension)); + assertEqualsExactType(0L, message.getExtension(optionalSint64Extension)); + assertEqualsExactType(0, message.getExtension(optionalFixed32Extension)); + assertEqualsExactType(0L, message.getExtension(optionalFixed64Extension)); + assertEqualsExactType(0, message.getExtension(optionalSfixed32Extension)); + assertEqualsExactType(0L, message.getExtension(optionalSfixed64Extension)); + assertEqualsExactType(0F, message.getExtension(optionalFloatExtension)); + assertEqualsExactType(0D, message.getExtension(optionalDoubleExtension)); + assertEqualsExactType(false, message.getExtension(optionalBoolExtension)); + assertEqualsExactType("", message.getExtension(optionalStringExtension)); + assertEqualsExactType(ByteString.EMPTY, message.getExtension(optionalBytesExtension)); + + // Embedded messages should also be clear. + Assert.assertFalse(message.getExtension(optionalGroupExtension).hasA()); + Assert.assertFalse(message.getExtension(optionalNestedMessageExtension).hasBb()); + Assert.assertFalse(message.getExtension(optionalForeignMessageExtension).hasC()); + Assert.assertFalse(message.getExtension(optionalImportMessageExtension).hasD()); + + assertEqualsExactType(0, message.getExtension(optionalGroupExtension).getA()); + assertEqualsExactType(0, message.getExtension(optionalNestedMessageExtension).getBb()); + assertEqualsExactType(0, message.getExtension(optionalForeignMessageExtension).getC()); + assertEqualsExactType(0, message.getExtension(optionalImportMessageExtension).getD()); + + // Enums without defaults are set to the first value in the enum. + assertEqualsExactType( + TestAllTypes.NestedEnum.FOO, message.getExtension(optionalNestedEnumExtension)); + assertEqualsExactType( + ForeignEnum.FOREIGN_FOO, message.getExtension(optionalForeignEnumExtension)); + assertEqualsExactType(ImportEnum.IMPORT_FOO, message.getExtension(optionalImportEnumExtension)); + + assertEqualsExactType("", message.getExtension(optionalStringPieceExtension)); + assertEqualsExactType("", message.getExtension(optionalCordExtension)); + + // Repeated fields are empty. + Assert.assertEquals(0, message.getExtensionCount(repeatedInt32Extension)); + Assert.assertEquals(0, message.getExtensionCount(repeatedInt64Extension)); + Assert.assertEquals(0, message.getExtensionCount(repeatedUint32Extension)); + Assert.assertEquals(0, message.getExtensionCount(repeatedUint64Extension)); + Assert.assertEquals(0, message.getExtensionCount(repeatedSint32Extension)); + Assert.assertEquals(0, message.getExtensionCount(repeatedSint64Extension)); + Assert.assertEquals(0, message.getExtensionCount(repeatedFixed32Extension)); + Assert.assertEquals(0, message.getExtensionCount(repeatedFixed64Extension)); + Assert.assertEquals(0, message.getExtensionCount(repeatedSfixed32Extension)); + Assert.assertEquals(0, message.getExtensionCount(repeatedSfixed64Extension)); + Assert.assertEquals(0, message.getExtensionCount(repeatedFloatExtension)); + Assert.assertEquals(0, message.getExtensionCount(repeatedDoubleExtension)); + Assert.assertEquals(0, message.getExtensionCount(repeatedBoolExtension)); + Assert.assertEquals(0, message.getExtensionCount(repeatedStringExtension)); + Assert.assertEquals(0, message.getExtensionCount(repeatedBytesExtension)); + + Assert.assertEquals(0, message.getExtensionCount(repeatedGroupExtension)); + Assert.assertEquals(0, message.getExtensionCount(repeatedNestedMessageExtension)); + Assert.assertEquals(0, message.getExtensionCount(repeatedForeignMessageExtension)); + Assert.assertEquals(0, message.getExtensionCount(repeatedImportMessageExtension)); + Assert.assertEquals(0, message.getExtensionCount(repeatedLazyMessageExtension)); + Assert.assertEquals(0, message.getExtensionCount(repeatedNestedEnumExtension)); + Assert.assertEquals(0, message.getExtensionCount(repeatedForeignEnumExtension)); + Assert.assertEquals(0, message.getExtensionCount(repeatedImportEnumExtension)); + + Assert.assertEquals(0, message.getExtensionCount(repeatedStringPieceExtension)); + Assert.assertEquals(0, message.getExtensionCount(repeatedCordExtension)); + + // Repeated fields are empty via getExtension().size(). + Assert.assertEquals(0, message.getExtension(repeatedInt32Extension).size()); + Assert.assertEquals(0, message.getExtension(repeatedInt64Extension).size()); + Assert.assertEquals(0, message.getExtension(repeatedUint32Extension).size()); + Assert.assertEquals(0, message.getExtension(repeatedUint64Extension).size()); + Assert.assertEquals(0, message.getExtension(repeatedSint32Extension).size()); + Assert.assertEquals(0, message.getExtension(repeatedSint64Extension).size()); + Assert.assertEquals(0, message.getExtension(repeatedFixed32Extension).size()); + Assert.assertEquals(0, message.getExtension(repeatedFixed64Extension).size()); + Assert.assertEquals(0, message.getExtension(repeatedSfixed32Extension).size()); + Assert.assertEquals(0, message.getExtension(repeatedSfixed64Extension).size()); + Assert.assertEquals(0, message.getExtension(repeatedFloatExtension).size()); + Assert.assertEquals(0, message.getExtension(repeatedDoubleExtension).size()); + Assert.assertEquals(0, message.getExtension(repeatedBoolExtension).size()); + Assert.assertEquals(0, message.getExtension(repeatedStringExtension).size()); + Assert.assertEquals(0, message.getExtension(repeatedBytesExtension).size()); + + Assert.assertEquals(0, message.getExtension(repeatedGroupExtension).size()); + Assert.assertEquals(0, message.getExtension(repeatedNestedMessageExtension).size()); + Assert.assertEquals(0, message.getExtension(repeatedForeignMessageExtension).size()); + Assert.assertEquals(0, message.getExtension(repeatedImportMessageExtension).size()); + Assert.assertEquals(0, message.getExtension(repeatedLazyMessageExtension).size()); + Assert.assertEquals(0, message.getExtension(repeatedNestedEnumExtension).size()); + Assert.assertEquals(0, message.getExtension(repeatedForeignEnumExtension).size()); + Assert.assertEquals(0, message.getExtension(repeatedImportEnumExtension).size()); + + Assert.assertEquals(0, message.getExtension(repeatedStringPieceExtension).size()); + Assert.assertEquals(0, message.getExtension(repeatedCordExtension).size()); + + // hasBlah() should also be false for all default fields. + Assert.assertFalse(message.hasExtension(defaultInt32Extension)); + Assert.assertFalse(message.hasExtension(defaultInt64Extension)); + Assert.assertFalse(message.hasExtension(defaultUint32Extension)); + Assert.assertFalse(message.hasExtension(defaultUint64Extension)); + Assert.assertFalse(message.hasExtension(defaultSint32Extension)); + Assert.assertFalse(message.hasExtension(defaultSint64Extension)); + Assert.assertFalse(message.hasExtension(defaultFixed32Extension)); + Assert.assertFalse(message.hasExtension(defaultFixed64Extension)); + Assert.assertFalse(message.hasExtension(defaultSfixed32Extension)); + Assert.assertFalse(message.hasExtension(defaultSfixed64Extension)); + Assert.assertFalse(message.hasExtension(defaultFloatExtension)); + Assert.assertFalse(message.hasExtension(defaultDoubleExtension)); + Assert.assertFalse(message.hasExtension(defaultBoolExtension)); + Assert.assertFalse(message.hasExtension(defaultStringExtension)); + Assert.assertFalse(message.hasExtension(defaultBytesExtension)); + + Assert.assertFalse(message.hasExtension(defaultNestedEnumExtension)); + Assert.assertFalse(message.hasExtension(defaultForeignEnumExtension)); + Assert.assertFalse(message.hasExtension(defaultImportEnumExtension)); + + Assert.assertFalse(message.hasExtension(defaultStringPieceExtension)); + Assert.assertFalse(message.hasExtension(defaultCordExtension)); + + // Fields with defaults have their default values (duh). + assertEqualsExactType(41, message.getExtension(defaultInt32Extension)); + assertEqualsExactType(42L, message.getExtension(defaultInt64Extension)); + assertEqualsExactType(43, message.getExtension(defaultUint32Extension)); + assertEqualsExactType(44L, message.getExtension(defaultUint64Extension)); + assertEqualsExactType(-45, message.getExtension(defaultSint32Extension)); + assertEqualsExactType(46L, message.getExtension(defaultSint64Extension)); + assertEqualsExactType(47, message.getExtension(defaultFixed32Extension)); + assertEqualsExactType(48L, message.getExtension(defaultFixed64Extension)); + assertEqualsExactType(49, message.getExtension(defaultSfixed32Extension)); + assertEqualsExactType(-50L, message.getExtension(defaultSfixed64Extension)); + assertEqualsExactType(51.5F, message.getExtension(defaultFloatExtension)); + assertEqualsExactType(52e3D, message.getExtension(defaultDoubleExtension)); + assertEqualsExactType(true, message.getExtension(defaultBoolExtension)); + assertEqualsExactType("hello", message.getExtension(defaultStringExtension)); + assertEqualsExactType(toBytes("world"), message.getExtension(defaultBytesExtension)); + + assertEqualsExactType( + TestAllTypes.NestedEnum.BAR, message.getExtension(defaultNestedEnumExtension)); + assertEqualsExactType( + ForeignEnum.FOREIGN_BAR, message.getExtension(defaultForeignEnumExtension)); + assertEqualsExactType(ImportEnum.IMPORT_BAR, message.getExtension(defaultImportEnumExtension)); + + assertEqualsExactType("abc", message.getExtension(defaultStringPieceExtension)); + assertEqualsExactType("123", message.getExtension(defaultCordExtension)); + + Assert.assertFalse(message.hasExtension(oneofUint32Extension)); + Assert.assertFalse(message.hasExtension(oneofNestedMessageExtension)); + Assert.assertFalse(message.hasExtension(oneofStringExtension)); + Assert.assertFalse(message.hasExtension(oneofBytesExtension)); + } + + // ------------------------------------------------------------------- + + /** + * Assert (using {@code junit.framework.Assert}} that all extensions of {@code message} are set to + * the values assigned by {@code setAllExtensions} followed by {@code modifyRepeatedExtensions}. + */ + public static void assertRepeatedExtensionsModified(TestAllExtensionsOrBuilder 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.assertEquals(2, message.getExtensionCount(repeatedInt32Extension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedInt64Extension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedUint32Extension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedUint64Extension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedSint32Extension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedSint64Extension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32Extension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64Extension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed32Extension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed64Extension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtension)); + + Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedForeignMessageExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtension)); + + Assert.assertEquals(2, message.getExtensionCount(repeatedStringPieceExtension)); + Assert.assertEquals(2, message.getExtensionCount(repeatedCordExtension)); + + assertEqualsExactType(201, message.getExtension(repeatedInt32Extension, 0)); + assertEqualsExactType(202L, message.getExtension(repeatedInt64Extension, 0)); + assertEqualsExactType(203, message.getExtension(repeatedUint32Extension, 0)); + assertEqualsExactType(204L, message.getExtension(repeatedUint64Extension, 0)); + assertEqualsExactType(205, message.getExtension(repeatedSint32Extension, 0)); + assertEqualsExactType(206L, message.getExtension(repeatedSint64Extension, 0)); + assertEqualsExactType(207, message.getExtension(repeatedFixed32Extension, 0)); + assertEqualsExactType(208L, message.getExtension(repeatedFixed64Extension, 0)); + assertEqualsExactType(209, message.getExtension(repeatedSfixed32Extension, 0)); + assertEqualsExactType(210L, message.getExtension(repeatedSfixed64Extension, 0)); + assertEqualsExactType(211F, message.getExtension(repeatedFloatExtension, 0)); + assertEqualsExactType(212D, message.getExtension(repeatedDoubleExtension, 0)); + assertEqualsExactType(true, message.getExtension(repeatedBoolExtension, 0)); + assertEqualsExactType("215", message.getExtension(repeatedStringExtension, 0)); + assertEqualsExactType(toBytes("216"), message.getExtension(repeatedBytesExtension, 0)); + + assertEqualsExactType(217, message.getExtension(repeatedGroupExtension, 0).getA()); + assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtension, 0).getBb()); + assertEqualsExactType(219, message.getExtension(repeatedForeignMessageExtension, 0).getC()); + assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtension, 0).getD()); + assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtension, 0).getBb()); + + assertEqualsExactType( + TestAllTypes.NestedEnum.BAR, message.getExtension(repeatedNestedEnumExtension, 0)); + assertEqualsExactType( + ForeignEnum.FOREIGN_BAR, message.getExtension(repeatedForeignEnumExtension, 0)); + assertEqualsExactType( + ImportEnum.IMPORT_BAR, message.getExtension(repeatedImportEnumExtension, 0)); + + assertEqualsExactType("224", message.getExtension(repeatedStringPieceExtension, 0)); + assertEqualsExactType("225", message.getExtension(repeatedCordExtension, 0)); + + // Actually verify the second (modified) elements now. + assertEqualsExactType(501, message.getExtension(repeatedInt32Extension, 1)); + assertEqualsExactType(502L, message.getExtension(repeatedInt64Extension, 1)); + assertEqualsExactType(503, message.getExtension(repeatedUint32Extension, 1)); + assertEqualsExactType(504L, message.getExtension(repeatedUint64Extension, 1)); + assertEqualsExactType(505, message.getExtension(repeatedSint32Extension, 1)); + assertEqualsExactType(506L, message.getExtension(repeatedSint64Extension, 1)); + assertEqualsExactType(507, message.getExtension(repeatedFixed32Extension, 1)); + assertEqualsExactType(508L, message.getExtension(repeatedFixed64Extension, 1)); + assertEqualsExactType(509, message.getExtension(repeatedSfixed32Extension, 1)); + assertEqualsExactType(510L, message.getExtension(repeatedSfixed64Extension, 1)); + assertEqualsExactType(511F, message.getExtension(repeatedFloatExtension, 1)); + assertEqualsExactType(512D, message.getExtension(repeatedDoubleExtension, 1)); + assertEqualsExactType(true, message.getExtension(repeatedBoolExtension, 1)); + assertEqualsExactType("515", message.getExtension(repeatedStringExtension, 1)); + assertEqualsExactType(toBytes("516"), message.getExtension(repeatedBytesExtension, 1)); + + assertEqualsExactType(517, message.getExtension(repeatedGroupExtension, 1).getA()); + assertEqualsExactType(518, message.getExtension(repeatedNestedMessageExtension, 1).getBb()); + assertEqualsExactType(519, message.getExtension(repeatedForeignMessageExtension, 1).getC()); + assertEqualsExactType(520, message.getExtension(repeatedImportMessageExtension, 1).getD()); + assertEqualsExactType(527, message.getExtension(repeatedLazyMessageExtension, 1).getBb()); + + assertEqualsExactType( + TestAllTypes.NestedEnum.FOO, message.getExtension(repeatedNestedEnumExtension, 1)); + assertEqualsExactType( + ForeignEnum.FOREIGN_FOO, message.getExtension(repeatedForeignEnumExtension, 1)); + assertEqualsExactType( + ImportEnum.IMPORT_FOO, message.getExtension(repeatedImportEnumExtension, 1)); + + assertEqualsExactType("524", message.getExtension(repeatedStringPieceExtension, 1)); + assertEqualsExactType("525", message.getExtension(repeatedCordExtension, 1)); + } + + public static void setPackedExtensions(TestPackedExtensions.Builder message) { + message.addExtension(packedInt32Extension, 601); + message.addExtension(packedInt64Extension, 602L); + message.addExtension(packedUint32Extension, 603); + message.addExtension(packedUint64Extension, 604L); + message.addExtension(packedSint32Extension, 605); + message.addExtension(packedSint64Extension, 606L); + message.addExtension(packedFixed32Extension, 607); + message.addExtension(packedFixed64Extension, 608L); + message.addExtension(packedSfixed32Extension, 609); + message.addExtension(packedSfixed64Extension, 610L); + message.addExtension(packedFloatExtension, 611F); + message.addExtension(packedDoubleExtension, 612D); + message.addExtension(packedBoolExtension, true); + message.addExtension(packedEnumExtension, ForeignEnum.FOREIGN_BAR); + // Add a second one of each field. + message.addExtension(packedInt32Extension, 701); + message.addExtension(packedInt64Extension, 702L); + message.addExtension(packedUint32Extension, 703); + message.addExtension(packedUint64Extension, 704L); + message.addExtension(packedSint32Extension, 705); + message.addExtension(packedSint64Extension, 706L); + message.addExtension(packedFixed32Extension, 707); + message.addExtension(packedFixed64Extension, 708L); + message.addExtension(packedSfixed32Extension, 709); + message.addExtension(packedSfixed64Extension, 710L); + message.addExtension(packedFloatExtension, 711F); + message.addExtension(packedDoubleExtension, 712D); + message.addExtension(packedBoolExtension, false); + message.addExtension(packedEnumExtension, ForeignEnum.FOREIGN_BAZ); + } + + public static void assertPackedExtensionsSet(TestPackedExtensions message) { + Assert.assertEquals(2, message.getExtensionCount(packedInt32Extension)); + Assert.assertEquals(2, message.getExtensionCount(packedInt64Extension)); + Assert.assertEquals(2, message.getExtensionCount(packedUint32Extension)); + Assert.assertEquals(2, message.getExtensionCount(packedUint64Extension)); + Assert.assertEquals(2, message.getExtensionCount(packedSint32Extension)); + Assert.assertEquals(2, message.getExtensionCount(packedSint64Extension)); + Assert.assertEquals(2, message.getExtensionCount(packedFixed32Extension)); + Assert.assertEquals(2, message.getExtensionCount(packedFixed64Extension)); + Assert.assertEquals(2, message.getExtensionCount(packedSfixed32Extension)); + Assert.assertEquals(2, message.getExtensionCount(packedSfixed64Extension)); + Assert.assertEquals(2, message.getExtensionCount(packedFloatExtension)); + Assert.assertEquals(2, message.getExtensionCount(packedDoubleExtension)); + Assert.assertEquals(2, message.getExtensionCount(packedBoolExtension)); + Assert.assertEquals(2, message.getExtensionCount(packedEnumExtension)); + assertEqualsExactType(601, message.getExtension(packedInt32Extension, 0)); + assertEqualsExactType(602L, message.getExtension(packedInt64Extension, 0)); + assertEqualsExactType(603, message.getExtension(packedUint32Extension, 0)); + assertEqualsExactType(604L, message.getExtension(packedUint64Extension, 0)); + assertEqualsExactType(605, message.getExtension(packedSint32Extension, 0)); + assertEqualsExactType(606L, message.getExtension(packedSint64Extension, 0)); + assertEqualsExactType(607, message.getExtension(packedFixed32Extension, 0)); + assertEqualsExactType(608L, message.getExtension(packedFixed64Extension, 0)); + assertEqualsExactType(609, message.getExtension(packedSfixed32Extension, 0)); + assertEqualsExactType(610L, message.getExtension(packedSfixed64Extension, 0)); + assertEqualsExactType(611F, message.getExtension(packedFloatExtension, 0)); + assertEqualsExactType(612D, message.getExtension(packedDoubleExtension, 0)); + assertEqualsExactType(true, message.getExtension(packedBoolExtension, 0)); + assertEqualsExactType(ForeignEnum.FOREIGN_BAR, message.getExtension(packedEnumExtension, 0)); + assertEqualsExactType(701, message.getExtension(packedInt32Extension, 1)); + assertEqualsExactType(702L, message.getExtension(packedInt64Extension, 1)); + assertEqualsExactType(703, message.getExtension(packedUint32Extension, 1)); + assertEqualsExactType(704L, message.getExtension(packedUint64Extension, 1)); + assertEqualsExactType(705, message.getExtension(packedSint32Extension, 1)); + assertEqualsExactType(706L, message.getExtension(packedSint64Extension, 1)); + assertEqualsExactType(707, message.getExtension(packedFixed32Extension, 1)); + assertEqualsExactType(708L, message.getExtension(packedFixed64Extension, 1)); + assertEqualsExactType(709, message.getExtension(packedSfixed32Extension, 1)); + assertEqualsExactType(710L, message.getExtension(packedSfixed64Extension, 1)); + assertEqualsExactType(711F, message.getExtension(packedFloatExtension, 1)); + assertEqualsExactType(712D, message.getExtension(packedDoubleExtension, 1)); + assertEqualsExactType(false, message.getExtension(packedBoolExtension, 1)); + assertEqualsExactType(ForeignEnum.FOREIGN_BAZ, message.getExtension(packedEnumExtension, 1)); + } + + // =================================================================== + // Lite extensions + + /** + * Assert (using {@code junit.framework.Assert}} that all extensions of {@code message} are set to + * the values assigned by {@code setAllExtensions}. + */ + public static void assertAllExtensionsSet(TestAllExtensionsLiteOrBuilder message) { + Assert.assertTrue(message.hasExtension(optionalInt32ExtensionLite)); + Assert.assertTrue(message.hasExtension(optionalInt64ExtensionLite)); + Assert.assertTrue(message.hasExtension(optionalUint32ExtensionLite)); + Assert.assertTrue(message.hasExtension(optionalUint64ExtensionLite)); + Assert.assertTrue(message.hasExtension(optionalSint32ExtensionLite)); + Assert.assertTrue(message.hasExtension(optionalSint64ExtensionLite)); + Assert.assertTrue(message.hasExtension(optionalFixed32ExtensionLite)); + Assert.assertTrue(message.hasExtension(optionalFixed64ExtensionLite)); + Assert.assertTrue(message.hasExtension(optionalSfixed32ExtensionLite)); + Assert.assertTrue(message.hasExtension(optionalSfixed64ExtensionLite)); + Assert.assertTrue(message.hasExtension(optionalFloatExtensionLite)); + Assert.assertTrue(message.hasExtension(optionalDoubleExtensionLite)); + Assert.assertTrue(message.hasExtension(optionalBoolExtensionLite)); + Assert.assertTrue(message.hasExtension(optionalStringExtensionLite)); + Assert.assertTrue(message.hasExtension(optionalBytesExtensionLite)); + + Assert.assertTrue(message.hasExtension(optionalGroupExtensionLite)); + Assert.assertTrue(message.hasExtension(optionalNestedMessageExtensionLite)); + Assert.assertTrue(message.hasExtension(optionalForeignMessageExtensionLite)); + Assert.assertTrue(message.hasExtension(optionalImportMessageExtensionLite)); + + Assert.assertTrue(message.getExtension(optionalGroupExtensionLite).hasA()); + Assert.assertTrue(message.getExtension(optionalNestedMessageExtensionLite).hasBb()); + Assert.assertTrue(message.getExtension(optionalForeignMessageExtensionLite).hasC()); + Assert.assertTrue(message.getExtension(optionalImportMessageExtensionLite).hasD()); + + Assert.assertTrue(message.hasExtension(optionalNestedEnumExtensionLite)); + Assert.assertTrue(message.hasExtension(optionalForeignEnumExtensionLite)); + Assert.assertTrue(message.hasExtension(optionalImportEnumExtensionLite)); + + Assert.assertTrue(message.hasExtension(optionalStringPieceExtensionLite)); + Assert.assertTrue(message.hasExtension(optionalCordExtensionLite)); + + assertEqualsExactType(101, message.getExtension(optionalInt32ExtensionLite)); + assertEqualsExactType(102L, message.getExtension(optionalInt64ExtensionLite)); + assertEqualsExactType(103, message.getExtension(optionalUint32ExtensionLite)); + assertEqualsExactType(104L, message.getExtension(optionalUint64ExtensionLite)); + assertEqualsExactType(105, message.getExtension(optionalSint32ExtensionLite)); + assertEqualsExactType(106L, message.getExtension(optionalSint64ExtensionLite)); + assertEqualsExactType(107, message.getExtension(optionalFixed32ExtensionLite)); + assertEqualsExactType(108L, message.getExtension(optionalFixed64ExtensionLite)); + assertEqualsExactType(109, message.getExtension(optionalSfixed32ExtensionLite)); + assertEqualsExactType(110L, message.getExtension(optionalSfixed64ExtensionLite)); + assertEqualsExactType(111F, message.getExtension(optionalFloatExtensionLite)); + assertEqualsExactType(112D, message.getExtension(optionalDoubleExtensionLite)); + assertEqualsExactType(true, message.getExtension(optionalBoolExtensionLite)); + assertEqualsExactType("115", message.getExtension(optionalStringExtensionLite)); + assertEqualsExactType(toBytes("116"), message.getExtension(optionalBytesExtensionLite)); + + assertEqualsExactType(117, message.getExtension(optionalGroupExtensionLite).getA()); + assertEqualsExactType(118, message.getExtension(optionalNestedMessageExtensionLite).getBb()); + assertEqualsExactType(119, message.getExtension(optionalForeignMessageExtensionLite).getC()); + assertEqualsExactType(120, message.getExtension(optionalImportMessageExtensionLite).getD()); + assertEqualsExactType( + 126, message.getExtension(optionalPublicImportMessageExtensionLite).getE()); + assertEqualsExactType(127, message.getExtension(optionalLazyMessageExtensionLite).getBb()); + + assertEqualsExactType( + TestAllTypesLite.NestedEnum.BAZ, message.getExtension(optionalNestedEnumExtensionLite)); + assertEqualsExactType( + ForeignEnumLite.FOREIGN_LITE_BAZ, message.getExtension(optionalForeignEnumExtensionLite)); + assertEqualsExactType( + ImportEnumLite.IMPORT_LITE_BAZ, message.getExtension(optionalImportEnumExtensionLite)); + + assertEqualsExactType("124", message.getExtension(optionalStringPieceExtensionLite)); + assertEqualsExactType("125", message.getExtension(optionalCordExtensionLite)); + + // ----------------------------------------------------------------- + + Assert.assertEquals(2, message.getExtensionCount(repeatedInt32ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedInt64ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedUint32ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedUint64ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedSint32ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedSint64ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed32ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed64ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtensionLite)); + + Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedForeignMessageExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtensionLite)); + + Assert.assertEquals(2, message.getExtensionCount(repeatedStringPieceExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedCordExtensionLite)); + + assertEqualsExactType(201, message.getExtension(repeatedInt32ExtensionLite, 0)); + assertEqualsExactType(202L, message.getExtension(repeatedInt64ExtensionLite, 0)); + assertEqualsExactType(203, message.getExtension(repeatedUint32ExtensionLite, 0)); + assertEqualsExactType(204L, message.getExtension(repeatedUint64ExtensionLite, 0)); + assertEqualsExactType(205, message.getExtension(repeatedSint32ExtensionLite, 0)); + assertEqualsExactType(206L, message.getExtension(repeatedSint64ExtensionLite, 0)); + assertEqualsExactType(207, message.getExtension(repeatedFixed32ExtensionLite, 0)); + assertEqualsExactType(208L, message.getExtension(repeatedFixed64ExtensionLite, 0)); + assertEqualsExactType(209, message.getExtension(repeatedSfixed32ExtensionLite, 0)); + assertEqualsExactType(210L, message.getExtension(repeatedSfixed64ExtensionLite, 0)); + assertEqualsExactType(211F, message.getExtension(repeatedFloatExtensionLite, 0)); + assertEqualsExactType(212D, message.getExtension(repeatedDoubleExtensionLite, 0)); + assertEqualsExactType(true, message.getExtension(repeatedBoolExtensionLite, 0)); + assertEqualsExactType("215", message.getExtension(repeatedStringExtensionLite, 0)); + assertEqualsExactType(toBytes("216"), message.getExtension(repeatedBytesExtensionLite, 0)); + + assertEqualsExactType(217, message.getExtension(repeatedGroupExtensionLite, 0).getA()); + assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtensionLite, 0).getBb()); + assertEqualsExactType(219, message.getExtension(repeatedForeignMessageExtensionLite, 0).getC()); + assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtensionLite, 0).getD()); + assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtensionLite, 0).getBb()); + + assertEqualsExactType( + TestAllTypesLite.NestedEnum.BAR, message.getExtension(repeatedNestedEnumExtensionLite, 0)); + assertEqualsExactType( + ForeignEnumLite.FOREIGN_LITE_BAR, + message.getExtension(repeatedForeignEnumExtensionLite, 0)); + assertEqualsExactType( + ImportEnumLite.IMPORT_LITE_BAR, message.getExtension(repeatedImportEnumExtensionLite, 0)); + + assertEqualsExactType("224", message.getExtension(repeatedStringPieceExtensionLite, 0)); + assertEqualsExactType("225", message.getExtension(repeatedCordExtensionLite, 0)); + + assertEqualsExactType(301, message.getExtension(repeatedInt32ExtensionLite, 1)); + assertEqualsExactType(302L, message.getExtension(repeatedInt64ExtensionLite, 1)); + assertEqualsExactType(303, message.getExtension(repeatedUint32ExtensionLite, 1)); + assertEqualsExactType(304L, message.getExtension(repeatedUint64ExtensionLite, 1)); + assertEqualsExactType(305, message.getExtension(repeatedSint32ExtensionLite, 1)); + assertEqualsExactType(306L, message.getExtension(repeatedSint64ExtensionLite, 1)); + assertEqualsExactType(307, message.getExtension(repeatedFixed32ExtensionLite, 1)); + assertEqualsExactType(308L, message.getExtension(repeatedFixed64ExtensionLite, 1)); + assertEqualsExactType(309, message.getExtension(repeatedSfixed32ExtensionLite, 1)); + assertEqualsExactType(310L, message.getExtension(repeatedSfixed64ExtensionLite, 1)); + assertEqualsExactType(311F, message.getExtension(repeatedFloatExtensionLite, 1)); + assertEqualsExactType(312D, message.getExtension(repeatedDoubleExtensionLite, 1)); + assertEqualsExactType(false, message.getExtension(repeatedBoolExtensionLite, 1)); + assertEqualsExactType("315", message.getExtension(repeatedStringExtensionLite, 1)); + assertEqualsExactType(toBytes("316"), message.getExtension(repeatedBytesExtensionLite, 1)); + + assertEqualsExactType(317, message.getExtension(repeatedGroupExtensionLite, 1).getA()); + assertEqualsExactType(318, message.getExtension(repeatedNestedMessageExtensionLite, 1).getBb()); + assertEqualsExactType(319, message.getExtension(repeatedForeignMessageExtensionLite, 1).getC()); + assertEqualsExactType(320, message.getExtension(repeatedImportMessageExtensionLite, 1).getD()); + assertEqualsExactType(327, message.getExtension(repeatedLazyMessageExtensionLite, 1).getBb()); + + assertEqualsExactType( + TestAllTypesLite.NestedEnum.BAZ, message.getExtension(repeatedNestedEnumExtensionLite, 1)); + assertEqualsExactType( + ForeignEnumLite.FOREIGN_LITE_BAZ, + message.getExtension(repeatedForeignEnumExtensionLite, 1)); + assertEqualsExactType( + ImportEnumLite.IMPORT_LITE_BAZ, message.getExtension(repeatedImportEnumExtensionLite, 1)); + + assertEqualsExactType("324", message.getExtension(repeatedStringPieceExtensionLite, 1)); + assertEqualsExactType("325", message.getExtension(repeatedCordExtensionLite, 1)); + + // ----------------------------------------------------------------- + + Assert.assertTrue(message.hasExtension(defaultInt32ExtensionLite)); + Assert.assertTrue(message.hasExtension(defaultInt64ExtensionLite)); + Assert.assertTrue(message.hasExtension(defaultUint32ExtensionLite)); + Assert.assertTrue(message.hasExtension(defaultUint64ExtensionLite)); + Assert.assertTrue(message.hasExtension(defaultSint32ExtensionLite)); + Assert.assertTrue(message.hasExtension(defaultSint64ExtensionLite)); + Assert.assertTrue(message.hasExtension(defaultFixed32ExtensionLite)); + Assert.assertTrue(message.hasExtension(defaultFixed64ExtensionLite)); + Assert.assertTrue(message.hasExtension(defaultSfixed32ExtensionLite)); + Assert.assertTrue(message.hasExtension(defaultSfixed64ExtensionLite)); + Assert.assertTrue(message.hasExtension(defaultFloatExtensionLite)); + Assert.assertTrue(message.hasExtension(defaultDoubleExtensionLite)); + Assert.assertTrue(message.hasExtension(defaultBoolExtensionLite)); + Assert.assertTrue(message.hasExtension(defaultStringExtensionLite)); + Assert.assertTrue(message.hasExtension(defaultBytesExtensionLite)); + + Assert.assertTrue(message.hasExtension(defaultNestedEnumExtensionLite)); + Assert.assertTrue(message.hasExtension(defaultForeignEnumExtensionLite)); + Assert.assertTrue(message.hasExtension(defaultImportEnumExtensionLite)); + + Assert.assertTrue(message.hasExtension(defaultStringPieceExtensionLite)); + Assert.assertTrue(message.hasExtension(defaultCordExtensionLite)); + + assertEqualsExactType(401, message.getExtension(defaultInt32ExtensionLite)); + assertEqualsExactType(402L, message.getExtension(defaultInt64ExtensionLite)); + assertEqualsExactType(403, message.getExtension(defaultUint32ExtensionLite)); + assertEqualsExactType(404L, message.getExtension(defaultUint64ExtensionLite)); + assertEqualsExactType(405, message.getExtension(defaultSint32ExtensionLite)); + assertEqualsExactType(406L, message.getExtension(defaultSint64ExtensionLite)); + assertEqualsExactType(407, message.getExtension(defaultFixed32ExtensionLite)); + assertEqualsExactType(408L, message.getExtension(defaultFixed64ExtensionLite)); + assertEqualsExactType(409, message.getExtension(defaultSfixed32ExtensionLite)); + assertEqualsExactType(410L, message.getExtension(defaultSfixed64ExtensionLite)); + assertEqualsExactType(411F, message.getExtension(defaultFloatExtensionLite)); + assertEqualsExactType(412D, message.getExtension(defaultDoubleExtensionLite)); + assertEqualsExactType(false, message.getExtension(defaultBoolExtensionLite)); + assertEqualsExactType("415", message.getExtension(defaultStringExtensionLite)); + assertEqualsExactType(toBytes("416"), message.getExtension(defaultBytesExtensionLite)); + + assertEqualsExactType( + TestAllTypesLite.NestedEnum.FOO, message.getExtension(defaultNestedEnumExtensionLite)); + assertEqualsExactType( + ForeignEnumLite.FOREIGN_LITE_FOO, message.getExtension(defaultForeignEnumExtensionLite)); + assertEqualsExactType( + ImportEnumLite.IMPORT_LITE_FOO, message.getExtension(defaultImportEnumExtensionLite)); + + assertEqualsExactType("424", message.getExtension(defaultStringPieceExtensionLite)); + assertEqualsExactType("425", message.getExtension(defaultCordExtensionLite)); + + Assert.assertTrue(message.hasExtension(oneofBytesExtensionLite)); + + assertEqualsExactType(toBytes("604"), message.getExtension(oneofBytesExtensionLite)); + } + + // ------------------------------------------------------------------- + + /** + * Assert (using {@code junit.framework.Assert}} that all extensions of {@code message} are + * cleared, and that getting the extensions returns their default values. + */ + public static void assertExtensionsClear(TestAllExtensionsLiteOrBuilder message) { + // hasBlah() should initially be false for all optional fields. + Assert.assertFalse(message.hasExtension(optionalInt32ExtensionLite)); + Assert.assertFalse(message.hasExtension(optionalInt64ExtensionLite)); + Assert.assertFalse(message.hasExtension(optionalUint32ExtensionLite)); + Assert.assertFalse(message.hasExtension(optionalUint64ExtensionLite)); + Assert.assertFalse(message.hasExtension(optionalSint32ExtensionLite)); + Assert.assertFalse(message.hasExtension(optionalSint64ExtensionLite)); + Assert.assertFalse(message.hasExtension(optionalFixed32ExtensionLite)); + Assert.assertFalse(message.hasExtension(optionalFixed64ExtensionLite)); + Assert.assertFalse(message.hasExtension(optionalSfixed32ExtensionLite)); + Assert.assertFalse(message.hasExtension(optionalSfixed64ExtensionLite)); + Assert.assertFalse(message.hasExtension(optionalFloatExtensionLite)); + Assert.assertFalse(message.hasExtension(optionalDoubleExtensionLite)); + Assert.assertFalse(message.hasExtension(optionalBoolExtensionLite)); + Assert.assertFalse(message.hasExtension(optionalStringExtensionLite)); + Assert.assertFalse(message.hasExtension(optionalBytesExtensionLite)); + + Assert.assertFalse(message.hasExtension(optionalGroupExtensionLite)); + Assert.assertFalse(message.hasExtension(optionalNestedMessageExtensionLite)); + Assert.assertFalse(message.hasExtension(optionalForeignMessageExtensionLite)); + Assert.assertFalse(message.hasExtension(optionalImportMessageExtensionLite)); + Assert.assertFalse(message.hasExtension(optionalPublicImportMessageExtensionLite)); + Assert.assertFalse(message.hasExtension(optionalLazyMessageExtensionLite)); + + Assert.assertFalse(message.hasExtension(optionalNestedEnumExtensionLite)); + Assert.assertFalse(message.hasExtension(optionalForeignEnumExtensionLite)); + Assert.assertFalse(message.hasExtension(optionalImportEnumExtensionLite)); + + Assert.assertFalse(message.hasExtension(optionalStringPieceExtensionLite)); + Assert.assertFalse(message.hasExtension(optionalCordExtensionLite)); + + // Optional fields without defaults are set to zero or something like it. + assertEqualsExactType(0, message.getExtension(optionalInt32ExtensionLite)); + assertEqualsExactType(0L, message.getExtension(optionalInt64ExtensionLite)); + assertEqualsExactType(0, message.getExtension(optionalUint32ExtensionLite)); + assertEqualsExactType(0L, message.getExtension(optionalUint64ExtensionLite)); + assertEqualsExactType(0, message.getExtension(optionalSint32ExtensionLite)); + assertEqualsExactType(0L, message.getExtension(optionalSint64ExtensionLite)); + assertEqualsExactType(0, message.getExtension(optionalFixed32ExtensionLite)); + assertEqualsExactType(0L, message.getExtension(optionalFixed64ExtensionLite)); + assertEqualsExactType(0, message.getExtension(optionalSfixed32ExtensionLite)); + assertEqualsExactType(0L, message.getExtension(optionalSfixed64ExtensionLite)); + assertEqualsExactType(0F, message.getExtension(optionalFloatExtensionLite)); + assertEqualsExactType(0D, message.getExtension(optionalDoubleExtensionLite)); + assertEqualsExactType(false, message.getExtension(optionalBoolExtensionLite)); + assertEqualsExactType("", message.getExtension(optionalStringExtensionLite)); + assertEqualsExactType(ByteString.EMPTY, message.getExtension(optionalBytesExtensionLite)); + + // Embedded messages should also be clear. + Assert.assertFalse(message.getExtension(optionalGroupExtensionLite).hasA()); + Assert.assertFalse(message.getExtension(optionalNestedMessageExtensionLite).hasBb()); + Assert.assertFalse(message.getExtension(optionalForeignMessageExtensionLite).hasC()); + Assert.assertFalse(message.getExtension(optionalImportMessageExtensionLite).hasD()); + Assert.assertFalse(message.getExtension(optionalPublicImportMessageExtensionLite).hasE()); + Assert.assertFalse(message.getExtension(optionalLazyMessageExtensionLite).hasBb()); + + assertEqualsExactType(0, message.getExtension(optionalGroupExtensionLite).getA()); + assertEqualsExactType(0, message.getExtension(optionalNestedMessageExtensionLite).getBb()); + assertEqualsExactType(0, message.getExtension(optionalForeignMessageExtensionLite).getC()); + assertEqualsExactType(0, message.getExtension(optionalImportMessageExtensionLite).getD()); + assertEqualsExactType(0, message.getExtension(optionalPublicImportMessageExtensionLite).getE()); + assertEqualsExactType(0, message.getExtension(optionalLazyMessageExtensionLite).getBb()); + + // Enums without defaults are set to the first value in the enum. + assertEqualsExactType( + TestAllTypesLite.NestedEnum.FOO, message.getExtension(optionalNestedEnumExtensionLite)); + assertEqualsExactType( + ForeignEnumLite.FOREIGN_LITE_FOO, message.getExtension(optionalForeignEnumExtensionLite)); + assertEqualsExactType( + ImportEnumLite.IMPORT_LITE_FOO, message.getExtension(optionalImportEnumExtensionLite)); + + assertEqualsExactType("", message.getExtension(optionalStringPieceExtensionLite)); + assertEqualsExactType("", message.getExtension(optionalCordExtensionLite)); + + // Repeated fields are empty. + Assert.assertEquals(0, message.getExtensionCount(repeatedInt32ExtensionLite)); + Assert.assertEquals(0, message.getExtensionCount(repeatedInt64ExtensionLite)); + Assert.assertEquals(0, message.getExtensionCount(repeatedUint32ExtensionLite)); + Assert.assertEquals(0, message.getExtensionCount(repeatedUint64ExtensionLite)); + Assert.assertEquals(0, message.getExtensionCount(repeatedSint32ExtensionLite)); + Assert.assertEquals(0, message.getExtensionCount(repeatedSint64ExtensionLite)); + Assert.assertEquals(0, message.getExtensionCount(repeatedFixed32ExtensionLite)); + Assert.assertEquals(0, message.getExtensionCount(repeatedFixed64ExtensionLite)); + Assert.assertEquals(0, message.getExtensionCount(repeatedSfixed32ExtensionLite)); + Assert.assertEquals(0, message.getExtensionCount(repeatedSfixed64ExtensionLite)); + Assert.assertEquals(0, message.getExtensionCount(repeatedFloatExtensionLite)); + Assert.assertEquals(0, message.getExtensionCount(repeatedDoubleExtensionLite)); + Assert.assertEquals(0, message.getExtensionCount(repeatedBoolExtensionLite)); + Assert.assertEquals(0, message.getExtensionCount(repeatedStringExtensionLite)); + Assert.assertEquals(0, message.getExtensionCount(repeatedBytesExtensionLite)); + + Assert.assertEquals(0, message.getExtensionCount(repeatedGroupExtensionLite)); + Assert.assertEquals(0, message.getExtensionCount(repeatedNestedMessageExtensionLite)); + Assert.assertEquals(0, message.getExtensionCount(repeatedForeignMessageExtensionLite)); + Assert.assertEquals(0, message.getExtensionCount(repeatedImportMessageExtensionLite)); + Assert.assertEquals(0, message.getExtensionCount(repeatedLazyMessageExtensionLite)); + Assert.assertEquals(0, message.getExtensionCount(repeatedNestedEnumExtensionLite)); + Assert.assertEquals(0, message.getExtensionCount(repeatedForeignEnumExtensionLite)); + Assert.assertEquals(0, message.getExtensionCount(repeatedImportEnumExtensionLite)); + + Assert.assertEquals(0, message.getExtensionCount(repeatedStringPieceExtensionLite)); + Assert.assertEquals(0, message.getExtensionCount(repeatedCordExtensionLite)); + + // hasBlah() should also be false for all default fields. + Assert.assertFalse(message.hasExtension(defaultInt32ExtensionLite)); + Assert.assertFalse(message.hasExtension(defaultInt64ExtensionLite)); + Assert.assertFalse(message.hasExtension(defaultUint32ExtensionLite)); + Assert.assertFalse(message.hasExtension(defaultUint64ExtensionLite)); + Assert.assertFalse(message.hasExtension(defaultSint32ExtensionLite)); + Assert.assertFalse(message.hasExtension(defaultSint64ExtensionLite)); + Assert.assertFalse(message.hasExtension(defaultFixed32ExtensionLite)); + Assert.assertFalse(message.hasExtension(defaultFixed64ExtensionLite)); + Assert.assertFalse(message.hasExtension(defaultSfixed32ExtensionLite)); + Assert.assertFalse(message.hasExtension(defaultSfixed64ExtensionLite)); + Assert.assertFalse(message.hasExtension(defaultFloatExtensionLite)); + Assert.assertFalse(message.hasExtension(defaultDoubleExtensionLite)); + Assert.assertFalse(message.hasExtension(defaultBoolExtensionLite)); + Assert.assertFalse(message.hasExtension(defaultStringExtensionLite)); + Assert.assertFalse(message.hasExtension(defaultBytesExtensionLite)); + + Assert.assertFalse(message.hasExtension(defaultNestedEnumExtensionLite)); + Assert.assertFalse(message.hasExtension(defaultForeignEnumExtensionLite)); + Assert.assertFalse(message.hasExtension(defaultImportEnumExtensionLite)); + + Assert.assertFalse(message.hasExtension(defaultStringPieceExtensionLite)); + Assert.assertFalse(message.hasExtension(defaultCordExtensionLite)); + + // Fields with defaults have their default values (duh). + assertEqualsExactType(41, message.getExtension(defaultInt32ExtensionLite)); + assertEqualsExactType(42L, message.getExtension(defaultInt64ExtensionLite)); + assertEqualsExactType(43, message.getExtension(defaultUint32ExtensionLite)); + assertEqualsExactType(44L, message.getExtension(defaultUint64ExtensionLite)); + assertEqualsExactType(-45, message.getExtension(defaultSint32ExtensionLite)); + assertEqualsExactType(46L, message.getExtension(defaultSint64ExtensionLite)); + assertEqualsExactType(47, message.getExtension(defaultFixed32ExtensionLite)); + assertEqualsExactType(48L, message.getExtension(defaultFixed64ExtensionLite)); + assertEqualsExactType(49, message.getExtension(defaultSfixed32ExtensionLite)); + assertEqualsExactType(-50L, message.getExtension(defaultSfixed64ExtensionLite)); + assertEqualsExactType(51.5F, message.getExtension(defaultFloatExtensionLite)); + assertEqualsExactType(52e3D, message.getExtension(defaultDoubleExtensionLite)); + assertEqualsExactType(true, message.getExtension(defaultBoolExtensionLite)); + assertEqualsExactType("hello", message.getExtension(defaultStringExtensionLite)); + assertEqualsExactType(toBytes("world"), message.getExtension(defaultBytesExtensionLite)); + + assertEqualsExactType( + TestAllTypesLite.NestedEnum.BAR, message.getExtension(defaultNestedEnumExtensionLite)); + assertEqualsExactType( + ForeignEnumLite.FOREIGN_LITE_BAR, message.getExtension(defaultForeignEnumExtensionLite)); + assertEqualsExactType( + ImportEnumLite.IMPORT_LITE_BAR, message.getExtension(defaultImportEnumExtensionLite)); + + assertEqualsExactType("abc", message.getExtension(defaultStringPieceExtensionLite)); + assertEqualsExactType("123", message.getExtension(defaultCordExtensionLite)); + + Assert.assertFalse(message.hasExtension(oneofUint32ExtensionLite)); + Assert.assertFalse(message.hasExtension(oneofNestedMessageExtensionLite)); + Assert.assertFalse(message.hasExtension(oneofStringExtensionLite)); + Assert.assertFalse(message.hasExtension(oneofBytesExtensionLite)); + } + + // ------------------------------------------------------------------- + + /** + * Assert (using {@code junit.framework.Assert}} that all extensions of {@code message} are set to + * the values assigned by {@code setAllExtensions} followed by {@code modifyRepeatedExtensions}. + */ + public static void assertRepeatedExtensionsModified(TestAllExtensionsLiteOrBuilder 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.assertEquals(2, message.getExtensionCount(repeatedInt32ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedInt64ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedUint32ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedUint64ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedSint32ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedSint64ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed32ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed64ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtensionLite)); + + Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedForeignMessageExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtensionLite)); + + Assert.assertEquals(2, message.getExtensionCount(repeatedStringPieceExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(repeatedCordExtensionLite)); + + assertEqualsExactType(201, message.getExtension(repeatedInt32ExtensionLite, 0)); + assertEqualsExactType(202L, message.getExtension(repeatedInt64ExtensionLite, 0)); + assertEqualsExactType(203, message.getExtension(repeatedUint32ExtensionLite, 0)); + assertEqualsExactType(204L, message.getExtension(repeatedUint64ExtensionLite, 0)); + assertEqualsExactType(205, message.getExtension(repeatedSint32ExtensionLite, 0)); + assertEqualsExactType(206L, message.getExtension(repeatedSint64ExtensionLite, 0)); + assertEqualsExactType(207, message.getExtension(repeatedFixed32ExtensionLite, 0)); + assertEqualsExactType(208L, message.getExtension(repeatedFixed64ExtensionLite, 0)); + assertEqualsExactType(209, message.getExtension(repeatedSfixed32ExtensionLite, 0)); + assertEqualsExactType(210L, message.getExtension(repeatedSfixed64ExtensionLite, 0)); + assertEqualsExactType(211F, message.getExtension(repeatedFloatExtensionLite, 0)); + assertEqualsExactType(212D, message.getExtension(repeatedDoubleExtensionLite, 0)); + assertEqualsExactType(true, message.getExtension(repeatedBoolExtensionLite, 0)); + assertEqualsExactType("215", message.getExtension(repeatedStringExtensionLite, 0)); + assertEqualsExactType(toBytes("216"), message.getExtension(repeatedBytesExtensionLite, 0)); + + assertEqualsExactType(217, message.getExtension(repeatedGroupExtensionLite, 0).getA()); + assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtensionLite, 0).getBb()); + assertEqualsExactType(219, message.getExtension(repeatedForeignMessageExtensionLite, 0).getC()); + assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtensionLite, 0).getD()); + assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtensionLite, 0).getBb()); + + assertEqualsExactType( + TestAllTypesLite.NestedEnum.BAR, message.getExtension(repeatedNestedEnumExtensionLite, 0)); + assertEqualsExactType( + ForeignEnumLite.FOREIGN_LITE_BAR, + message.getExtension(repeatedForeignEnumExtensionLite, 0)); + assertEqualsExactType( + ImportEnumLite.IMPORT_LITE_BAR, message.getExtension(repeatedImportEnumExtensionLite, 0)); + + assertEqualsExactType("224", message.getExtension(repeatedStringPieceExtensionLite, 0)); + assertEqualsExactType("225", message.getExtension(repeatedCordExtensionLite, 0)); + + // Actually verify the second (modified) elements now. + assertEqualsExactType(501, message.getExtension(repeatedInt32ExtensionLite, 1)); + assertEqualsExactType(502L, message.getExtension(repeatedInt64ExtensionLite, 1)); + assertEqualsExactType(503, message.getExtension(repeatedUint32ExtensionLite, 1)); + assertEqualsExactType(504L, message.getExtension(repeatedUint64ExtensionLite, 1)); + assertEqualsExactType(505, message.getExtension(repeatedSint32ExtensionLite, 1)); + assertEqualsExactType(506L, message.getExtension(repeatedSint64ExtensionLite, 1)); + assertEqualsExactType(507, message.getExtension(repeatedFixed32ExtensionLite, 1)); + assertEqualsExactType(508L, message.getExtension(repeatedFixed64ExtensionLite, 1)); + assertEqualsExactType(509, message.getExtension(repeatedSfixed32ExtensionLite, 1)); + assertEqualsExactType(510L, message.getExtension(repeatedSfixed64ExtensionLite, 1)); + assertEqualsExactType(511F, message.getExtension(repeatedFloatExtensionLite, 1)); + assertEqualsExactType(512D, message.getExtension(repeatedDoubleExtensionLite, 1)); + assertEqualsExactType(true, message.getExtension(repeatedBoolExtensionLite, 1)); + assertEqualsExactType("515", message.getExtension(repeatedStringExtensionLite, 1)); + assertEqualsExactType(toBytes("516"), message.getExtension(repeatedBytesExtensionLite, 1)); + + assertEqualsExactType(517, message.getExtension(repeatedGroupExtensionLite, 1).getA()); + assertEqualsExactType(518, message.getExtension(repeatedNestedMessageExtensionLite, 1).getBb()); + assertEqualsExactType(519, message.getExtension(repeatedForeignMessageExtensionLite, 1).getC()); + assertEqualsExactType(520, message.getExtension(repeatedImportMessageExtensionLite, 1).getD()); + assertEqualsExactType(527, message.getExtension(repeatedLazyMessageExtensionLite, 1).getBb()); + + assertEqualsExactType( + TestAllTypesLite.NestedEnum.FOO, message.getExtension(repeatedNestedEnumExtensionLite, 1)); + assertEqualsExactType( + ForeignEnumLite.FOREIGN_LITE_FOO, + message.getExtension(repeatedForeignEnumExtensionLite, 1)); + assertEqualsExactType( + ImportEnumLite.IMPORT_LITE_FOO, message.getExtension(repeatedImportEnumExtensionLite, 1)); + + assertEqualsExactType("524", message.getExtension(repeatedStringPieceExtensionLite, 1)); + assertEqualsExactType("525", message.getExtension(repeatedCordExtensionLite, 1)); + } + + public static void assertPackedExtensionsSet(TestPackedExtensionsLite message) { + Assert.assertEquals(2, message.getExtensionCount(packedInt32ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(packedInt64ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(packedUint32ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(packedUint64ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(packedSint32ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(packedSint64ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(packedFixed32ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(packedFixed64ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(packedSfixed32ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(packedSfixed64ExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(packedFloatExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(packedDoubleExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(packedBoolExtensionLite)); + Assert.assertEquals(2, message.getExtensionCount(packedEnumExtensionLite)); + assertEqualsExactType(601, message.getExtension(packedInt32ExtensionLite, 0)); + assertEqualsExactType(602L, message.getExtension(packedInt64ExtensionLite, 0)); + assertEqualsExactType(603, message.getExtension(packedUint32ExtensionLite, 0)); + assertEqualsExactType(604L, message.getExtension(packedUint64ExtensionLite, 0)); + assertEqualsExactType(605, message.getExtension(packedSint32ExtensionLite, 0)); + assertEqualsExactType(606L, message.getExtension(packedSint64ExtensionLite, 0)); + assertEqualsExactType(607, message.getExtension(packedFixed32ExtensionLite, 0)); + assertEqualsExactType(608L, message.getExtension(packedFixed64ExtensionLite, 0)); + assertEqualsExactType(609, message.getExtension(packedSfixed32ExtensionLite, 0)); + assertEqualsExactType(610L, message.getExtension(packedSfixed64ExtensionLite, 0)); + assertEqualsExactType(611F, message.getExtension(packedFloatExtensionLite, 0)); + assertEqualsExactType(612D, message.getExtension(packedDoubleExtensionLite, 0)); + assertEqualsExactType(true, message.getExtension(packedBoolExtensionLite, 0)); + assertEqualsExactType( + ForeignEnumLite.FOREIGN_LITE_BAR, message.getExtension(packedEnumExtensionLite, 0)); + assertEqualsExactType(701, message.getExtension(packedInt32ExtensionLite, 1)); + assertEqualsExactType(702L, message.getExtension(packedInt64ExtensionLite, 1)); + assertEqualsExactType(703, message.getExtension(packedUint32ExtensionLite, 1)); + assertEqualsExactType(704L, message.getExtension(packedUint64ExtensionLite, 1)); + assertEqualsExactType(705, message.getExtension(packedSint32ExtensionLite, 1)); + assertEqualsExactType(706L, message.getExtension(packedSint64ExtensionLite, 1)); + assertEqualsExactType(707, message.getExtension(packedFixed32ExtensionLite, 1)); + assertEqualsExactType(708L, message.getExtension(packedFixed64ExtensionLite, 1)); + assertEqualsExactType(709, message.getExtension(packedSfixed32ExtensionLite, 1)); + assertEqualsExactType(710L, message.getExtension(packedSfixed64ExtensionLite, 1)); + assertEqualsExactType(711F, message.getExtension(packedFloatExtensionLite, 1)); + assertEqualsExactType(712D, message.getExtension(packedDoubleExtensionLite, 1)); + assertEqualsExactType(false, message.getExtension(packedBoolExtensionLite, 1)); + assertEqualsExactType( + ForeignEnumLite.FOREIGN_LITE_BAZ, message.getExtension(packedEnumExtensionLite, 1)); + } + + // =================================================================== + // oneof + public static void setOneof(TestOneof2.Builder message) { + message.setFooLazyMessage(TestOneof2.NestedMessage.newBuilder().setQuxInt(100).build()); + message.setBarString("101"); + message.setBazInt(102); + message.setBazString("103"); + } + + public static void assertOneofSet(TestOneof2 message) { + Assert.assertTrue(message.hasFooLazyMessage()); + Assert.assertTrue(message.getFooLazyMessage().hasQuxInt()); + + Assert.assertTrue(message.hasBarString()); + Assert.assertTrue(message.hasBazInt()); + Assert.assertTrue(message.hasBazString()); + + Assert.assertEquals(100, message.getFooLazyMessage().getQuxInt()); + Assert.assertEquals("101", message.getBarString()); + Assert.assertEquals(102, message.getBazInt()); + Assert.assertEquals("103", message.getBazString()); + } + + public static void assertAtMostOneFieldSetOneof(TestOneof2 message) { + int count = 0; + if (message.hasFooInt()) { + ++count; + } + if (message.hasFooString()) { + ++count; + } + if (message.hasFooCord()) { + ++count; + } + if (message.hasFooStringPiece()) { + ++count; + } + if (message.hasFooBytes()) { + ++count; + } + if (message.hasFooEnum()) { + ++count; + } + if (message.hasFooMessage()) { + ++count; + } + if (message.hasFooGroup()) { + ++count; + } + if (message.hasFooLazyMessage()) { + ++count; + } + Assert.assertTrue(count <= 1); + + count = 0; + if (message.hasBarInt()) { + ++count; + } + if (message.hasBarString()) { + ++count; + } + if (message.hasBarCord()) { + ++count; + } + if (message.hasBarStringPiece()) { + ++count; + } + if (message.hasBarBytes()) { + ++count; + } + if (message.hasBarEnum()) { + ++count; + } + Assert.assertTrue(count <= 1); + + switch (message.getFooCase()) { + case FOO_INT: + Assert.assertTrue(message.hasFooInt()); + break; + case FOO_STRING: + Assert.assertTrue(message.hasFooString()); + break; + case FOO_CORD: + Assert.assertTrue(message.hasFooCord()); + break; + case FOO_STRING_PIECE: + Assert.assertTrue(message.hasFooStringPiece()); + break; + case FOO_BYTES: + Assert.assertTrue(message.hasFooBytes()); + break; + case FOO_ENUM: + Assert.assertTrue(message.hasFooEnum()); + break; + case FOO_MESSAGE: + Assert.assertTrue(message.hasFooMessage()); + break; + case FOOGROUP: + Assert.assertTrue(message.hasFooGroup()); + break; + case FOO_LAZY_MESSAGE: + Assert.assertTrue(message.hasFooLazyMessage()); + break; + case FOO_NOT_SET: + break; + // TODO(b/18683919): go/enum-switch-lsc + } + } + + // ================================================================= + // BEGIN FULL-RUNTIME + + /** + * Performs the same things that the methods of {@code TestUtil} do, but via the reflection + * interface. This is its own class because it needs to know what descriptor to use. + */ + public static class ReflectionTester { + private final Descriptors.Descriptor baseDescriptor; + private final ExtensionRegistry extensionRegistry; + + private final Descriptors.FileDescriptor file; + private final Descriptors.FileDescriptor importFile; + private final Descriptors.FileDescriptor publicImportFile; + + private final Descriptors.Descriptor optionalGroup; + private final Descriptors.Descriptor repeatedGroup; + private final Descriptors.Descriptor nestedMessage; + private final Descriptors.Descriptor foreignMessage; + private final Descriptors.Descriptor importMessage; + private final Descriptors.Descriptor publicImportMessage; + + private final Descriptors.FieldDescriptor groupA; + private final Descriptors.FieldDescriptor repeatedGroupA; + private final Descriptors.FieldDescriptor nestedB; + private final Descriptors.FieldDescriptor foreignC; + private final Descriptors.FieldDescriptor importD; + private final Descriptors.FieldDescriptor importE; + + private final Descriptors.EnumDescriptor nestedEnum; + private final Descriptors.EnumDescriptor foreignEnum; + private final Descriptors.EnumDescriptor importEnum; + + private final Descriptors.EnumValueDescriptor nestedFoo; + private final Descriptors.EnumValueDescriptor nestedBar; + private final Descriptors.EnumValueDescriptor nestedBaz; + private final Descriptors.EnumValueDescriptor foreignFoo; + private final Descriptors.EnumValueDescriptor foreignBar; + private final Descriptors.EnumValueDescriptor foreignBaz; + private final Descriptors.EnumValueDescriptor importFoo; + private final Descriptors.EnumValueDescriptor importBar; + private final Descriptors.EnumValueDescriptor importBaz; + + /** + * Construct a {@code ReflectionTester} that will expect messages using the given descriptor. + * + *

Normally {@code baseDescriptor} should be a descriptor for the type {@code TestAllTypes}, + * defined in {@code google/protobuf/unittest.proto}. However, if {@code extensionRegistry} + * is non-null, then {@code baseDescriptor} should be for {@code TestAllExtensions} instead, and + * instead of reading and writing normal fields, the tester will read and write extensions. All + * of {@code TestAllExtensions}' extensions must be registered in the registry. + */ + public ReflectionTester( + Descriptors.Descriptor baseDescriptor, ExtensionRegistry extensionRegistry) { + this.baseDescriptor = baseDescriptor; + this.extensionRegistry = extensionRegistry; + + this.file = baseDescriptor.getFile(); + Assert.assertEquals(1, file.getDependencies().size()); + this.importFile = file.getDependencies().get(0); + this.publicImportFile = importFile.getDependencies().get(0); + + Descriptors.Descriptor testAllTypes; + if ("TestAllTypes".equals(baseDescriptor.getName())) { + testAllTypes = baseDescriptor; + } else { + testAllTypes = file.findMessageTypeByName("TestAllTypes"); + Assert.assertNotNull(testAllTypes); + } + + if (extensionRegistry == null) { + // Use testAllTypes, rather than baseDescriptor, to allow + // initialization using TestPackedTypes descriptors. These objects + // won't be used by the methods for packed fields. + this.optionalGroup = testAllTypes.findNestedTypeByName("OptionalGroup"); + this.repeatedGroup = testAllTypes.findNestedTypeByName("RepeatedGroup"); + } else { + this.optionalGroup = file.findMessageTypeByName("OptionalGroup_extension"); + this.repeatedGroup = file.findMessageTypeByName("RepeatedGroup_extension"); + } + this.nestedMessage = testAllTypes.findNestedTypeByName("NestedMessage"); + this.foreignMessage = file.findMessageTypeByName("ForeignMessage"); + this.importMessage = importFile.findMessageTypeByName("ImportMessage"); + this.publicImportMessage = publicImportFile.findMessageTypeByName("PublicImportMessage"); + + this.nestedEnum = testAllTypes.findEnumTypeByName("NestedEnum"); + this.foreignEnum = file.findEnumTypeByName("ForeignEnum"); + this.importEnum = importFile.findEnumTypeByName("ImportEnum"); + + Assert.assertNotNull(optionalGroup); + Assert.assertNotNull(repeatedGroup); + Assert.assertNotNull(nestedMessage); + Assert.assertNotNull(foreignMessage); + Assert.assertNotNull(importMessage); + Assert.assertNotNull(nestedEnum); + Assert.assertNotNull(foreignEnum); + Assert.assertNotNull(importEnum); + + this.nestedB = nestedMessage.findFieldByName("bb"); + this.foreignC = foreignMessage.findFieldByName("c"); + this.importD = importMessage.findFieldByName("d"); + this.importE = publicImportMessage.findFieldByName("e"); + this.nestedFoo = nestedEnum.findValueByName("FOO"); + this.nestedBar = nestedEnum.findValueByName("BAR"); + this.nestedBaz = nestedEnum.findValueByName("BAZ"); + this.foreignFoo = foreignEnum.findValueByName("FOREIGN_FOO"); + this.foreignBar = foreignEnum.findValueByName("FOREIGN_BAR"); + this.foreignBaz = foreignEnum.findValueByName("FOREIGN_BAZ"); + this.importFoo = importEnum.findValueByName("IMPORT_FOO"); + this.importBar = importEnum.findValueByName("IMPORT_BAR"); + this.importBaz = importEnum.findValueByName("IMPORT_BAZ"); + + this.groupA = optionalGroup.findFieldByName("a"); + this.repeatedGroupA = repeatedGroup.findFieldByName("a"); + + Assert.assertNotNull(groupA); + Assert.assertNotNull(repeatedGroupA); + Assert.assertNotNull(nestedB); + Assert.assertNotNull(foreignC); + Assert.assertNotNull(importD); + Assert.assertNotNull(importE); + Assert.assertNotNull(nestedFoo); + Assert.assertNotNull(nestedBar); + Assert.assertNotNull(nestedBaz); + Assert.assertNotNull(foreignFoo); + Assert.assertNotNull(foreignBar); + Assert.assertNotNull(foreignBaz); + Assert.assertNotNull(importFoo); + Assert.assertNotNull(importBar); + Assert.assertNotNull(importBaz); + } + + /** Shorthand to get a FieldDescriptor for a field of unittest::TestAllTypes. */ + Descriptors.FieldDescriptor f(String name) { + Descriptors.FieldDescriptor result; + if (extensionRegistry == null) { + result = baseDescriptor.findFieldByName(name); + } else { + result = file.findExtensionByName(name + "_extension"); + } + Assert.assertNotNull(result); + return result; + } + + /** + * Calls {@code parent.newBuilderForField()} or uses the {@code ExtensionRegistry} to find an + * appropriate builder, depending on what type is being tested. + */ + private Message.Builder newBuilderForField( + Message.Builder parent, Descriptors.FieldDescriptor field) { + if (extensionRegistry == null) { + return parent.newBuilderForField(field); + } else { + ExtensionRegistry.ExtensionInfo extension = + extensionRegistry.findImmutableExtensionByNumber( + field.getContainingType(), field.getNumber()); + Assert.assertNotNull(extension); + Assert.assertNotNull(extension.defaultInstance); + return extension.defaultInstance.newBuilderForType(); + } + } + + // ------------------------------------------------------------------- + + /** + * Set every field of {@code message} to the values expected by {@code assertAllFieldsSet()}, + * using the {@link Message.Builder} reflection interface. + */ + void setAllFieldsViaReflection(Message.Builder message) { + message.setField(f("optional_int32"), 101); + message.setField(f("optional_int64"), 102L); + message.setField(f("optional_uint32"), 103); + message.setField(f("optional_uint64"), 104L); + message.setField(f("optional_sint32"), 105); + message.setField(f("optional_sint64"), 106L); + message.setField(f("optional_fixed32"), 107); + message.setField(f("optional_fixed64"), 108L); + message.setField(f("optional_sfixed32"), 109); + message.setField(f("optional_sfixed64"), 110L); + message.setField(f("optional_float"), 111F); + message.setField(f("optional_double"), 112D); + message.setField(f("optional_bool"), true); + message.setField(f("optional_string"), "115"); + message.setField(f("optional_bytes"), toBytes("116")); + + message.setField( + f("optionalgroup"), + newBuilderForField(message, f("optionalgroup")).setField(groupA, 117).build()); + message.setField( + f("optional_nested_message"), + newBuilderForField(message, f("optional_nested_message")).setField(nestedB, 118).build()); + message.setField( + f("optional_foreign_message"), + newBuilderForField(message, f("optional_foreign_message")) + .setField(foreignC, 119) + .build()); + message.setField( + f("optional_import_message"), + newBuilderForField(message, f("optional_import_message")).setField(importD, 120).build()); + message.setField( + f("optional_public_import_message"), + newBuilderForField(message, f("optional_public_import_message")) + .setField(importE, 126) + .build()); + message.setField( + f("optional_lazy_message"), + newBuilderForField(message, f("optional_lazy_message")).setField(nestedB, 127).build()); + + message.setField(f("optional_nested_enum"), nestedBaz); + message.setField(f("optional_foreign_enum"), foreignBaz); + message.setField(f("optional_import_enum"), importBaz); + + message.setField(f("optional_string_piece"), "124"); + message.setField(f("optional_cord"), "125"); + + // ----------------------------------------------------------------- + + message.addRepeatedField(f("repeated_int32"), 201); + message.addRepeatedField(f("repeated_int64"), 202L); + message.addRepeatedField(f("repeated_uint32"), 203); + message.addRepeatedField(f("repeated_uint64"), 204L); + message.addRepeatedField(f("repeated_sint32"), 205); + message.addRepeatedField(f("repeated_sint64"), 206L); + message.addRepeatedField(f("repeated_fixed32"), 207); + message.addRepeatedField(f("repeated_fixed64"), 208L); + message.addRepeatedField(f("repeated_sfixed32"), 209); + message.addRepeatedField(f("repeated_sfixed64"), 210L); + message.addRepeatedField(f("repeated_float"), 211F); + message.addRepeatedField(f("repeated_double"), 212D); + message.addRepeatedField(f("repeated_bool"), true); + message.addRepeatedField(f("repeated_string"), "215"); + message.addRepeatedField(f("repeated_bytes"), toBytes("216")); + + message.addRepeatedField( + f("repeatedgroup"), + newBuilderForField(message, f("repeatedgroup")).setField(repeatedGroupA, 217).build()); + message.addRepeatedField( + f("repeated_nested_message"), + newBuilderForField(message, f("repeated_nested_message")).setField(nestedB, 218).build()); + message.addRepeatedField( + f("repeated_foreign_message"), + newBuilderForField(message, f("repeated_foreign_message")) + .setField(foreignC, 219) + .build()); + message.addRepeatedField( + f("repeated_import_message"), + newBuilderForField(message, f("repeated_import_message")).setField(importD, 220).build()); + message.addRepeatedField( + f("repeated_lazy_message"), + newBuilderForField(message, f("repeated_lazy_message")).setField(nestedB, 227).build()); + + message.addRepeatedField(f("repeated_nested_enum"), nestedBar); + message.addRepeatedField(f("repeated_foreign_enum"), foreignBar); + message.addRepeatedField(f("repeated_import_enum"), importBar); + + message.addRepeatedField(f("repeated_string_piece"), "224"); + message.addRepeatedField(f("repeated_cord"), "225"); + + // Add a second one of each field. + message.addRepeatedField(f("repeated_int32"), 301); + message.addRepeatedField(f("repeated_int64"), 302L); + message.addRepeatedField(f("repeated_uint32"), 303); + message.addRepeatedField(f("repeated_uint64"), 304L); + message.addRepeatedField(f("repeated_sint32"), 305); + message.addRepeatedField(f("repeated_sint64"), 306L); + message.addRepeatedField(f("repeated_fixed32"), 307); + message.addRepeatedField(f("repeated_fixed64"), 308L); + message.addRepeatedField(f("repeated_sfixed32"), 309); + message.addRepeatedField(f("repeated_sfixed64"), 310L); + message.addRepeatedField(f("repeated_float"), 311F); + message.addRepeatedField(f("repeated_double"), 312D); + message.addRepeatedField(f("repeated_bool"), false); + message.addRepeatedField(f("repeated_string"), "315"); + message.addRepeatedField(f("repeated_bytes"), toBytes("316")); + + message.addRepeatedField( + f("repeatedgroup"), + newBuilderForField(message, f("repeatedgroup")).setField(repeatedGroupA, 317).build()); + message.addRepeatedField( + f("repeated_nested_message"), + newBuilderForField(message, f("repeated_nested_message")).setField(nestedB, 318).build()); + message.addRepeatedField( + f("repeated_foreign_message"), + newBuilderForField(message, f("repeated_foreign_message")) + .setField(foreignC, 319) + .build()); + message.addRepeatedField( + f("repeated_import_message"), + newBuilderForField(message, f("repeated_import_message")).setField(importD, 320).build()); + message.addRepeatedField( + f("repeated_lazy_message"), + newBuilderForField(message, f("repeated_lazy_message")).setField(nestedB, 327).build()); + + message.addRepeatedField(f("repeated_nested_enum"), nestedBaz); + message.addRepeatedField(f("repeated_foreign_enum"), foreignBaz); + message.addRepeatedField(f("repeated_import_enum"), importBaz); + + message.addRepeatedField(f("repeated_string_piece"), "324"); + message.addRepeatedField(f("repeated_cord"), "325"); + + // ----------------------------------------------------------------- + + message.setField(f("default_int32"), 401); + message.setField(f("default_int64"), 402L); + message.setField(f("default_uint32"), 403); + message.setField(f("default_uint64"), 404L); + message.setField(f("default_sint32"), 405); + message.setField(f("default_sint64"), 406L); + message.setField(f("default_fixed32"), 407); + message.setField(f("default_fixed64"), 408L); + message.setField(f("default_sfixed32"), 409); + message.setField(f("default_sfixed64"), 410L); + message.setField(f("default_float"), 411F); + message.setField(f("default_double"), 412D); + message.setField(f("default_bool"), false); + message.setField(f("default_string"), "415"); + message.setField(f("default_bytes"), toBytes("416")); + + message.setField(f("default_nested_enum"), nestedFoo); + message.setField(f("default_foreign_enum"), foreignFoo); + message.setField(f("default_import_enum"), importFoo); + + message.setField(f("default_string_piece"), "424"); + message.setField(f("default_cord"), "425"); + + message.setField(f("oneof_uint32"), 601); + message.setField( + f("oneof_nested_message"), + newBuilderForField(message, f("oneof_nested_message")).setField(nestedB, 602).build()); + message.setField(f("oneof_string"), "603"); + message.setField(f("oneof_bytes"), toBytes("604")); + } + + // ------------------------------------------------------------------- + + /** + * Modify the repeated fields of {@code message} to contain the values expected by {@code + * assertRepeatedFieldsModified()}, using the {@link Message.Builder} reflection interface. + */ + void modifyRepeatedFieldsViaReflection(Message.Builder message) { + message.setRepeatedField(f("repeated_int32"), 1, 501); + message.setRepeatedField(f("repeated_int64"), 1, 502L); + message.setRepeatedField(f("repeated_uint32"), 1, 503); + message.setRepeatedField(f("repeated_uint64"), 1, 504L); + message.setRepeatedField(f("repeated_sint32"), 1, 505); + message.setRepeatedField(f("repeated_sint64"), 1, 506L); + message.setRepeatedField(f("repeated_fixed32"), 1, 507); + message.setRepeatedField(f("repeated_fixed64"), 1, 508L); + message.setRepeatedField(f("repeated_sfixed32"), 1, 509); + message.setRepeatedField(f("repeated_sfixed64"), 1, 510L); + message.setRepeatedField(f("repeated_float"), 1, 511F); + message.setRepeatedField(f("repeated_double"), 1, 512D); + message.setRepeatedField(f("repeated_bool"), 1, true); + message.setRepeatedField(f("repeated_string"), 1, "515"); + message.setRepeatedField(f("repeated_bytes"), 1, toBytes("516")); + + message.setRepeatedField( + f("repeatedgroup"), + 1, + newBuilderForField(message, f("repeatedgroup")).setField(repeatedGroupA, 517).build()); + message.setRepeatedField( + f("repeated_nested_message"), + 1, + newBuilderForField(message, f("repeated_nested_message")).setField(nestedB, 518).build()); + message.setRepeatedField( + f("repeated_foreign_message"), + 1, + newBuilderForField(message, f("repeated_foreign_message")) + .setField(foreignC, 519) + .build()); + message.setRepeatedField( + f("repeated_import_message"), + 1, + newBuilderForField(message, f("repeated_import_message")).setField(importD, 520).build()); + message.setRepeatedField( + f("repeated_lazy_message"), + 1, + newBuilderForField(message, f("repeated_lazy_message")).setField(nestedB, 527).build()); + + message.setRepeatedField(f("repeated_nested_enum"), 1, nestedFoo); + message.setRepeatedField(f("repeated_foreign_enum"), 1, foreignFoo); + message.setRepeatedField(f("repeated_import_enum"), 1, importFoo); + + message.setRepeatedField(f("repeated_string_piece"), 1, "524"); + message.setRepeatedField(f("repeated_cord"), 1, "525"); + } + + // ------------------------------------------------------------------- + + /** + * Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are set to + * the values assigned by {@code setAllFields}, using the {@link Message} reflection interface. + */ + public void assertAllFieldsSetViaReflection(MessageOrBuilder message) { + Assert.assertTrue(message.hasField(f("optional_int32"))); + Assert.assertTrue(message.hasField(f("optional_int64"))); + Assert.assertTrue(message.hasField(f("optional_uint32"))); + Assert.assertTrue(message.hasField(f("optional_uint64"))); + Assert.assertTrue(message.hasField(f("optional_sint32"))); + Assert.assertTrue(message.hasField(f("optional_sint64"))); + Assert.assertTrue(message.hasField(f("optional_fixed32"))); + Assert.assertTrue(message.hasField(f("optional_fixed64"))); + Assert.assertTrue(message.hasField(f("optional_sfixed32"))); + Assert.assertTrue(message.hasField(f("optional_sfixed64"))); + Assert.assertTrue(message.hasField(f("optional_float"))); + Assert.assertTrue(message.hasField(f("optional_double"))); + Assert.assertTrue(message.hasField(f("optional_bool"))); + Assert.assertTrue(message.hasField(f("optional_string"))); + Assert.assertTrue(message.hasField(f("optional_bytes"))); + + Assert.assertTrue(message.hasField(f("optionalgroup"))); + Assert.assertTrue(message.hasField(f("optional_nested_message"))); + Assert.assertTrue(message.hasField(f("optional_foreign_message"))); + Assert.assertTrue(message.hasField(f("optional_import_message"))); + + Assert.assertTrue(((Message) message.getField(f("optionalgroup"))).hasField(groupA)); + Assert.assertTrue( + ((Message) message.getField(f("optional_nested_message"))).hasField(nestedB)); + Assert.assertTrue( + ((Message) message.getField(f("optional_foreign_message"))).hasField(foreignC)); + Assert.assertTrue( + ((Message) message.getField(f("optional_import_message"))).hasField(importD)); + + Assert.assertTrue(message.hasField(f("optional_nested_enum"))); + Assert.assertTrue(message.hasField(f("optional_foreign_enum"))); + Assert.assertTrue(message.hasField(f("optional_import_enum"))); + + Assert.assertTrue(message.hasField(f("optional_string_piece"))); + Assert.assertTrue(message.hasField(f("optional_cord"))); + + Assert.assertEquals(101, message.getField(f("optional_int32"))); + Assert.assertEquals(102L, message.getField(f("optional_int64"))); + Assert.assertEquals(103, message.getField(f("optional_uint32"))); + Assert.assertEquals(104L, message.getField(f("optional_uint64"))); + Assert.assertEquals(105, message.getField(f("optional_sint32"))); + Assert.assertEquals(106L, message.getField(f("optional_sint64"))); + Assert.assertEquals(107, message.getField(f("optional_fixed32"))); + Assert.assertEquals(108L, message.getField(f("optional_fixed64"))); + Assert.assertEquals(109, message.getField(f("optional_sfixed32"))); + Assert.assertEquals(110L, message.getField(f("optional_sfixed64"))); + Assert.assertEquals(111F, message.getField(f("optional_float"))); + Assert.assertEquals(112D, message.getField(f("optional_double"))); + Assert.assertEquals(true, message.getField(f("optional_bool"))); + Assert.assertEquals("115", message.getField(f("optional_string"))); + Assert.assertEquals(toBytes("116"), message.getField(f("optional_bytes"))); + + Assert.assertEquals(117, ((Message) message.getField(f("optionalgroup"))).getField(groupA)); + Assert.assertEquals( + 118, ((Message) message.getField(f("optional_nested_message"))).getField(nestedB)); + Assert.assertEquals( + 119, ((Message) message.getField(f("optional_foreign_message"))).getField(foreignC)); + Assert.assertEquals( + 120, ((Message) message.getField(f("optional_import_message"))).getField(importD)); + Assert.assertEquals( + 126, ((Message) message.getField(f("optional_public_import_message"))).getField(importE)); + Assert.assertEquals( + 127, ((Message) message.getField(f("optional_lazy_message"))).getField(nestedB)); + + Assert.assertEquals(nestedBaz, message.getField(f("optional_nested_enum"))); + Assert.assertEquals(foreignBaz, message.getField(f("optional_foreign_enum"))); + Assert.assertEquals(importBaz, message.getField(f("optional_import_enum"))); + + Assert.assertEquals("124", message.getField(f("optional_string_piece"))); + Assert.assertEquals("125", message.getField(f("optional_cord"))); + + // ----------------------------------------------------------------- + + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sfixed32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sfixed64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_float"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_double"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bool"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bytes"))); + + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeatedgroup"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_message"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_message"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_message"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_lazy_message"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_enum"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_enum"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_enum"))); + + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string_piece"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_cord"))); + + Assert.assertEquals(201, message.getRepeatedField(f("repeated_int32"), 0)); + Assert.assertEquals(202L, message.getRepeatedField(f("repeated_int64"), 0)); + Assert.assertEquals(203, message.getRepeatedField(f("repeated_uint32"), 0)); + Assert.assertEquals(204L, message.getRepeatedField(f("repeated_uint64"), 0)); + Assert.assertEquals(205, message.getRepeatedField(f("repeated_sint32"), 0)); + Assert.assertEquals(206L, message.getRepeatedField(f("repeated_sint64"), 0)); + Assert.assertEquals(207, message.getRepeatedField(f("repeated_fixed32"), 0)); + Assert.assertEquals(208L, message.getRepeatedField(f("repeated_fixed64"), 0)); + Assert.assertEquals(209, message.getRepeatedField(f("repeated_sfixed32"), 0)); + Assert.assertEquals(210L, message.getRepeatedField(f("repeated_sfixed64"), 0)); + Assert.assertEquals(211F, message.getRepeatedField(f("repeated_float"), 0)); + Assert.assertEquals(212D, message.getRepeatedField(f("repeated_double"), 0)); + Assert.assertEquals(true, message.getRepeatedField(f("repeated_bool"), 0)); + Assert.assertEquals("215", message.getRepeatedField(f("repeated_string"), 0)); + Assert.assertEquals(toBytes("216"), message.getRepeatedField(f("repeated_bytes"), 0)); + + Assert.assertEquals( + 217, + ((Message) message.getRepeatedField(f("repeatedgroup"), 0)).getField(repeatedGroupA)); + Assert.assertEquals( + 218, + ((Message) message.getRepeatedField(f("repeated_nested_message"), 0)).getField(nestedB)); + Assert.assertEquals( + 219, + ((Message) message.getRepeatedField(f("repeated_foreign_message"), 0)) + .getField(foreignC)); + Assert.assertEquals( + 220, + ((Message) message.getRepeatedField(f("repeated_import_message"), 0)).getField(importD)); + Assert.assertEquals( + 227, + ((Message) message.getRepeatedField(f("repeated_lazy_message"), 0)).getField(nestedB)); + + Assert.assertEquals(nestedBar, message.getRepeatedField(f("repeated_nested_enum"), 0)); + Assert.assertEquals(foreignBar, message.getRepeatedField(f("repeated_foreign_enum"), 0)); + Assert.assertEquals(importBar, message.getRepeatedField(f("repeated_import_enum"), 0)); + + Assert.assertEquals("224", message.getRepeatedField(f("repeated_string_piece"), 0)); + Assert.assertEquals("225", message.getRepeatedField(f("repeated_cord"), 0)); + + Assert.assertEquals(301, message.getRepeatedField(f("repeated_int32"), 1)); + Assert.assertEquals(302L, message.getRepeatedField(f("repeated_int64"), 1)); + Assert.assertEquals(303, message.getRepeatedField(f("repeated_uint32"), 1)); + Assert.assertEquals(304L, message.getRepeatedField(f("repeated_uint64"), 1)); + Assert.assertEquals(305, message.getRepeatedField(f("repeated_sint32"), 1)); + Assert.assertEquals(306L, message.getRepeatedField(f("repeated_sint64"), 1)); + Assert.assertEquals(307, message.getRepeatedField(f("repeated_fixed32"), 1)); + Assert.assertEquals(308L, message.getRepeatedField(f("repeated_fixed64"), 1)); + Assert.assertEquals(309, message.getRepeatedField(f("repeated_sfixed32"), 1)); + Assert.assertEquals(310L, message.getRepeatedField(f("repeated_sfixed64"), 1)); + Assert.assertEquals(311F, message.getRepeatedField(f("repeated_float"), 1)); + Assert.assertEquals(312D, message.getRepeatedField(f("repeated_double"), 1)); + Assert.assertEquals(false, message.getRepeatedField(f("repeated_bool"), 1)); + Assert.assertEquals("315", message.getRepeatedField(f("repeated_string"), 1)); + Assert.assertEquals(toBytes("316"), message.getRepeatedField(f("repeated_bytes"), 1)); + + Assert.assertEquals( + 317, + ((Message) message.getRepeatedField(f("repeatedgroup"), 1)).getField(repeatedGroupA)); + Assert.assertEquals( + 318, + ((Message) message.getRepeatedField(f("repeated_nested_message"), 1)).getField(nestedB)); + Assert.assertEquals( + 319, + ((Message) message.getRepeatedField(f("repeated_foreign_message"), 1)) + .getField(foreignC)); + Assert.assertEquals( + 320, + ((Message) message.getRepeatedField(f("repeated_import_message"), 1)).getField(importD)); + Assert.assertEquals( + 327, + ((Message) message.getRepeatedField(f("repeated_lazy_message"), 1)).getField(nestedB)); + + Assert.assertEquals(nestedBaz, message.getRepeatedField(f("repeated_nested_enum"), 1)); + Assert.assertEquals(foreignBaz, message.getRepeatedField(f("repeated_foreign_enum"), 1)); + Assert.assertEquals(importBaz, message.getRepeatedField(f("repeated_import_enum"), 1)); + + Assert.assertEquals("324", message.getRepeatedField(f("repeated_string_piece"), 1)); + Assert.assertEquals("325", message.getRepeatedField(f("repeated_cord"), 1)); + + // ----------------------------------------------------------------- + + Assert.assertTrue(message.hasField(f("default_int32"))); + Assert.assertTrue(message.hasField(f("default_int64"))); + Assert.assertTrue(message.hasField(f("default_uint32"))); + Assert.assertTrue(message.hasField(f("default_uint64"))); + Assert.assertTrue(message.hasField(f("default_sint32"))); + Assert.assertTrue(message.hasField(f("default_sint64"))); + Assert.assertTrue(message.hasField(f("default_fixed32"))); + Assert.assertTrue(message.hasField(f("default_fixed64"))); + Assert.assertTrue(message.hasField(f("default_sfixed32"))); + Assert.assertTrue(message.hasField(f("default_sfixed64"))); + Assert.assertTrue(message.hasField(f("default_float"))); + Assert.assertTrue(message.hasField(f("default_double"))); + Assert.assertTrue(message.hasField(f("default_bool"))); + Assert.assertTrue(message.hasField(f("default_string"))); + Assert.assertTrue(message.hasField(f("default_bytes"))); + + Assert.assertTrue(message.hasField(f("default_nested_enum"))); + Assert.assertTrue(message.hasField(f("default_foreign_enum"))); + Assert.assertTrue(message.hasField(f("default_import_enum"))); + + Assert.assertTrue(message.hasField(f("default_string_piece"))); + Assert.assertTrue(message.hasField(f("default_cord"))); + + Assert.assertEquals(401, message.getField(f("default_int32"))); + Assert.assertEquals(402L, message.getField(f("default_int64"))); + Assert.assertEquals(403, message.getField(f("default_uint32"))); + Assert.assertEquals(404L, message.getField(f("default_uint64"))); + Assert.assertEquals(405, message.getField(f("default_sint32"))); + Assert.assertEquals(406L, message.getField(f("default_sint64"))); + Assert.assertEquals(407, message.getField(f("default_fixed32"))); + Assert.assertEquals(408L, message.getField(f("default_fixed64"))); + Assert.assertEquals(409, message.getField(f("default_sfixed32"))); + Assert.assertEquals(410L, message.getField(f("default_sfixed64"))); + Assert.assertEquals(411F, message.getField(f("default_float"))); + Assert.assertEquals(412D, message.getField(f("default_double"))); + Assert.assertEquals(false, message.getField(f("default_bool"))); + Assert.assertEquals("415", message.getField(f("default_string"))); + Assert.assertEquals(toBytes("416"), message.getField(f("default_bytes"))); + + Assert.assertEquals(nestedFoo, message.getField(f("default_nested_enum"))); + Assert.assertEquals(foreignFoo, message.getField(f("default_foreign_enum"))); + Assert.assertEquals(importFoo, message.getField(f("default_import_enum"))); + + Assert.assertEquals("424", message.getField(f("default_string_piece"))); + Assert.assertEquals("425", message.getField(f("default_cord"))); + + Assert.assertTrue(message.hasField(f("oneof_bytes"))); + Assert.assertEquals(toBytes("604"), message.getField(f("oneof_bytes"))); + + if (extensionRegistry == null) { + Assert.assertFalse(message.hasField(f("oneof_uint32"))); + Assert.assertFalse(message.hasField(f("oneof_nested_message"))); + Assert.assertFalse(message.hasField(f("oneof_string"))); + } else { + Assert.assertTrue(message.hasField(f("oneof_uint32"))); + Assert.assertTrue(message.hasField(f("oneof_nested_message"))); + Assert.assertTrue(message.hasField(f("oneof_string"))); + Assert.assertEquals(601, message.getField(f("oneof_uint32"))); + Assert.assertEquals( + 602, + ((MessageOrBuilder) message.getField(f("oneof_nested_message"))).getField(nestedB)); + Assert.assertEquals("603", message.getField(f("oneof_string"))); + } + } + + // ------------------------------------------------------------------- + + /** + * Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are cleared, + * and that getting the fields returns their default values, using the {@link Message} + * reflection interface. + */ + public void assertClearViaReflection(MessageOrBuilder message) { + // has_blah() should initially be false for all optional fields. + Assert.assertFalse(message.hasField(f("optional_int32"))); + Assert.assertFalse(message.hasField(f("optional_int64"))); + Assert.assertFalse(message.hasField(f("optional_uint32"))); + Assert.assertFalse(message.hasField(f("optional_uint64"))); + Assert.assertFalse(message.hasField(f("optional_sint32"))); + Assert.assertFalse(message.hasField(f("optional_sint64"))); + Assert.assertFalse(message.hasField(f("optional_fixed32"))); + Assert.assertFalse(message.hasField(f("optional_fixed64"))); + Assert.assertFalse(message.hasField(f("optional_sfixed32"))); + Assert.assertFalse(message.hasField(f("optional_sfixed64"))); + Assert.assertFalse(message.hasField(f("optional_float"))); + Assert.assertFalse(message.hasField(f("optional_double"))); + Assert.assertFalse(message.hasField(f("optional_bool"))); + Assert.assertFalse(message.hasField(f("optional_string"))); + Assert.assertFalse(message.hasField(f("optional_bytes"))); + + Assert.assertFalse(message.hasField(f("optionalgroup"))); + Assert.assertFalse(message.hasField(f("optional_nested_message"))); + Assert.assertFalse(message.hasField(f("optional_foreign_message"))); + Assert.assertFalse(message.hasField(f("optional_import_message"))); + + Assert.assertFalse(message.hasField(f("optional_nested_enum"))); + Assert.assertFalse(message.hasField(f("optional_foreign_enum"))); + Assert.assertFalse(message.hasField(f("optional_import_enum"))); + + Assert.assertFalse(message.hasField(f("optional_string_piece"))); + Assert.assertFalse(message.hasField(f("optional_cord"))); + + // Optional fields without defaults are set to zero or something like it. + Assert.assertEquals(0, message.getField(f("optional_int32"))); + Assert.assertEquals(0L, message.getField(f("optional_int64"))); + Assert.assertEquals(0, message.getField(f("optional_uint32"))); + Assert.assertEquals(0L, message.getField(f("optional_uint64"))); + Assert.assertEquals(0, message.getField(f("optional_sint32"))); + Assert.assertEquals(0L, message.getField(f("optional_sint64"))); + Assert.assertEquals(0, message.getField(f("optional_fixed32"))); + Assert.assertEquals(0L, message.getField(f("optional_fixed64"))); + Assert.assertEquals(0, message.getField(f("optional_sfixed32"))); + Assert.assertEquals(0L, message.getField(f("optional_sfixed64"))); + Assert.assertEquals(0F, message.getField(f("optional_float"))); + Assert.assertEquals(0D, message.getField(f("optional_double"))); + Assert.assertEquals(false, message.getField(f("optional_bool"))); + Assert.assertEquals("", message.getField(f("optional_string"))); + Assert.assertEquals(ByteString.EMPTY, message.getField(f("optional_bytes"))); + + // Embedded messages should also be clear. + Assert.assertFalse(((Message) message.getField(f("optionalgroup"))).hasField(groupA)); + Assert.assertFalse( + ((Message) message.getField(f("optional_nested_message"))).hasField(nestedB)); + Assert.assertFalse( + ((Message) message.getField(f("optional_foreign_message"))).hasField(foreignC)); + Assert.assertFalse( + ((Message) message.getField(f("optional_import_message"))).hasField(importD)); + Assert.assertFalse( + ((Message) message.getField(f("optional_public_import_message"))).hasField(importE)); + Assert.assertFalse( + ((Message) message.getField(f("optional_lazy_message"))).hasField(nestedB)); + + Assert.assertEquals(0, ((Message) message.getField(f("optionalgroup"))).getField(groupA)); + Assert.assertEquals( + 0, ((Message) message.getField(f("optional_nested_message"))).getField(nestedB)); + Assert.assertEquals( + 0, ((Message) message.getField(f("optional_foreign_message"))).getField(foreignC)); + Assert.assertEquals( + 0, ((Message) message.getField(f("optional_import_message"))).getField(importD)); + Assert.assertEquals( + 0, ((Message) message.getField(f("optional_public_import_message"))).getField(importE)); + Assert.assertEquals( + 0, ((Message) message.getField(f("optional_lazy_message"))).getField(nestedB)); + + // Enums without defaults are set to the first value in the enum. + Assert.assertEquals(nestedFoo, message.getField(f("optional_nested_enum"))); + Assert.assertEquals(foreignFoo, message.getField(f("optional_foreign_enum"))); + Assert.assertEquals(importFoo, message.getField(f("optional_import_enum"))); + + Assert.assertEquals("", message.getField(f("optional_string_piece"))); + Assert.assertEquals("", message.getField(f("optional_cord"))); + + // Repeated fields are empty. + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_int32"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_int64"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_uint32"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_uint64"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sint32"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sint64"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_fixed32"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_fixed64"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sfixed32"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sfixed64"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_float"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_double"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_bool"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_string"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_bytes"))); + + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeatedgroup"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_nested_message"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_foreign_message"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_import_message"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_lazy_message"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_nested_enum"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_foreign_enum"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_import_enum"))); + + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_string_piece"))); + Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_cord"))); + + // has_blah() should also be false for all default fields. + Assert.assertFalse(message.hasField(f("default_int32"))); + Assert.assertFalse(message.hasField(f("default_int64"))); + Assert.assertFalse(message.hasField(f("default_uint32"))); + Assert.assertFalse(message.hasField(f("default_uint64"))); + Assert.assertFalse(message.hasField(f("default_sint32"))); + Assert.assertFalse(message.hasField(f("default_sint64"))); + Assert.assertFalse(message.hasField(f("default_fixed32"))); + Assert.assertFalse(message.hasField(f("default_fixed64"))); + Assert.assertFalse(message.hasField(f("default_sfixed32"))); + Assert.assertFalse(message.hasField(f("default_sfixed64"))); + Assert.assertFalse(message.hasField(f("default_float"))); + Assert.assertFalse(message.hasField(f("default_double"))); + Assert.assertFalse(message.hasField(f("default_bool"))); + Assert.assertFalse(message.hasField(f("default_string"))); + Assert.assertFalse(message.hasField(f("default_bytes"))); + + Assert.assertFalse(message.hasField(f("default_nested_enum"))); + Assert.assertFalse(message.hasField(f("default_foreign_enum"))); + Assert.assertFalse(message.hasField(f("default_import_enum"))); + + Assert.assertFalse(message.hasField(f("default_string_piece"))); + Assert.assertFalse(message.hasField(f("default_cord"))); + + // Fields with defaults have their default values (duh). + Assert.assertEquals(41, message.getField(f("default_int32"))); + Assert.assertEquals(42L, message.getField(f("default_int64"))); + Assert.assertEquals(43, message.getField(f("default_uint32"))); + Assert.assertEquals(44L, message.getField(f("default_uint64"))); + Assert.assertEquals(-45, message.getField(f("default_sint32"))); + Assert.assertEquals(46L, message.getField(f("default_sint64"))); + Assert.assertEquals(47, message.getField(f("default_fixed32"))); + Assert.assertEquals(48L, message.getField(f("default_fixed64"))); + Assert.assertEquals(49, message.getField(f("default_sfixed32"))); + Assert.assertEquals(-50L, message.getField(f("default_sfixed64"))); + Assert.assertEquals(51.5F, message.getField(f("default_float"))); + Assert.assertEquals(52e3D, message.getField(f("default_double"))); + Assert.assertEquals(true, message.getField(f("default_bool"))); + Assert.assertEquals("hello", message.getField(f("default_string"))); + Assert.assertEquals(toBytes("world"), message.getField(f("default_bytes"))); + + Assert.assertEquals(nestedBar, message.getField(f("default_nested_enum"))); + Assert.assertEquals(foreignBar, message.getField(f("default_foreign_enum"))); + Assert.assertEquals(importBar, message.getField(f("default_import_enum"))); + + Assert.assertEquals("abc", message.getField(f("default_string_piece"))); + Assert.assertEquals("123", message.getField(f("default_cord"))); + + Assert.assertFalse(message.hasField(f("oneof_uint32"))); + Assert.assertFalse(message.hasField(f("oneof_nested_message"))); + Assert.assertFalse(message.hasField(f("oneof_string"))); + Assert.assertFalse(message.hasField(f("oneof_bytes"))); + + Assert.assertEquals(0, message.getField(f("oneof_uint32"))); + Assert.assertEquals("", message.getField(f("oneof_string"))); + Assert.assertEquals(toBytes(""), message.getField(f("oneof_bytes"))); + } + + // --------------------------------------------------------------- + + public void assertRepeatedFieldsModifiedViaReflection(MessageOrBuilder 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.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sfixed32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sfixed64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_float"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_double"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bool"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bytes"))); + + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeatedgroup"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_message"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_message"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_message"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_lazy_message"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_enum"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_enum"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_enum"))); + + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string_piece"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_cord"))); + + Assert.assertEquals(201, message.getRepeatedField(f("repeated_int32"), 0)); + Assert.assertEquals(202L, message.getRepeatedField(f("repeated_int64"), 0)); + Assert.assertEquals(203, message.getRepeatedField(f("repeated_uint32"), 0)); + Assert.assertEquals(204L, message.getRepeatedField(f("repeated_uint64"), 0)); + Assert.assertEquals(205, message.getRepeatedField(f("repeated_sint32"), 0)); + Assert.assertEquals(206L, message.getRepeatedField(f("repeated_sint64"), 0)); + Assert.assertEquals(207, message.getRepeatedField(f("repeated_fixed32"), 0)); + Assert.assertEquals(208L, message.getRepeatedField(f("repeated_fixed64"), 0)); + Assert.assertEquals(209, message.getRepeatedField(f("repeated_sfixed32"), 0)); + Assert.assertEquals(210L, message.getRepeatedField(f("repeated_sfixed64"), 0)); + Assert.assertEquals(211F, message.getRepeatedField(f("repeated_float"), 0)); + Assert.assertEquals(212D, message.getRepeatedField(f("repeated_double"), 0)); + Assert.assertEquals(true, message.getRepeatedField(f("repeated_bool"), 0)); + Assert.assertEquals("215", message.getRepeatedField(f("repeated_string"), 0)); + Assert.assertEquals(toBytes("216"), message.getRepeatedField(f("repeated_bytes"), 0)); + + Assert.assertEquals( + 217, + ((Message) message.getRepeatedField(f("repeatedgroup"), 0)).getField(repeatedGroupA)); + Assert.assertEquals( + 218, + ((Message) message.getRepeatedField(f("repeated_nested_message"), 0)).getField(nestedB)); + Assert.assertEquals( + 219, + ((Message) message.getRepeatedField(f("repeated_foreign_message"), 0)) + .getField(foreignC)); + Assert.assertEquals( + 220, + ((Message) message.getRepeatedField(f("repeated_import_message"), 0)).getField(importD)); + Assert.assertEquals( + 227, + ((Message) message.getRepeatedField(f("repeated_lazy_message"), 0)).getField(nestedB)); + + Assert.assertEquals(nestedBar, message.getRepeatedField(f("repeated_nested_enum"), 0)); + Assert.assertEquals(foreignBar, message.getRepeatedField(f("repeated_foreign_enum"), 0)); + Assert.assertEquals(importBar, message.getRepeatedField(f("repeated_import_enum"), 0)); + + Assert.assertEquals("224", message.getRepeatedField(f("repeated_string_piece"), 0)); + Assert.assertEquals("225", message.getRepeatedField(f("repeated_cord"), 0)); + + Assert.assertEquals(501, message.getRepeatedField(f("repeated_int32"), 1)); + Assert.assertEquals(502L, message.getRepeatedField(f("repeated_int64"), 1)); + Assert.assertEquals(503, message.getRepeatedField(f("repeated_uint32"), 1)); + Assert.assertEquals(504L, message.getRepeatedField(f("repeated_uint64"), 1)); + Assert.assertEquals(505, message.getRepeatedField(f("repeated_sint32"), 1)); + Assert.assertEquals(506L, message.getRepeatedField(f("repeated_sint64"), 1)); + Assert.assertEquals(507, message.getRepeatedField(f("repeated_fixed32"), 1)); + Assert.assertEquals(508L, message.getRepeatedField(f("repeated_fixed64"), 1)); + Assert.assertEquals(509, message.getRepeatedField(f("repeated_sfixed32"), 1)); + Assert.assertEquals(510L, message.getRepeatedField(f("repeated_sfixed64"), 1)); + Assert.assertEquals(511F, message.getRepeatedField(f("repeated_float"), 1)); + Assert.assertEquals(512D, message.getRepeatedField(f("repeated_double"), 1)); + Assert.assertEquals(true, message.getRepeatedField(f("repeated_bool"), 1)); + Assert.assertEquals("515", message.getRepeatedField(f("repeated_string"), 1)); + Assert.assertEquals(toBytes("516"), message.getRepeatedField(f("repeated_bytes"), 1)); + + Assert.assertEquals( + 517, + ((Message) message.getRepeatedField(f("repeatedgroup"), 1)).getField(repeatedGroupA)); + Assert.assertEquals( + 518, + ((Message) message.getRepeatedField(f("repeated_nested_message"), 1)).getField(nestedB)); + Assert.assertEquals( + 519, + ((Message) message.getRepeatedField(f("repeated_foreign_message"), 1)) + .getField(foreignC)); + Assert.assertEquals( + 520, + ((Message) message.getRepeatedField(f("repeated_import_message"), 1)).getField(importD)); + Assert.assertEquals( + 527, + ((Message) message.getRepeatedField(f("repeated_lazy_message"), 1)).getField(nestedB)); + + Assert.assertEquals(nestedFoo, message.getRepeatedField(f("repeated_nested_enum"), 1)); + Assert.assertEquals(foreignFoo, message.getRepeatedField(f("repeated_foreign_enum"), 1)); + Assert.assertEquals(importFoo, message.getRepeatedField(f("repeated_import_enum"), 1)); + + Assert.assertEquals("524", message.getRepeatedField(f("repeated_string_piece"), 1)); + Assert.assertEquals("525", message.getRepeatedField(f("repeated_cord"), 1)); + } + + public void setPackedFieldsViaReflection(Message.Builder message) { + message.addRepeatedField(f("packed_int32"), 601); + message.addRepeatedField(f("packed_int64"), 602L); + message.addRepeatedField(f("packed_uint32"), 603); + message.addRepeatedField(f("packed_uint64"), 604L); + message.addRepeatedField(f("packed_sint32"), 605); + message.addRepeatedField(f("packed_sint64"), 606L); + message.addRepeatedField(f("packed_fixed32"), 607); + message.addRepeatedField(f("packed_fixed64"), 608L); + message.addRepeatedField(f("packed_sfixed32"), 609); + message.addRepeatedField(f("packed_sfixed64"), 610L); + message.addRepeatedField(f("packed_float"), 611F); + message.addRepeatedField(f("packed_double"), 612D); + message.addRepeatedField(f("packed_bool"), true); + message.addRepeatedField(f("packed_enum"), foreignBar); + // Add a second one of each field. + message.addRepeatedField(f("packed_int32"), 701); + message.addRepeatedField(f("packed_int64"), 702L); + message.addRepeatedField(f("packed_uint32"), 703); + message.addRepeatedField(f("packed_uint64"), 704L); + message.addRepeatedField(f("packed_sint32"), 705); + message.addRepeatedField(f("packed_sint64"), 706L); + message.addRepeatedField(f("packed_fixed32"), 707); + message.addRepeatedField(f("packed_fixed64"), 708L); + message.addRepeatedField(f("packed_sfixed32"), 709); + message.addRepeatedField(f("packed_sfixed64"), 710L); + message.addRepeatedField(f("packed_float"), 711F); + message.addRepeatedField(f("packed_double"), 712D); + message.addRepeatedField(f("packed_bool"), false); + message.addRepeatedField(f("packed_enum"), foreignBaz); + } + + public void assertPackedFieldsSetViaReflection(MessageOrBuilder message) { + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_int32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_int64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_uint32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_uint64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sint32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sint64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_fixed32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_fixed64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sfixed32"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sfixed64"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_float"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_double"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_bool"))); + Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_enum"))); + Assert.assertEquals(601, message.getRepeatedField(f("packed_int32"), 0)); + Assert.assertEquals(602L, message.getRepeatedField(f("packed_int64"), 0)); + Assert.assertEquals(603, message.getRepeatedField(f("packed_uint32"), 0)); + Assert.assertEquals(604L, message.getRepeatedField(f("packed_uint64"), 0)); + Assert.assertEquals(605, message.getRepeatedField(f("packed_sint32"), 0)); + Assert.assertEquals(606L, message.getRepeatedField(f("packed_sint64"), 0)); + Assert.assertEquals(607, message.getRepeatedField(f("packed_fixed32"), 0)); + Assert.assertEquals(608L, message.getRepeatedField(f("packed_fixed64"), 0)); + Assert.assertEquals(609, message.getRepeatedField(f("packed_sfixed32"), 0)); + Assert.assertEquals(610L, message.getRepeatedField(f("packed_sfixed64"), 0)); + Assert.assertEquals(611F, message.getRepeatedField(f("packed_float"), 0)); + Assert.assertEquals(612D, message.getRepeatedField(f("packed_double"), 0)); + Assert.assertEquals(true, message.getRepeatedField(f("packed_bool"), 0)); + Assert.assertEquals(foreignBar, message.getRepeatedField(f("packed_enum"), 0)); + Assert.assertEquals(701, message.getRepeatedField(f("packed_int32"), 1)); + Assert.assertEquals(702L, message.getRepeatedField(f("packed_int64"), 1)); + Assert.assertEquals(703, message.getRepeatedField(f("packed_uint32"), 1)); + Assert.assertEquals(704L, message.getRepeatedField(f("packed_uint64"), 1)); + Assert.assertEquals(705, message.getRepeatedField(f("packed_sint32"), 1)); + Assert.assertEquals(706L, message.getRepeatedField(f("packed_sint64"), 1)); + Assert.assertEquals(707, message.getRepeatedField(f("packed_fixed32"), 1)); + Assert.assertEquals(708L, message.getRepeatedField(f("packed_fixed64"), 1)); + Assert.assertEquals(709, message.getRepeatedField(f("packed_sfixed32"), 1)); + Assert.assertEquals(710L, message.getRepeatedField(f("packed_sfixed64"), 1)); + Assert.assertEquals(711F, message.getRepeatedField(f("packed_float"), 1)); + Assert.assertEquals(712D, message.getRepeatedField(f("packed_double"), 1)); + Assert.assertEquals(false, message.getRepeatedField(f("packed_bool"), 1)); + Assert.assertEquals(foreignBaz, message.getRepeatedField(f("packed_enum"), 1)); + } + + /** + * Verifies that the reflection setters for the given.Builder object throw a + * NullPointerException if they are passed a null value. Uses Assert to throw an appropriate + * assertion failure, if the condition is not verified. + */ + public void assertReflectionSettersRejectNull(Message.Builder builder) throws Exception { + try { + builder.setField(f("optional_string"), null); + Assert.fail("Exception was not thrown"); + } catch (NullPointerException e) { + // We expect this exception. + } + try { + builder.setField(f("optional_bytes"), null); + Assert.fail("Exception was not thrown"); + } catch (NullPointerException e) { + // We expect this exception. + } + try { + builder.setField(f("optional_nested_enum"), null); + Assert.fail("Exception was not thrown"); + } catch (NullPointerException e) { + // We expect this exception. + } + try { + builder.setField(f("optional_nested_message"), (TestAllTypes.NestedMessage) null); + Assert.fail("Exception was not thrown"); + } catch (NullPointerException e) { + // We expect this exception. + } + try { + builder.setField(f("optional_nested_message"), (TestAllTypes.NestedMessage.Builder) null); + Assert.fail("Exception was not thrown"); + } catch (NullPointerException e) { + // We expect this exception. + } + + try { + builder.addRepeatedField(f("repeated_string"), null); + Assert.fail("Exception was not thrown"); + } catch (NullPointerException e) { + // We expect this exception. + } + try { + builder.addRepeatedField(f("repeated_bytes"), null); + Assert.fail("Exception was not thrown"); + } catch (NullPointerException e) { + // We expect this exception. + } + try { + builder.addRepeatedField(f("repeated_nested_enum"), null); + Assert.fail("Exception was not thrown"); + } catch (NullPointerException e) { + // We expect this exception. + } + try { + builder.addRepeatedField(f("repeated_nested_message"), null); + Assert.fail("Exception was not thrown"); + } catch (NullPointerException e) { + // We expect this exception. + } + } + + /** + * Verifies that the reflection repeated setters for the given Builder object throw a + * NullPointerException if they are passed a null value. Uses Assert to throw an appropriate + * assertion failure, if the condition is not verified. + */ + public void assertReflectionRepeatedSettersRejectNull(Message.Builder builder) + throws Exception { + builder.addRepeatedField(f("repeated_string"), "one"); + try { + builder.setRepeatedField(f("repeated_string"), 0, null); + Assert.fail("Exception was not thrown"); + } catch (NullPointerException e) { + // We expect this exception. + } + + builder.addRepeatedField(f("repeated_bytes"), toBytes("one")); + try { + builder.setRepeatedField(f("repeated_bytes"), 0, null); + Assert.fail("Exception was not thrown"); + } catch (NullPointerException e) { + // We expect this exception. + } + + builder.addRepeatedField(f("repeated_nested_enum"), nestedBaz); + try { + builder.setRepeatedField(f("repeated_nested_enum"), 0, null); + Assert.fail("Exception was not thrown"); + } catch (NullPointerException e) { + // We expect this exception. + } + + builder.addRepeatedField( + f("repeated_nested_message"), TestAllTypes.NestedMessage.newBuilder().setBb(218).build()); + try { + builder.setRepeatedField(f("repeated_nested_message"), 0, null); + Assert.fail("Exception was not thrown"); + } catch (NullPointerException e) { + // We expect this exception. + } + } + } + + /** @param filePath The path relative to {@link #getTestDataDir}. */ + public static String readTextFromFile(String filePath) { + return readBytesFromFile(filePath) + .toStringUtf8() + .replace(System.getProperty("line.separator"), "\n"); + } + + private static File getTestDataDir() { + // Search each parent directory looking for "src/google/protobuf". + File ancestor = new File(System.getProperty("protobuf.dir", ".")); + String initialPath = ancestor.getAbsolutePath(); + try { + ancestor = ancestor.getCanonicalFile(); + } catch (IOException e) { + throw new RuntimeException("Couldn't get canonical name of working directory.", e); + } + + String srcRootCheck = "src/google/protobuf"; + + // If we're running w/ Bazel on Windows, we're not in a sandbox, so we + // we must change our source root check condition to find the true test data dir. + String testBinaryName = System.getenv("TEST_BINARY"); + if (testBinaryName != null && testBinaryName.endsWith(".exe")) { + srcRootCheck = srcRootCheck + "/descriptor.cc"; + } + + while (ancestor != null && ancestor.exists()) { + // Identify the true source root. + if (new File(ancestor, srcRootCheck).exists()) { + return new File(ancestor, "src/google/protobuf/testdata"); + } + ancestor = ancestor.getParentFile(); + } + + throw new RuntimeException( + "Could not find golden files. This test must be run from within the " + + "protobuf source package so that it can read test data files from the " + + "C++ source tree: " + + initialPath); + } + + /** @param filename The path relative to {@link #getTestDataDir}. */ + public static ByteString readBytesFromFile(String filename) { + File fullPath = new File(getTestDataDir(), filename); + try { + RandomAccessFile file = new RandomAccessFile(fullPath, "r"); + byte[] content = new byte[(int) file.length()]; + file.readFully(content); + return ByteString.copyFrom(content); + } catch (IOException e) { + // Throw a RuntimeException here so that we can call this function from + // static initializers. + throw new IllegalArgumentException("Couldn't read file: " + fullPath.getPath(), e); + } + } + // END FULL-RUNTIME + + private static ByteString readBytesFromResource(String name) { + try { + return ByteString.readFrom(TestUtil.class.getResourceAsStream(name)); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + /** + * Get the bytes of the "golden message". This is a serialized TestAllTypes with all fields set as + * they would be by {@link #setAllFields(TestAllTypes.Builder)}, but it is loaded from a file on + * disk rather than generated dynamically. The file is actually generated by C++ code, so testing + * against it verifies compatibility with C++. + */ + public static ByteString getGoldenMessage() { + if (goldenMessage == null) { + goldenMessage = + readBytesFromResource("/google/protobuf/testdata/golden_message_oneof_implemented"); + } + return goldenMessage; + } + + private static ByteString goldenMessage = null; + + /** + * Get the bytes of the "golden packed fields message". This is a serialized TestPackedTypes with + * all fields set as they would be by {@link #setPackedFields(TestPackedTypes.Builder)}, but it is + * loaded from a file on disk rather than generated dynamically. The file is actually generated by + * C++ code, so testing against it verifies compatibility with C++. + */ + public static ByteString getGoldenPackedFieldsMessage() { + if (goldenPackedFieldsMessage == null) { + goldenPackedFieldsMessage = + readBytesFromResource("/google/protobuf/testdata/golden_packed_fields_message"); + } + return goldenPackedFieldsMessage; + } + + private static ByteString goldenPackedFieldsMessage = null; + + // BEGIN FULL-RUNTIME + /** + * Mock implementation of {@link GeneratedMessage.BuilderParent} for testing. + * + * @author jonp@google.com (Jon Perlow) + */ + public static class MockBuilderParent implements GeneratedMessage.BuilderParent { + + private int invalidations; + + @Override + public void markDirty() { + invalidations++; + } + + public int getInvalidationCount() { + return invalidations; + } + } + // END FULL-RUNTIME + + /** Helper class to test logged messages */ + public static class TestLogHandler extends Handler { + /** We will keep a private list of all logged records */ + private final List list = new ArrayList<>(); + + /** Adds the most recently logged record to our list. */ + @Override + public synchronized void publish(LogRecord record) { + list.add(record); + } + + @Override + public void flush() {} + + @Override + public void close() {} + + /** Returns a snapshot of the logged records. */ + public synchronized List getStoredLogRecords() { + List result = new ArrayList<>(list); + return Collections.unmodifiableList(result); + } + } +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/WireFormatTest.java b/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/WireFormatTest.java new file mode 100644 index 0000000..e072eb8 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/test/java/com/google/protobuf/WireFormatTest.java @@ -0,0 +1,548 @@ +// 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. + +package com.google.protobuf; + +import static com.google.common.truth.Truth.assertThat; + +import protobuf_unittest.UnittestMset.RawMessageSet; +import protobuf_unittest.UnittestMset.TestMessageSetExtension1; +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; +import protobuf_unittest.UnittestProto.TestPackedExtensions; +import protobuf_unittest.UnittestProto.TestPackedTypes; +import proto2_wireformat_unittest.UnittestMsetWireFormat.TestMessageSet; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.List; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests related to parsing and serialization. */ +@RunWith(JUnit4.class) +public class WireFormatTest { + + private static final int TYPE_ID_1 = + TestMessageSetExtension1.getDescriptor().getExtensions().get(0).getNumber(); + private static final int TYPE_ID_2 = + TestMessageSetExtension2.getDescriptor().getExtensions().get(0).getNumber(); + private static final int UNKNOWN_TYPE_ID = 1550055; + + @Test + public void testSerialization() throws Exception { + TestAllTypes message = TestUtil.getAllSet(); + + ByteString rawBytes = message.toByteString(); + assertThat(rawBytes.size()).isEqualTo(message.getSerializedSize()); + + TestAllTypes message2 = TestAllTypes.parseFrom(rawBytes); + + TestUtil.assertAllFieldsSet(message2); + } + + @Test + public void testSerializationPacked() throws Exception { + TestPackedTypes message = TestUtil.getPackedSet(); + + ByteString rawBytes = message.toByteString(); + assertThat(message.getSerializedSize()).isEqualTo(rawBytes.size()); + + TestPackedTypes message2 = TestPackedTypes.parseFrom(rawBytes); + + TestUtil.assertPackedFieldsSet(message2); + } + + @Test + public void testSerializeExtensions() throws Exception { + // TestAllTypes and TestAllExtensions should have compatible wire formats, + // so if we serialize a TestAllExtensions then parse it as TestAllTypes + // it should work. + + TestAllExtensions message = TestUtil.getAllExtensionsSet(); + ByteString rawBytes = message.toByteString(); + assertThat(message.getSerializedSize()).isEqualTo(rawBytes.size()); + + TestAllTypes message2 = TestAllTypes.parseFrom(rawBytes); + + TestUtil.assertAllFieldsSet(message2); + } + + @Test + public void testSerializePackedExtensions() throws Exception { + // TestPackedTypes and TestPackedExtensions should have compatible wire + // formats; check that they serialize to the same string. + TestPackedExtensions message = TestUtil.getPackedExtensionsSet(); + ByteString rawBytes = message.toByteString(); + + TestPackedTypes message2 = TestUtil.getPackedSet(); + ByteString rawBytes2 = message2.toByteString(); + + assertThat(rawBytes).isEqualTo(rawBytes2); + } + + @Test + public void testSerializationPackedWithoutGetSerializedSize() throws Exception { + // Write directly to an OutputStream, without invoking getSerializedSize() + // This used to be a bug where the size of a packed field was incorrect, + // since getSerializedSize() was never invoked. + TestPackedTypes message = TestUtil.getPackedSet(); + + // Directly construct a CodedOutputStream around the actual OutputStream, + // in case writeTo(OutputStream output) invokes getSerializedSize(); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + CodedOutputStream codedOutput = CodedOutputStream.newInstance(outputStream); + + message.writeTo(codedOutput); + + codedOutput.flush(); + + TestPackedTypes message2 = TestPackedTypes.parseFrom(outputStream.toByteArray()); + + TestUtil.assertPackedFieldsSet(message2); + } + + @Test + public void testParseExtensions() throws Exception { + // TestAllTypes and TestAllExtensions should have compatible wire formats, + // so if we serialize a TestAllTypes then parse it as TestAllExtensions + // it should work. + + TestAllTypes message = TestUtil.getAllSet(); + ByteString rawBytes = message.toByteString(); + + ExtensionRegistryLite registry = TestUtil.getExtensionRegistry(); + + TestAllExtensions message2 = TestAllExtensions.parseFrom(rawBytes, registry); + + TestUtil.assertAllExtensionsSet(message2); + } + + @Test + public void testParsePackedExtensions() throws Exception { + // Ensure that packed extensions can be properly parsed. + TestPackedExtensions message = TestUtil.getPackedExtensionsSet(); + ByteString rawBytes = message.toByteString(); + + ExtensionRegistryLite registry = TestUtil.getExtensionRegistry(); + + TestPackedExtensions message2 = TestPackedExtensions.parseFrom(rawBytes, registry); + + TestUtil.assertPackedExtensionsSet(message2); + } + + @Test + public void testSerializeDelimited() throws Exception { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + TestUtil.getAllSet().writeDelimitedTo(output); + output.write(12); + TestUtil.getPackedSet().writeDelimitedTo(output); + output.write(34); + + ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray()); + + TestUtil.assertAllFieldsSet(TestAllTypes.parseDelimitedFrom(input)); + assertThat(input.read()).isEqualTo(12); + TestUtil.assertPackedFieldsSet(TestPackedTypes.parseDelimitedFrom(input)); + assertThat(input.read()).isEqualTo(34); + assertThat(input.read()).isEqualTo(-1); + + // We're at EOF, so parsing again should return null. + assertThat(TestAllTypes.parseDelimitedFrom(input)).isNull(); + } + + private void assertFieldsInOrder(ByteString data) throws Exception { + CodedInputStream input = data.newCodedInput(); + int previousTag = 0; + + while (true) { + int tag = input.readTag(); + if (tag == 0) { + break; + } + + assertThat(tag).isGreaterThan(previousTag); + previousTag = tag; + input.skipField(tag); + } + } + + @Test + public void testInterleavedFieldsAndExtensions() throws Exception { + // Tests that fields are written in order even when extension ranges + // are interleaved with field numbers. + ByteString data = + TestFieldOrderings.newBuilder() + .setMyInt(1) + .setMyString("foo") + .setMyFloat(1.0F) + .setExtension(UnittestProto.myExtensionInt, 23) + .setExtension(UnittestProto.myExtensionString, "bar") + .build() + .toByteString(); + assertFieldsInOrder(data); + + Descriptors.Descriptor descriptor = TestFieldOrderings.getDescriptor(); + ByteString dynamicData = + DynamicMessage.newBuilder(TestFieldOrderings.getDescriptor()) + .setField(descriptor.findFieldByName("my_int"), 1L) + .setField(descriptor.findFieldByName("my_string"), "foo") + .setField(descriptor.findFieldByName("my_float"), 1.0F) + .setField(UnittestProto.myExtensionInt.getDescriptor(), 23) + .setField(UnittestProto.myExtensionString.getDescriptor(), "bar") + .build() + .toByteString(); + assertFieldsInOrder(dynamicData); + } + + private ExtensionRegistry getTestFieldOrderingsRegistry() { + ExtensionRegistry result = ExtensionRegistry.newInstance(); + result.add(UnittestProto.myExtensionInt); + result.add(UnittestProto.myExtensionString); + return result; + } + + @Test + public void testParseMultipleExtensionRanges() throws Exception { + // Make sure we can parse a message that contains multiple extensions + // ranges. + TestFieldOrderings source = + TestFieldOrderings.newBuilder() + .setMyInt(1) + .setMyString("foo") + .setMyFloat(1.0F) + .setExtension(UnittestProto.myExtensionInt, 23) + .setExtension(UnittestProto.myExtensionString, "bar") + .build(); + TestFieldOrderings dest = + TestFieldOrderings.parseFrom(source.toByteString(), getTestFieldOrderingsRegistry()); + assertThat(source).isEqualTo(dest); + } + + private static ExtensionRegistry getTestExtensionInsideTableRegistry() { + ExtensionRegistry result = ExtensionRegistry.newInstance(); + result.add(UnittestProto.testExtensionInsideTableExtension); + return result; + } + + @Test + 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()); + assertThat(source).isEqualTo(dest); + } + + @Test + public void testParseMultipleExtensionRangesDynamic() throws Exception { + // Same as above except with DynamicMessage. + Descriptors.Descriptor descriptor = TestFieldOrderings.getDescriptor(); + DynamicMessage source = + DynamicMessage.newBuilder(TestFieldOrderings.getDescriptor()) + .setField(descriptor.findFieldByName("my_int"), 1L) + .setField(descriptor.findFieldByName("my_string"), "foo") + .setField(descriptor.findFieldByName("my_float"), 1.0F) + .setField(UnittestProto.myExtensionInt.getDescriptor(), 23) + .setField(UnittestProto.myExtensionString.getDescriptor(), "bar") + .build(); + DynamicMessage dest = + DynamicMessage.parseFrom( + descriptor, source.toByteString(), getTestFieldOrderingsRegistry()); + assertThat(source).isEqualTo(dest); + } + + @Test + public void testSerializeMessageSetEagerly() throws Exception { + testSerializeMessageSetWithFlag(true); + } + + @Test + public void testSerializeMessageSetNotEagerly() throws Exception { + testSerializeMessageSetWithFlag(false); + } + + private void testSerializeMessageSetWithFlag(boolean eagerParsing) throws Exception { + ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing); + // Set up a TestMessageSet with two known messages and an unknown one. + TestMessageSet messageSet = + TestMessageSet.newBuilder() + .setExtension( + TestMessageSetExtension1.messageSetExtension, + TestMessageSetExtension1.newBuilder().setI(123).build()) + .setExtension( + TestMessageSetExtension2.messageSetExtension, + TestMessageSetExtension2.newBuilder().setStr("foo").build()) + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + UNKNOWN_TYPE_ID, + UnknownFieldSet.Field.newBuilder() + .addLengthDelimited(ByteString.copyFromUtf8("bar")) + .build()) + .build()) + .build(); + + ByteString data = messageSet.toByteString(); + + // Parse back using RawMessageSet and check the contents. + RawMessageSet raw = RawMessageSet.parseFrom(data); + + assertThat(raw.getUnknownFields().asMap()).isEmpty(); + + assertThat(raw.getItemCount()).isEqualTo(3); + assertThat(raw.getItem(0).getTypeId()).isEqualTo(TYPE_ID_1); + assertThat(raw.getItem(1).getTypeId()).isEqualTo(TYPE_ID_2); + assertThat(raw.getItem(2).getTypeId()).isEqualTo(UNKNOWN_TYPE_ID); + + TestMessageSetExtension1 message1 = + TestMessageSetExtension1.parseFrom(raw.getItem(0).getMessage()); + assertThat(message1.getI()).isEqualTo(123); + + TestMessageSetExtension2 message2 = + TestMessageSetExtension2.parseFrom(raw.getItem(1).getMessage()); + assertThat(message2.getStr()).isEqualTo("foo"); + + assertThat(raw.getItem(2).getMessage().toStringUtf8()).isEqualTo("bar"); + } + + @Test + public void testParseMessageSetEagerly() throws Exception { + testParseMessageSetWithFlag(true); + } + + @Test + public void testParseMessageSetNotEagerly() throws Exception { + testParseMessageSetWithFlag(false); + } + + private void testParseMessageSetWithFlag(boolean eagerParsing) throws Exception { + ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing); + ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance(); + extensionRegistry.add(TestMessageSetExtension1.messageSetExtension); + extensionRegistry.add(TestMessageSetExtension2.messageSetExtension); + + // Set up a RawMessageSet with two known messages and an unknown one. + RawMessageSet raw = + RawMessageSet.newBuilder() + .addItem( + RawMessageSet.Item.newBuilder() + .setTypeId(TYPE_ID_1) + .setMessage( + TestMessageSetExtension1.newBuilder().setI(123).build().toByteString()) + .build()) + .addItem( + RawMessageSet.Item.newBuilder() + .setTypeId(TYPE_ID_2) + .setMessage( + TestMessageSetExtension2.newBuilder().setStr("foo").build().toByteString()) + .build()) + .addItem( + RawMessageSet.Item.newBuilder() + .setTypeId(UNKNOWN_TYPE_ID) + .setMessage(ByteString.copyFromUtf8("bar")) + .build()) + .build(); + + ByteString data = raw.toByteString(); + + // Parse as a TestMessageSet and check the contents. + TestMessageSet messageSet = TestMessageSet.parseFrom(data, extensionRegistry); + + assertThat(messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI()) + .isEqualTo(123); + assertThat(messageSet.getExtension(TestMessageSetExtension2.messageSetExtension).getStr()) + .isEqualTo("foo"); + + // Check for unknown field with type LENGTH_DELIMITED, + // number UNKNOWN_TYPE_ID, and contents "bar". + UnknownFieldSet unknownFields = messageSet.getUnknownFields(); + assertThat(unknownFields.asMap()).hasSize(1); + assertThat(unknownFields.hasField(UNKNOWN_TYPE_ID)).isTrue(); + + UnknownFieldSet.Field field = unknownFields.getField(UNKNOWN_TYPE_ID); + assertThat(field.getLengthDelimitedList()).hasSize(1); + assertThat(field.getLengthDelimitedList().get(0).toStringUtf8()).isEqualTo("bar"); + } + + @Test + public void testParseMessageSetExtensionEagerly() throws Exception { + testParseMessageSetExtensionWithFlag(true); + } + + @Test + public void testParseMessageSetExtensionNotEagerly() throws Exception { + testParseMessageSetExtensionWithFlag(false); + } + + private void testParseMessageSetExtensionWithFlag(boolean eagerParsing) throws Exception { + ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing); + ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance(); + extensionRegistry.add(TestMessageSetExtension1.messageSetExtension); + + // Set up a RawMessageSet with a known messages. + RawMessageSet raw = + RawMessageSet.newBuilder() + .addItem( + RawMessageSet.Item.newBuilder() + .setTypeId(TYPE_ID_1) + .setMessage( + TestMessageSetExtension1.newBuilder().setI(123).build().toByteString()) + .build()) + .build(); + + ByteString data = raw.toByteString(); + + // Parse as a TestMessageSet and check the contents. + TestMessageSet messageSet = TestMessageSet.parseFrom(data, extensionRegistry); + assertThat(messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI()) + .isEqualTo(123); + } + + @Test + public void testMergeLazyMessageSetExtensionEagerly() throws Exception { + testMergeLazyMessageSetExtensionWithFlag(true); + } + + @Test + public void testMergeLazyMessageSetExtensionNotEagerly() throws Exception { + testMergeLazyMessageSetExtensionWithFlag(false); + } + + private void testMergeLazyMessageSetExtensionWithFlag(boolean eagerParsing) throws Exception { + ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing); + ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance(); + extensionRegistry.add(TestMessageSetExtension1.messageSetExtension); + + // Set up a RawMessageSet with a known messages. + RawMessageSet raw = + RawMessageSet.newBuilder() + .addItem( + RawMessageSet.Item.newBuilder() + .setTypeId(TYPE_ID_1) + .setMessage( + TestMessageSetExtension1.newBuilder().setI(123).build().toByteString()) + .build()) + .build(); + + ByteString data = raw.toByteString(); + + // Parse as a TestMessageSet and store value into lazy field + TestMessageSet messageSet = TestMessageSet.parseFrom(data, extensionRegistry); + // Merge lazy field check the contents. + messageSet = messageSet.toBuilder().mergeFrom(data, extensionRegistry).build(); + assertThat(messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI()) + .isEqualTo(123); + } + + @Test + public void testMergeMessageSetExtensionEagerly() throws Exception { + testMergeMessageSetExtensionWithFlag(true); + } + + @Test + public void testMergeMessageSetExtensionNotEagerly() throws Exception { + testMergeMessageSetExtensionWithFlag(false); + } + + private void testMergeMessageSetExtensionWithFlag(boolean eagerParsing) throws Exception { + ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing); + ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance(); + extensionRegistry.add(TestMessageSetExtension1.messageSetExtension); + + // Set up a RawMessageSet with a known messages. + RawMessageSet raw = + RawMessageSet.newBuilder() + .addItem( + RawMessageSet.Item.newBuilder() + .setTypeId(TYPE_ID_1) + .setMessage( + TestMessageSetExtension1.newBuilder().setI(123).build().toByteString()) + .build()) + .build(); + + // Serialize RawMessageSet unnormally (message value before type id) + ByteString.CodedBuilder out = ByteString.newCodedBuilder(raw.getSerializedSize()); + CodedOutputStream output = out.getCodedOutput(); + List items = raw.getItemList(); + for (int i = 0; i < items.size(); i++) { + RawMessageSet.Item item = items.get(i); + output.writeTag(1, WireFormat.WIRETYPE_START_GROUP); + output.writeBytes(3, item.getMessage()); + output.writeInt32(2, item.getTypeId()); + output.writeTag(1, WireFormat.WIRETYPE_END_GROUP); + } + ByteString data = out.build(); + + // Merge bytes into TestMessageSet and check the contents. + TestMessageSet messageSet = + TestMessageSet.newBuilder().mergeFrom(data, extensionRegistry).build(); + assertThat(messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI()) + .isEqualTo(123); + } + + // ================================================================ + // oneof + @Test + public void testOneofWireFormat() throws Exception { + TestOneof2.Builder builder = TestOneof2.newBuilder(); + TestUtil.setOneof(builder); + TestOneof2 message = builder.build(); + ByteString rawBytes = message.toByteString(); + + assertThat(message.getSerializedSize()).isEqualTo(rawBytes.size()); + + TestOneof2 message2 = TestOneof2.parseFrom(rawBytes); + TestUtil.assertOneofSet(message2); + } + + @Test + public void testOneofOnlyLastSet() throws Exception { + TestOneofBackwardsCompatible source = + TestOneofBackwardsCompatible.newBuilder().setFooInt(100).setFooString("101").build(); + + ByteString rawBytes = source.toByteString(); + TestOneof2 message = TestOneof2.parseFrom(rawBytes); + assertThat(message.hasFooInt()).isFalse(); + assertThat(message.hasFooString()).isTrue(); + } +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto b/tools/env-vars-generator/protobuf/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto new file mode 100644 index 0000000..4ec9688 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto @@ -0,0 +1,130 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto2"; + + +option java_outer_classname = "MapForProto2TestProto"; + +message TestMap { + message MessageValue { + optional int32 value = 1; + } + enum EnumValue { + FOO = 0; + BAR = 1; + BAZ = 2; + QUX = 3; + } + + map int32_to_int32_field = 1; + map int32_to_string_field = 2; + map int32_to_bytes_field = 3; + map int32_to_enum_field = 4; + map int32_to_message_field = 5; + map string_to_int32_field = 6; + + message MessageWithRequiredFields { + required int32 value = 1; + } + map required_message_map = 11; +} + +message TestUnknownEnumValue { + // Wire-compatible with TestMap.int32_to_enum_field so we can test the + // parsing behavior of TestMap regarding unknown enum values. + map int32_to_int32_field = 4; +} + +// Test that the maps initialization code works correctly when the map field +// references the containing message. +message TestRecursiveMap { + optional int32 value = 1; + map recursive_map_field = 2; +} + +// a decoy of TestMap for testing parsing errors +message BizarroTestMap { + // same key type, different value + map int32_to_int32_field = 1; + // different key and value types + map int32_to_string_field = 2; + // different key types, same value + map int32_to_bytes_field = 3; + // different key and value types + map int32_to_enum_field = 4; + // different key and value types + map int32_to_message_field = 5; + // same key type, different value + map string_to_int32_field = 6; +} + +// Used to test that java reserved words can be used as protobuf field names +// Not all reserved words are tested (to avoid bloat) but instead an arbitrary +// subset of them chosen to cover various keyword categories like +// type, modifier, declaration, etc. +message ReservedAsMapField { + map if = 1; + map const = 2; + map private = 3; + map class = 4; + map int = 5; + map void = 6; + // These are also proto keywords + map string = 7; + map package = 8; + // Most recent Java reserved word + map enum = 9; + // null is not a 'reserved word' per se but as a literal needs similar care + map null = 10; +} + +message ReservedAsMapFieldWithEnumValue { + enum SampleEnum { + A = 0; + B = 1; + } + map if = 1; + map const = 2; + map private = 3; + map class = 4; + map int = 5; + map void = 6; + // These are also proto keywords + map string = 7; + map package = 8; + // Most recent Java reserved word + map enum = 9; + // null is not a 'reserved word' per se but as a literal needs similar care + map null = 10; +} +package map_for_proto2_lite_test; +option java_package = "map_lite_test"; +option optimize_for = LITE_RUNTIME; diff --git a/tools/env-vars-generator/protobuf/java/core/src/test/proto/com/google/protobuf/map_for_proto2_test.proto b/tools/env-vars-generator/protobuf/java/core/src/test/proto/com/google/protobuf/map_for_proto2_test.proto new file mode 100644 index 0000000..f73bd63 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/test/proto/com/google/protobuf/map_for_proto2_test.proto @@ -0,0 +1,129 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto2"; + +package map_for_proto2_test; + +option java_package = "map_test"; +option java_outer_classname = "MapForProto2TestProto"; + +message TestMap { + message MessageValue { + optional int32 value = 1; + } + enum EnumValue { + FOO = 0; + BAR = 1; + BAZ = 2; + QUX = 3; + } + + map int32_to_int32_field = 1; + map int32_to_string_field = 2; + map int32_to_bytes_field = 3; + map int32_to_enum_field = 4; + map int32_to_message_field = 5; + map string_to_int32_field = 6; + + message MessageWithRequiredFields { + required int32 value = 1; + } + map required_message_map = 11; +} + +message TestUnknownEnumValue { + // Wire-compatible with TestMap.int32_to_enum_field so we can test the + // parsing behavior of TestMap regarding unknown enum values. + map int32_to_int32_field = 4; +} + +// Test that the maps initialization code works correctly when the map field +// references the containing message. +message TestRecursiveMap { + optional int32 value = 1; + map recursive_map_field = 2; +} + +// a decoy of TestMap for testing parsing errors +message BizarroTestMap { + // same key type, different value + map int32_to_int32_field = 1; + // different key and value types + map int32_to_string_field = 2; + // different key types, same value + map int32_to_bytes_field = 3; + // different key and value types + map int32_to_enum_field = 4; + // different key and value types + map int32_to_message_field = 5; + // same key type, different value + map string_to_int32_field = 6; +} + +// Used to test that java reserved words can be used as protobuf field names +// Not all reserved words are tested (to avoid bloat) but instead an arbitrary +// subset of them chosen to cover various keyword categories like +// type, modifier, declaration, etc. +message ReservedAsMapField { + map if = 1; + map const = 2; + map private = 3; + map class = 4; + map int = 5; + map void = 6; + // These are also proto keywords + map string = 7; + map package = 8; + // Most recent Java reserved word + map enum = 9; + // null is not a 'reserved word' per se but as a literal needs similar care + map null = 10; +} + +message ReservedAsMapFieldWithEnumValue { + enum SampleEnum { + A = 0; + B = 1; + } + map if = 1; + map const = 2; + map private = 3; + map class = 4; + map int = 5; + map void = 6; + // These are also proto keywords + map string = 7; + map package = 8; + // Most recent Java reserved word + map enum = 9; + // null is not a 'reserved word' per se but as a literal needs similar care + map null = 10; +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/test/proto/com/google/protobuf/nested_extension.proto b/tools/env-vars-generator/protobuf/java/core/src/test/proto/com/google/protobuf/nested_extension.proto new file mode 100644 index 0000000..2da6d08 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/test/proto/com/google/protobuf/nested_extension.proto @@ -0,0 +1,48 @@ +// 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: Darick Tong (darick@google.com) +// +// A proto file with nested extensions. Note that this must be defined in +// a separate file to properly test the initialization of the outer class. + +syntax = "proto2"; + +package protobuf_unittest; + +import "com/google/protobuf/non_nested_extension.proto"; + + +message MyNestedExtension { + extend MessageToBeExtended { + optional MessageToBeExtended recursiveExtension = 2; + optional int32 default = 2002; + } +} diff --git a/tools/env-vars-generator/protobuf/java/core/src/test/proto/com/google/protobuf/test_check_utf8_size.proto b/tools/env-vars-generator/protobuf/java/core/src/test/proto/com/google/protobuf/test_check_utf8_size.proto new file mode 100644 index 0000000..f06d76d --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/core/src/test/proto/com/google/protobuf/test_check_utf8_size.proto @@ -0,0 +1,52 @@ +// 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: Jacob Butcher (jbaum@google.com) +// +// Test file option java_string_check_utf8. +syntax = "proto2"; + +package proto2_test_check_utf8_size; + +option java_outer_classname = "TestCheckUtf8Size"; +option java_string_check_utf8 = true; +option optimize_for = CODE_SIZE; + +message StringWrapperSize { + required string req = 1; + optional string opt = 2; + repeated string rep = 3; +} + +message BytesWrapperSize { + required bytes req = 1; + optional bytes opt = 2; + repeated bytes rep = 3; +} diff --git a/tools/env-vars-generator/protobuf/java/internal/BUILD b/tools/env-vars-generator/protobuf/java/internal/BUILD new file mode 100644 index 0000000..4f542ec --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/internal/BUILD @@ -0,0 +1 @@ +package(default_visibility = ["//java:__subpackages__"]) \ No newline at end of file diff --git a/tools/env-vars-generator/protobuf/java/kotlin-lite/lite.awk b/tools/env-vars-generator/protobuf/java/kotlin-lite/lite.awk new file mode 100644 index 0000000..b22d965 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/kotlin-lite/lite.awk @@ -0,0 +1,25 @@ +# Remove code enclosed by "BEGIN FULL-RUNTIME" and "END FULL-RUNTIME" to +# create the lite-only version of a test file. + +BEGIN { + in_full_runtime = 0; +} + +/BEGIN FULL-RUNTIME/ { + in_full_runtime = 1; + next; +} + +/END FULL-RUNTIME/ { + in_full_runtime = 0; + next; +} + +in_full_runtime { + # Skip full runtime code path. + next; +} + +{ + print; +} diff --git a/tools/env-vars-generator/protobuf/java/kotlin-lite/src/main/kotlin/com/google/protobuf/ExtendableMessageLiteExtensions.kt b/tools/env-vars-generator/protobuf/java/kotlin-lite/src/main/kotlin/com/google/protobuf/ExtendableMessageLiteExtensions.kt new file mode 100644 index 0000000..6c208b2 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/kotlin-lite/src/main/kotlin/com/google/protobuf/ExtendableMessageLiteExtensions.kt @@ -0,0 +1,58 @@ +// 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. + +package com.google.protobuf.kotlin + +import com.google.protobuf.ExtensionLite +import com.google.protobuf.GeneratedMessageLite + +/** Gets the value of the proto extension. */ +operator fun < + M : GeneratedMessageLite.ExtendableMessage, + MOrBT : GeneratedMessageLite.ExtendableMessageOrBuilder, + T : Any + > MOrBT.get(extension: ExtensionLite): T = getExtension(extension) + +/** Sets the current value of the proto extension in this builder. */ +operator fun < + M : GeneratedMessageLite.ExtendableMessage, + B : GeneratedMessageLite.ExtendableBuilder, + T : Any + > B.set(extension: ExtensionLite, value: T) { + setExtension(extension, value) +} + +/** Returns true if the specified extension is set. */ +operator fun < + M : GeneratedMessageLite.ExtendableMessage, + MorBT : GeneratedMessageLite.ExtendableMessageOrBuilder + > MorBT.contains( + extension: ExtensionLite +): Boolean = hasExtension(extension) diff --git a/tools/env-vars-generator/protobuf/java/kotlin-lite/src/test/kotlin/com/google/protobuf/ExtendableMessageLiteExtensionsTest.kt b/tools/env-vars-generator/protobuf/java/kotlin-lite/src/test/kotlin/com/google/protobuf/ExtendableMessageLiteExtensionsTest.kt new file mode 100644 index 0000000..53291b4 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/kotlin-lite/src/test/kotlin/com/google/protobuf/ExtendableMessageLiteExtensionsTest.kt @@ -0,0 +1,90 @@ +// 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. + +package com.google.protobuf.kotlin + +import com.google.common.truth.Truth.assertThat +import com.google.protobuf.kotlin.test.ExampleExtensibleMessage +import com.google.protobuf.kotlin.test.ExampleExtensibleMessageOuterClass as TestProto +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +@RunWith(JUnit4::class) +class ExtendableMessageLiteExtensionsTest { + @Test + fun setOnBuilder() { + val builder = ExampleExtensibleMessage.newBuilder() + builder[TestProto.int32Extension] = 5 + assertThat(builder.build().getExtension(TestProto.int32Extension)).isEqualTo(5) + } + + @Test + fun getOnBuilder() { + val builder = ExampleExtensibleMessage.newBuilder() + .setExtension(TestProto.int32Extension, 6) + assertThat(builder[TestProto.int32Extension]).isEqualTo(6) + } + + @Test + fun getOnMessage() { + val message = ExampleExtensibleMessage.newBuilder() + .setExtension(TestProto.int32Extension, 6) + .build() + assertThat(message[TestProto.int32Extension]).isEqualTo(6) + } + + @Test + fun containsPositiveOnMessage() { + val message = ExampleExtensibleMessage.newBuilder() + .setExtension(TestProto.int32Extension, 6) + .build() + assertThat(TestProto.int32Extension in message).isTrue() + } + + @Test + fun containsPositiveOnBuilder() { + val builder = ExampleExtensibleMessage.newBuilder() + .setExtension(TestProto.int32Extension, 6) + assertThat(TestProto.int32Extension in builder).isTrue() + } + + @Test + fun containsNegativeOnMessage() { + val message = ExampleExtensibleMessage.newBuilder().build() + assertThat(TestProto.int32Extension in message).isFalse() + } + + @Test + fun containsNegativeOnBuilder() { + val builder = ExampleExtensibleMessage.newBuilder() + assertThat(TestProto.int32Extension in builder).isFalse() + } +} diff --git a/tools/env-vars-generator/protobuf/java/kotlin/BUILD b/tools/env-vars-generator/protobuf/java/kotlin/BUILD new file mode 100644 index 0000000..5403e6f --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/kotlin/BUILD @@ -0,0 +1,284 @@ +load("@io_bazel_rules_kotlin//kotlin:jvm.bzl", "kt_jvm_library") +load("@rules_java//java:defs.bzl", "java_proto_library") +load("@rules_proto//proto:defs.bzl", "proto_library") +load("//:protobuf_version.bzl", "PROTOBUF_VERSION") + +# Kotlin generated protos depend on this and only this. +kt_jvm_library( + name = "shared_runtime", + srcs = [ + "src/main/kotlin/com/google/protobuf/DslList.kt", + "src/main/kotlin/com/google/protobuf/DslMap.kt", + "src/main/kotlin/com/google/protobuf/DslProxy.kt", + "src/main/kotlin/com/google/protobuf/ExtensionList.kt", + "src/main/kotlin/com/google/protobuf/ProtoDslMarker.kt", + "src/main/kotlin/com/google/protobuf/UnmodifiableCollections.kt", + ], + visibility = ["//visibility:public"], + deps = [ + ":only_for_use_in_proto_generated_code_its_generator_and_tests", + "//java/lite", + ], +) + +kt_jvm_library( + name = "only_for_use_in_proto_generated_code_its_generator_and_tests", + srcs = ["src/main/kotlin/com/google/protobuf/OnlyForUseByGeneratedProtoCode.kt"], + visibility = ["//java:__subpackages__"], +) + +kt_jvm_library( + name = "bytestring_lib", + srcs = ["src/main/kotlin/com/google/protobuf/ByteStrings.kt"], + deps = ["//java/lite"], +) + +kt_jvm_library( + name = "full_extensions", + srcs = ["src/main/kotlin/com/google/protobuf/ExtendableMessageExtensions.kt"], + deps = ["//java/core"], +) + +test_suite( + name = "tests", + tests = [ + "bytestring_test", + "shared_tests", + "test_extensions", + "proto2_test", + "proto3_test", + ], +) + +kt_jvm_library( + name = "bytestring_test_library", + srcs = ["src/test/kotlin/com/google/protobuf/ByteStringsTest.kt"], + deps = [ + ":bytestring_lib", + "//java/lite", + "@com_github_jetbrains_kotlin//:kotlin-test", + "@maven//:com_google_truth_truth", + "@maven//:junit_junit", + ], +) + +java_test( + name = "bytestring_test", + runtime_deps = [":bytestring_test_library"], + test_class = "com.google.protobuf.kotlin.ByteStringsTest", +) + +proto_library( + name = "example_extensible_message_proto", + srcs = ["src/test/proto/com/google/protobuf/example_extensible_message.proto"], + visibility = ["//java:__subpackages__"], +) + +java_proto_library( + name = "example_extensible_message_java_proto", + deps = [":example_extensible_message_proto"], +) + +kt_jvm_library( + name = "shared_tests_library", + srcs = [ + "src/test/kotlin/com/google/protobuf/DslListTest.kt", + "src/test/kotlin/com/google/protobuf/DslMapTest.kt", + "src/test/kotlin/com/google/protobuf/ExtensionListTest.kt", + ], + deps = [ + ":bytestring_lib", + ":example_extensible_message_java_proto", + ":only_for_use_in_proto_generated_code_its_generator_and_tests", + ":shared_runtime", + "@com_github_jetbrains_kotlin//:kotlin-test", + "@maven//:com_google_truth_truth", + "@maven//:com_google_guava_guava_testlib", + "@maven//:junit_junit", + ], +) + +java_test( + name = "shared_tests", + runtime_deps = [":shared_tests_library"], + test_class = "com.google.protobuf.kotlin.DslListTest", +) + +kt_jvm_library( + name = "test_extensions_library", + srcs = ["src/test/kotlin/com/google/protobuf/ExtendableMessageExtensionsTest.kt"], + deps = [ + ":example_extensible_message_java_proto", + ":full_extensions", + "//java/lite", + ":only_for_use_in_proto_generated_code_its_generator_and_tests", + ":shared_runtime", + "@com_github_jetbrains_kotlin//:kotlin-test", + "@maven//:com_google_truth_truth", + "@maven//:junit_junit", + ], +) + +java_test( + name = "test_extensions", + runtime_deps = [":test_extensions_library"], + test_class = "com.google.protobuf.kotlin.ExtendableMessageExtensionsTest", +) + +proto_library( + name = "evil_names_proto2", + srcs = ["src/test/proto/com/google/protobuf/evil_names_proto2.proto"], + visibility = ["//:__subpackages__"], +) + +proto_library( + name = "evil_names_proto3", + srcs = ["src/test/proto/com/google/protobuf/evil_names_proto3.proto"], + visibility = ["//:__subpackages__"], +) + +java_proto_library( + name = "evil_names_proto2_java_proto", + deps = [":evil_names_proto2"], +) + +java_proto_library( + name = "evil_names_proto3_java_proto", + deps = [":evil_names_proto3"], +) + +proto_library( + name = "multiple_files_proto3", + srcs = ["src/test/proto/com/google/protobuf/multiple_files_proto3.proto"], + visibility = ["//:__subpackages__"], +) + +java_proto_library( name = "multiple_files_proto3_java_proto", + deps = [":multiple_files_proto3"], +) + +genrule( + name = "gen_kotlin_proto3_java_multiple_files", + srcs = ["src/test/proto/com/google/protobuf/multiple_files_proto3.proto"], + outs = [ + "MultipleFilesMessageAKt.kt", + "MultipleFilesMessageBKt.kt", + "MultipleFilesProto3Kt.kt", + ], + cmd = "$(location //:protoc) " + + "--kotlin_out=shared,immutable:$(@D) " + + "$(location src/test/proto/com/google/protobuf/multiple_files_proto3.proto) && " + + "cp $(@D)/com/google/protobuf/kotlin/generator/MultipleFilesMessageAKt.kt " + + "$(location MultipleFilesMessageAKt.kt) && " + + "cp $(@D)/com/google/protobuf/kotlin/generator/MultipleFilesMessageBKt.kt " + + "$(location MultipleFilesMessageBKt.kt) && " + + "cp $(@D)/com/google/protobuf/kotlin/generator/MultipleFilesProto3Kt.kt " + + "$(location MultipleFilesProto3Kt.kt)", + tools = ["//:protoc"], +) + +genrule( + name = "gen_evil_names_proto2", + srcs = ["src/test/proto/com/google/protobuf/evil_names_proto2.proto"], + outs = [ + "EvilNamesProto2Kt.kt", + "HardKeywordsAllTypesProto2Kt.kt", + "InterfaceKt.kt", + ], + cmd = "$(location //:protoc) " + + "--kotlin_out=shared,immutable:$(@D) " + + "$(location src/test/proto/com/google/protobuf/evil_names_proto2.proto) && " + + "cp $(@D)/com/google/protobuf/kotlin/generator/EvilNamesProto2Kt.kt " + + "$(location EvilNamesProto2Kt.kt) && " + + "cp $(@D)/com/google/protobuf/kotlin/generator/HardKeywordsAllTypesProto2Kt.kt " + + "$(location HardKeywordsAllTypesProto2Kt.kt) && " + + "cp $(@D)/com/google/protobuf/kotlin/generator/InterfaceKt.kt " + + "$(location InterfaceKt.kt)", + tools = ["//:protoc"], +) + +genrule( + name = "gen_evil_names_proto3", + srcs = ["src/test/proto/com/google/protobuf/evil_names_proto3.proto"], + outs = [ + "ClassKt.kt", + "EvilNamesProto3Kt.kt", + "HardKeywordsAllTypesProto3Kt.kt", + ], + cmd = "$(location //:protoc) " + + "--kotlin_out=shared,immutable:$(@D) " + + "$(location src/test/proto/com/google/protobuf/evil_names_proto3.proto) && " + + "cp $(@D)/com/google/protobuf/kotlin/generator/ClassKt.kt " + + "$(location ClassKt.kt) && " + + "cp $(@D)/com/google/protobuf/kotlin/generator/EvilNamesProto3Kt.kt " + + "$(location EvilNamesProto3Kt.kt) && " + + "cp $(@D)/com/google/protobuf/kotlin/generator/HardKeywordsAllTypesProto3Kt.kt " + + "$(location HardKeywordsAllTypesProto3Kt.kt)", + tools = ["//:protoc"], +) + +kt_jvm_library( + name = "kotlin_unittest", + srcs = [ + ":gen_evil_names_proto2", + "//:gen_kotlin_unittest", + ], + deps = [ + ":evil_names_proto2_java_proto", + "//java/core:core", + ":only_for_use_in_proto_generated_code_its_generator_and_tests", + ":shared_runtime", + "//:java_test_protos", + ], +) + +kt_jvm_library( + name = "kotlin_proto3_unittest", + srcs = [ + ":gen_evil_names_proto3", + ":gen_kotlin_proto3_java_multiple_files", + "//:gen_kotlin_proto3_unittest", + ], + deps = [ + ":evil_names_proto3_java_proto", + ":multiple_files_proto3_java_proto", + "//java/core:core", + ":only_for_use_in_proto_generated_code_its_generator_and_tests", + ":shared_runtime", + "//:java_test_protos", + ], +) + +kt_jvm_library( + name = "proto2_test_library", + srcs = ["src/test/kotlin/com/google/protobuf/Proto2Test.kt"], + deps = [ + ":kotlin_unittest", + "//java/core:test_util", + "@maven//:com_google_truth_truth", + "@maven//:junit_junit", + ], +) + +java_test( + name = "proto2_test", + runtime_deps = [":proto2_test_library"], + test_class = "com.google.protobuf.kotlin.Proto2Test", +) + +kt_jvm_library( + name = "proto3_test_library", + srcs = ["src/test/kotlin/com/google/protobuf/Proto3Test.kt"], + deps = [ + ":kotlin_proto3_unittest", + "//java/core:test_util", + "@maven//:com_google_truth_truth", + "@maven//:junit_junit", + ], +) + +java_test( + name = "proto3_test", + runtime_deps = [":proto3_test_library"], + test_class = "com.google.protobuf.kotlin.Proto3Test", +) diff --git a/tools/env-vars-generator/protobuf/java/kotlin/generate-test-sources-build.xml b/tools/env-vars-generator/protobuf/java/kotlin/generate-test-sources-build.xml new file mode 100644 index 0000000..dca1a05 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/kotlin/generate-test-sources-build.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tools/env-vars-generator/protobuf/java/kotlin/pom_template.xml b/tools/env-vars-generator/protobuf/java/kotlin/pom_template.xml new file mode 100644 index 0000000..c8ddcad --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/kotlin/pom_template.xml @@ -0,0 +1,23 @@ + + + 4.0.0 + + {groupId} + protobuf-parent + {version} + + + {artifactId} + {type} + + Protocol Buffers [Kotlin-Core] + + Kotlin core Protocol Buffers library. Protocol Buffers are a way of encoding structured data in an + efficient yet extensible format. + + + + 1.5.0 + + + diff --git a/tools/env-vars-generator/protobuf/java/kotlin/src/main/kotlin/com/google/protobuf/ExtensionList.kt b/tools/env-vars-generator/protobuf/java/kotlin/src/main/kotlin/com/google/protobuf/ExtensionList.kt new file mode 100644 index 0000000..206c19f --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/kotlin/src/main/kotlin/com/google/protobuf/ExtensionList.kt @@ -0,0 +1,57 @@ +// 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. + +package com.google.protobuf.kotlin + +import com.google.protobuf.ExtensionLite +import com.google.protobuf.MessageLite + +/** + * Implementation for ExtensionList and ExtensionListLite. Like [DslList], represents an + * unmodifiable view of a repeated proto field -- in this case, an extension field -- but supports + * querying the extension. + */ +class ExtensionList +@OnlyForUseByGeneratedProtoCode +constructor(val extension: ExtensionLite>, private val delegate: List) : + List by delegate { + override fun iterator(): Iterator = UnmodifiableIterator(delegate.iterator()) + + override fun listIterator(): ListIterator = UnmodifiableListIterator(delegate.listIterator()) + + override fun listIterator(index: Int): ListIterator = + UnmodifiableListIterator(delegate.listIterator(index)) + + override fun equals(other: Any?): Boolean = delegate == other + + override fun hashCode(): Int = delegate.hashCode() + + override fun toString(): String = delegate.toString() +} diff --git a/tools/env-vars-generator/protobuf/java/kotlin/src/test/kotlin/com/google/protobuf/ExtensionListTest.kt b/tools/env-vars-generator/protobuf/java/kotlin/src/test/kotlin/com/google/protobuf/ExtensionListTest.kt new file mode 100644 index 0000000..239f27a --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/kotlin/src/test/kotlin/com/google/protobuf/ExtensionListTest.kt @@ -0,0 +1,155 @@ +// 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. + +package com.google.protobuf.kotlin + +import com.google.common.testing.EqualsTester +import com.google.common.truth.Truth.assertThat +import com.google.protobuf.kotlin.test.ExampleExtensibleMessage +import com.google.protobuf.kotlin.test.ExampleExtensibleMessageOuterClass as TestProto +import kotlin.test.assertFailsWith +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +/** Tests for [DslList]. */ +@RunWith(JUnit4::class) +@OptIn(OnlyForUseByGeneratedProtoCode::class) +class ExtensionListTest { + class DummyProxy private constructor() : DslProxy() + + @Test + fun matchesList() { + assertThat( + ExtensionList( + TestProto.repeatedExtension, listOf(1, 2, 3) + ) + ).containsExactly(1, 2, 3).inOrder() + } + + @Test + fun reflectsChangesInList() { + val mutableList = mutableListOf(1, 2, 3) + val extensionList = ExtensionList( + TestProto.repeatedExtension, mutableList + ) + mutableList.add(4) + assertThat(extensionList).containsExactly(1, 2, 3, 4).inOrder() + } + + @Test + fun extensionListIsNotMutable() { + val extensionList = ExtensionList( + TestProto.repeatedExtension, mutableListOf(1, 2, 3) + ) + assertThat(extensionList is MutableList<*>).isFalse() + } + + @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "UNCHECKED_CAST") + @Test + fun extensionListIsNotEvenSecretlyMutable() { + val extensionList = ExtensionList( + TestProto.repeatedExtension, mutableListOf(1, 2, 3) + ) + val extensionListAsJavaUtil = extensionList as java.util.List + assertFailsWith { + extensionListAsJavaUtil.add(4) + } + } + + @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "UNCHECKED_CAST") + @Test + fun extensionList_IteratorIsNotEvenSecretlyMutable() { + val extensionList = ExtensionList( + TestProto.repeatedExtension, mutableListOf(1, 2, 3) + ) + val iterator = extensionList.iterator() as java.util.Iterator + iterator.next() + + assertFailsWith { + iterator.remove() + } + } + + @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "UNCHECKED_CAST") + @Test + fun extensionList_ListIteratorIsNotEvenSecretlyMutable() { + val extensionList = ExtensionList( + TestProto.repeatedExtension, mutableListOf(1, 2, 3) + ) + val iterator = extensionList.listIterator() as java.util.ListIterator + iterator.next() + + assertFailsWith { + iterator.remove() + } + } + + @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "UNCHECKED_CAST") + @Test + fun extensionList_ListIteratorIndexIsNotEvenSecretlyMutable() { + val extensionList = ExtensionList( + TestProto.repeatedExtension, mutableListOf(1, 2, 3) + ) + val iterator = extensionList.listIterator(1) as java.util.ListIterator + iterator.next() + + assertFailsWith { + iterator.remove() + } + } + + @Test + fun expectedToString() { + assertThat( + ExtensionList(TestProto.repeatedExtension, listOf(1, 2)) + .toString() + ).isEqualTo("[1, 2]") + } + + @Test + fun equality() { + EqualsTester() + .addEqualityGroup( + ExtensionList(TestProto.repeatedExtension, listOf(1, 2)), + ExtensionList(TestProto.differentExtension, listOf(1, 2)), + listOf(1, 2) + ) + .addEqualityGroup( + ExtensionList(TestProto.repeatedExtension, listOf(2, 2)), + listOf(2, 2) + ) + .addEqualityGroup( + ExtensionList(TestProto.repeatedExtension, emptyList()), + emptyList() + ) + .testEquals() + } +} diff --git a/tools/env-vars-generator/protobuf/java/kotlin/src/test/proto/com/google/protobuf/example_extensible_message.proto b/tools/env-vars-generator/protobuf/java/kotlin/src/test/proto/com/google/protobuf/example_extensible_message.proto new file mode 100644 index 0000000..b82c82b --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/kotlin/src/test/proto/com/google/protobuf/example_extensible_message.proto @@ -0,0 +1,46 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto2"; + +package protobuf.kotlin.test; + +option java_package = "com.google.protobuf.kotlin.test"; +option java_multiple_files = true; + +message ExampleExtensibleMessage { + extensions 10 to 20; +} + +extend ExampleExtensibleMessage { + repeated int32 repeated_extension = 10; + repeated int32 different_extension = 11; + optional int32 int32_extension = 12; +} diff --git a/tools/env-vars-generator/protobuf/java/lite/generate-sources-build.xml b/tools/env-vars-generator/protobuf/java/lite/generate-sources-build.xml new file mode 100644 index 0000000..74d96a2 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/lite/generate-sources-build.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/tools/env-vars-generator/protobuf/java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java b/tools/env-vars-generator/protobuf/java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java new file mode 100644 index 0000000..f00bbb1 --- /dev/null +++ b/tools/env-vars-generator/protobuf/java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java @@ -0,0 +1,1898 @@ +// 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. + +package com.google.protobuf.util; + +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; + +import com.google.common.collect.ImmutableSet; +import com.google.protobuf.Any; +import com.google.protobuf.BoolValue; +import com.google.protobuf.ByteString; +import com.google.protobuf.BytesValue; +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.DoubleValue; +import com.google.protobuf.FloatValue; +import com.google.protobuf.Int32Value; +import com.google.protobuf.Int64Value; +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.ListValue; +import com.google.protobuf.Message; +import com.google.protobuf.NullValue; +import com.google.protobuf.StringValue; +import com.google.protobuf.Struct; +import com.google.protobuf.UInt32Value; +import com.google.protobuf.UInt64Value; +import com.google.protobuf.Value; +import com.google.protobuf.util.JsonFormat.TypeRegistry; +import com.google.protobuf.util.proto.JsonTestProto.TestAllTypes; +import com.google.protobuf.util.proto.JsonTestProto.TestAllTypes.AliasedEnum; +import com.google.protobuf.util.proto.JsonTestProto.TestAllTypes.NestedEnum; +import com.google.protobuf.util.proto.JsonTestProto.TestAllTypes.NestedMessage; +import com.google.protobuf.util.proto.JsonTestProto.TestAny; +import com.google.protobuf.util.proto.JsonTestProto.TestCustomJsonName; +import com.google.protobuf.util.proto.JsonTestProto.TestDuration; +import com.google.protobuf.util.proto.JsonTestProto.TestFieldMask; +import com.google.protobuf.util.proto.JsonTestProto.TestMap; +import com.google.protobuf.util.proto.JsonTestProto.TestOneof; +import com.google.protobuf.util.proto.JsonTestProto.TestRecursive; +import com.google.protobuf.util.proto.JsonTestProto.TestStruct; +import com.google.protobuf.util.proto.JsonTestProto.TestTimestamp; +import com.google.protobuf.util.proto.JsonTestProto.TestWrappers; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Collections; +import java.util.HashSet; +import java.util.Locale; +import java.util.Set; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class JsonFormatTest { + public JsonFormatTest() { + // Test that locale does not affect JsonFormat. + Locale.setDefault(Locale.forLanguageTag("hi-IN")); + } + + private void setAllFields(TestAllTypes.Builder builder) { + builder.setOptionalInt32(1234); + builder.setOptionalInt64(1234567890123456789L); + builder.setOptionalUint32(5678); + builder.setOptionalUint64(2345678901234567890L); + builder.setOptionalSint32(9012); + builder.setOptionalSint64(3456789012345678901L); + builder.setOptionalFixed32(3456); + builder.setOptionalFixed64(4567890123456789012L); + builder.setOptionalSfixed32(7890); + builder.setOptionalSfixed64(5678901234567890123L); + builder.setOptionalFloat(1.5f); + builder.setOptionalDouble(1.25); + builder.setOptionalBool(true); + builder.setOptionalString("Hello world!"); + builder.setOptionalBytes(ByteString.copyFrom(new byte[] {0, 1, 2})); + builder.setOptionalNestedEnum(NestedEnum.BAR); + builder.getOptionalNestedMessageBuilder().setValue(100); + + builder.addRepeatedInt32(1234); + builder.addRepeatedInt64(1234567890123456789L); + builder.addRepeatedUint32(5678); + builder.addRepeatedUint64(2345678901234567890L); + builder.addRepeatedSint32(9012); + builder.addRepeatedSint64(3456789012345678901L); + builder.addRepeatedFixed32(3456); + builder.addRepeatedFixed64(4567890123456789012L); + builder.addRepeatedSfixed32(7890); + builder.addRepeatedSfixed64(5678901234567890123L); + builder.addRepeatedFloat(1.5f); + builder.addRepeatedDouble(1.25); + builder.addRepeatedBool(true); + builder.addRepeatedString("Hello world!"); + builder.addRepeatedBytes(ByteString.copyFrom(new byte[] {0, 1, 2})); + builder.addRepeatedNestedEnum(NestedEnum.BAR); + builder.addRepeatedNestedMessageBuilder().setValue(100); + + builder.addRepeatedInt32(234); + builder.addRepeatedInt64(234567890123456789L); + builder.addRepeatedUint32(678); + builder.addRepeatedUint64(345678901234567890L); + builder.addRepeatedSint32(012); + builder.addRepeatedSint64(456789012345678901L); + builder.addRepeatedFixed32(456); + builder.addRepeatedFixed64(567890123456789012L); + builder.addRepeatedSfixed32(890); + builder.addRepeatedSfixed64(678901234567890123L); + builder.addRepeatedFloat(11.5f); + builder.addRepeatedDouble(11.25); + builder.addRepeatedBool(true); + builder.addRepeatedString("ello world!"); + builder.addRepeatedBytes(ByteString.copyFrom(new byte[] {1, 2})); + builder.addRepeatedNestedEnum(NestedEnum.BAZ); + builder.addRepeatedNestedMessageBuilder().setValue(200); + } + + private void assertRoundTripEquals(Message message) throws Exception { + assertRoundTripEquals(message, TypeRegistry.getEmptyTypeRegistry()); + } + + private void assertRoundTripEquals(Message message, TypeRegistry registry) throws Exception { + JsonFormat.Printer printer = JsonFormat.printer().usingTypeRegistry(registry); + JsonFormat.Parser parser = JsonFormat.parser().usingTypeRegistry(registry); + Message.Builder builder = message.newBuilderForType(); + parser.merge(printer.print(message), builder); + Message parsedMessage = builder.build(); + assertThat(parsedMessage.toString()).isEqualTo(message.toString()); + } + + private void assertRoundTripEquals(Message message, com.google.protobuf.TypeRegistry registry) + throws Exception { + JsonFormat.Printer printer = JsonFormat.printer().usingTypeRegistry(registry); + JsonFormat.Parser parser = JsonFormat.parser().usingTypeRegistry(registry); + Message.Builder builder = message.newBuilderForType(); + parser.merge(printer.print(message), builder); + Message parsedMessage = builder.build(); + assertThat(parsedMessage.toString()).isEqualTo(message.toString()); + } + + private String toJsonString(Message message) throws IOException { + return JsonFormat.printer().print(message); + } + private String toCompactJsonString(Message message) throws IOException { + return JsonFormat.printer().omittingInsignificantWhitespace().print(message); + } + private String toSortedJsonString(Message message) throws IOException { + return JsonFormat.printer().sortingMapKeys().print(message); + } + + private void mergeFromJson(String json, Message.Builder builder) throws IOException { + JsonFormat.parser().merge(json, builder); + } + + private void mergeFromJsonIgnoringUnknownFields(String json, Message.Builder builder) + throws IOException { + JsonFormat.parser().ignoringUnknownFields().merge(json, builder); + } + + @Test + public void testAllFields() throws Exception { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + setAllFields(builder); + TestAllTypes message = builder.build(); + + assertThat(toJsonString(message)) + .isEqualTo( + "{\n" + + " \"optionalInt32\": 1234,\n" + + " \"optionalInt64\": \"1234567890123456789\",\n" + + " \"optionalUint32\": 5678,\n" + + " \"optionalUint64\": \"2345678901234567890\",\n" + + " \"optionalSint32\": 9012,\n" + + " \"optionalSint64\": \"3456789012345678901\",\n" + + " \"optionalFixed32\": 3456,\n" + + " \"optionalFixed64\": \"4567890123456789012\",\n" + + " \"optionalSfixed32\": 7890,\n" + + " \"optionalSfixed64\": \"5678901234567890123\",\n" + + " \"optionalFloat\": 1.5,\n" + + " \"optionalDouble\": 1.25,\n" + + " \"optionalBool\": true,\n" + + " \"optionalString\": \"Hello world!\",\n" + + " \"optionalBytes\": \"AAEC\",\n" + + " \"optionalNestedMessage\": {\n" + + " \"value\": 100\n" + + " },\n" + + " \"optionalNestedEnum\": \"BAR\",\n" + + " \"repeatedInt32\": [1234, 234],\n" + + " \"repeatedInt64\": [\"1234567890123456789\", \"234567890123456789\"],\n" + + " \"repeatedUint32\": [5678, 678],\n" + + " \"repeatedUint64\": [\"2345678901234567890\", \"345678901234567890\"],\n" + + " \"repeatedSint32\": [9012, 10],\n" + + " \"repeatedSint64\": [\"3456789012345678901\", \"456789012345678901\"],\n" + + " \"repeatedFixed32\": [3456, 456],\n" + + " \"repeatedFixed64\": [\"4567890123456789012\", \"567890123456789012\"],\n" + + " \"repeatedSfixed32\": [7890, 890],\n" + + " \"repeatedSfixed64\": [\"5678901234567890123\", \"678901234567890123\"],\n" + + " \"repeatedFloat\": [1.5, 11.5],\n" + + " \"repeatedDouble\": [1.25, 11.25],\n" + + " \"repeatedBool\": [true, true],\n" + + " \"repeatedString\": [\"Hello world!\", \"ello world!\"],\n" + + " \"repeatedBytes\": [\"AAEC\", \"AQI=\"],\n" + + " \"repeatedNestedMessage\": [{\n" + + " \"value\": 100\n" + + " }, {\n" + + " \"value\": 200\n" + + " }],\n" + + " \"repeatedNestedEnum\": [\"BAR\", \"BAZ\"]\n" + + "}"); + + assertRoundTripEquals(message); + } + + @Test + public void testUnknownEnumValues() throws Exception { + TestAllTypes message = + TestAllTypes.newBuilder() + .setOptionalNestedEnumValue(12345) + .addRepeatedNestedEnumValue(12345) + .addRepeatedNestedEnumValue(0) + .build(); + assertThat(toJsonString(message)) + .isEqualTo( + "{\n" + + " \"optionalNestedEnum\": 12345,\n" + + " \"repeatedNestedEnum\": [12345, \"FOO\"]\n" + + "}"); + assertRoundTripEquals(message); + + TestMap.Builder mapBuilder = TestMap.newBuilder(); + mapBuilder.putInt32ToEnumMapValue(1, 0); + mapBuilder.putInt32ToEnumMapValue(2, 12345); + TestMap mapMessage = mapBuilder.build(); + assertThat(toJsonString(mapMessage)) + .isEqualTo( + "{\n" + + " \"int32ToEnumMap\": {\n" + + " \"1\": \"FOO\",\n" + + " \"2\": 12345\n" + + " }\n" + + "}"); + assertRoundTripEquals(mapMessage); + } + + @Test + public void testSpecialFloatValues() throws Exception { + TestAllTypes message = + TestAllTypes.newBuilder() + .addRepeatedFloat(Float.NaN) + .addRepeatedFloat(Float.POSITIVE_INFINITY) + .addRepeatedFloat(Float.NEGATIVE_INFINITY) + .addRepeatedDouble(Double.NaN) + .addRepeatedDouble(Double.POSITIVE_INFINITY) + .addRepeatedDouble(Double.NEGATIVE_INFINITY) + .build(); + assertThat(toJsonString(message)) + .isEqualTo( + "{\n" + + " \"repeatedFloat\": [\"NaN\", \"Infinity\", \"-Infinity\"],\n" + + " \"repeatedDouble\": [\"NaN\", \"Infinity\", \"-Infinity\"]\n" + + "}"); + + assertRoundTripEquals(message); + } + + @Test + public void testParserAcceptStringForNumericField() throws Exception { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + mergeFromJson( + "{\n" + + " \"optionalInt32\": \"1234\",\n" + + " \"optionalUint32\": \"5678\",\n" + + " \"optionalSint32\": \"9012\",\n" + + " \"optionalFixed32\": \"3456\",\n" + + " \"optionalSfixed32\": \"7890\",\n" + + " \"optionalFloat\": \"1.5\",\n" + + " \"optionalDouble\": \"1.25\",\n" + + " \"optionalBool\": \"true\"\n" + + "}", + builder); + TestAllTypes message = builder.build(); + assertThat(message.getOptionalInt32()).isEqualTo(1234); + assertThat(message.getOptionalUint32()).isEqualTo(5678); + assertThat(message.getOptionalSint32()).isEqualTo(9012); + assertThat(message.getOptionalFixed32()).isEqualTo(3456); + assertThat(message.getOptionalSfixed32()).isEqualTo(7890); + assertThat(message.getOptionalFloat()).isEqualTo(1.5f); + assertThat(message.getOptionalDouble()).isEqualTo(1.25); + assertThat(message.getOptionalBool()).isTrue(); + } + + @Test + public void testParserAcceptFloatingPointValueForIntegerField() throws Exception { + // Test that numeric values like "1.000", "1e5" will also be accepted. + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + mergeFromJson( + "{\n" + + " \"repeatedInt32\": [1.000, 1e5, \"1.000\", \"1e5\"],\n" + + " \"repeatedUint32\": [1.000, 1e5, \"1.000\", \"1e5\"],\n" + + " \"repeatedInt64\": [1.000, 1e5, \"1.000\", \"1e5\"],\n" + + " \"repeatedUint64\": [1.000, 1e5, \"1.000\", \"1e5\"]\n" + + "}", + builder); + int[] expectedValues = new int[] {1, 100000, 1, 100000}; + assertThat(builder.getRepeatedInt32Count()).isEqualTo(4); + assertThat(builder.getRepeatedUint32Count()).isEqualTo(4); + assertThat(builder.getRepeatedInt64Count()).isEqualTo(4); + assertThat(builder.getRepeatedUint64Count()).isEqualTo(4); + for (int i = 0; i < 4; ++i) { + assertThat(builder.getRepeatedInt32(i)).isEqualTo(expectedValues[i]); + assertThat(builder.getRepeatedUint32(i)).isEqualTo(expectedValues[i]); + assertThat(builder.getRepeatedInt64(i)).isEqualTo(expectedValues[i]); + assertThat(builder.getRepeatedUint64(i)).isEqualTo(expectedValues[i]); + } + + // Non-integers will still be rejected. + assertRejects("optionalInt32", "1.5"); + assertRejects("optionalUint32", "1.5"); + assertRejects("optionalInt64", "1.5"); + assertRejects("optionalUint64", "1.5"); + } + + private void assertRejects(String name, String value) { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + try { + // Numeric form is rejected. + mergeFromJson("{\"" + name + "\":" + value + "}", builder); + assertWithMessage("Exception is expected.").fail(); + } catch (IOException e) { + // Expected. + } + try { + // String form is also rejected. + mergeFromJson("{\"" + name + "\":\"" + value + "\"}", builder); + assertWithMessage("Exception is expected.").fail(); + } catch (IOException e) { + // Expected. + } + } + + private void assertAccepts(String name, String value) throws IOException { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + // Both numeric form and string form are accepted. + mergeFromJson("{\"" + name + "\":" + value + "}", builder); + builder.clear(); + mergeFromJson("{\"" + name + "\":\"" + value + "\"}", builder); + } + + @Test + public void testParserRejectOutOfRangeNumericValues() throws Exception { + assertAccepts("optionalInt32", String.valueOf(Integer.MAX_VALUE)); + assertAccepts("optionalInt32", String.valueOf(Integer.MIN_VALUE)); + assertRejects("optionalInt32", String.valueOf(Integer.MAX_VALUE + 1L)); + assertRejects("optionalInt32", String.valueOf(Integer.MIN_VALUE - 1L)); + + assertAccepts("optionalUint32", String.valueOf(Integer.MAX_VALUE + 1L)); + assertRejects("optionalUint32", "123456789012345"); + assertRejects("optionalUint32", "-1"); + + BigInteger one = BigInteger.ONE; + BigInteger maxLong = new BigInteger(String.valueOf(Long.MAX_VALUE)); + BigInteger minLong = new BigInteger(String.valueOf(Long.MIN_VALUE)); + assertAccepts("optionalInt64", maxLong.toString()); + assertAccepts("optionalInt64", minLong.toString()); + assertRejects("optionalInt64", maxLong.add(one).toString()); + assertRejects("optionalInt64", minLong.subtract(one).toString()); + + assertAccepts("optionalUint64", maxLong.add(one).toString()); + assertRejects("optionalUint64", "1234567890123456789012345"); + assertRejects("optionalUint64", "-1"); + + assertAccepts("optionalBool", "true"); + assertRejects("optionalBool", "1"); + assertRejects("optionalBool", "0"); + + assertAccepts("optionalFloat", String.valueOf(Float.MAX_VALUE)); + assertAccepts("optionalFloat", String.valueOf(-Float.MAX_VALUE)); + assertRejects("optionalFloat", String.valueOf(Double.MAX_VALUE)); + assertRejects("optionalFloat", String.valueOf(-Double.MAX_VALUE)); + + BigDecimal moreThanOne = new BigDecimal("1.000001"); + BigDecimal maxDouble = new BigDecimal(Double.MAX_VALUE); + BigDecimal minDouble = new BigDecimal(-Double.MAX_VALUE); + assertAccepts("optionalDouble", maxDouble.toString()); + assertAccepts("optionalDouble", minDouble.toString()); + assertRejects("optionalDouble", maxDouble.multiply(moreThanOne).toString()); + assertRejects("optionalDouble", minDouble.multiply(moreThanOne).toString()); + } + + @Test + public void testParserAcceptNull() throws Exception { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + mergeFromJson( + "{\n" + + " \"optionalInt32\": null,\n" + + " \"optionalInt64\": null,\n" + + " \"optionalUint32\": null,\n" + + " \"optionalUint64\": null,\n" + + " \"optionalSint32\": null,\n" + + " \"optionalSint64\": null,\n" + + " \"optionalFixed32\": null,\n" + + " \"optionalFixed64\": null,\n" + + " \"optionalSfixed32\": null,\n" + + " \"optionalSfixed64\": null,\n" + + " \"optionalFloat\": null,\n" + + " \"optionalDouble\": null,\n" + + " \"optionalBool\": null,\n" + + " \"optionalString\": null,\n" + + " \"optionalBytes\": null,\n" + + " \"optionalNestedMessage\": null,\n" + + " \"optionalNestedEnum\": null,\n" + + " \"repeatedInt32\": null,\n" + + " \"repeatedInt64\": null,\n" + + " \"repeatedUint32\": null,\n" + + " \"repeatedUint64\": null,\n" + + " \"repeatedSint32\": null,\n" + + " \"repeatedSint64\": null,\n" + + " \"repeatedFixed32\": null,\n" + + " \"repeatedFixed64\": null,\n" + + " \"repeatedSfixed32\": null,\n" + + " \"repeatedSfixed64\": null,\n" + + " \"repeatedFloat\": null,\n" + + " \"repeatedDouble\": null,\n" + + " \"repeatedBool\": null,\n" + + " \"repeatedString\": null,\n" + + " \"repeatedBytes\": null,\n" + + " \"repeatedNestedMessage\": null,\n" + + " \"repeatedNestedEnum\": null\n" + + "}", + builder); + TestAllTypes message = builder.build(); + assertThat(message).isEqualTo(TestAllTypes.getDefaultInstance()); + + // Repeated field elements cannot be null. + try { + builder = TestAllTypes.newBuilder(); + mergeFromJson("{\n" + " \"repeatedInt32\": [null, null],\n" + "}", builder); + assertWithMessage("expected exception").fail(); + } catch (InvalidProtocolBufferException e) { + // Exception expected. + } + + try { + builder = TestAllTypes.newBuilder(); + mergeFromJson("{\n" + " \"repeatedNestedMessage\": [null, null],\n" + "}", builder); + assertWithMessage("expected exception").fail(); + } catch (InvalidProtocolBufferException e) { + // Exception expected. + } + } + + @Test + public void testNullInOneof() throws Exception { + TestOneof.Builder builder = TestOneof.newBuilder(); + mergeFromJson("{\n" + " \"oneofNullValue\": null \n" + "}", builder); + TestOneof message = builder.build(); + assertThat(message.getOneofFieldCase()).isEqualTo(TestOneof.OneofFieldCase.ONEOF_NULL_VALUE); + assertThat(message.getOneofNullValue()).isEqualTo(NullValue.NULL_VALUE); + } + + @Test + public void testNullFirstInDuplicateOneof() throws Exception { + TestOneof.Builder builder = TestOneof.newBuilder(); + mergeFromJson("{\"oneofNestedMessage\": null, \"oneofInt32\": 1}", builder); + TestOneof message = builder.build(); + assertThat(message.getOneofInt32()).isEqualTo(1); + } + + @Test + public void testNullLastInDuplicateOneof() throws Exception { + TestOneof.Builder builder = TestOneof.newBuilder(); + mergeFromJson("{\"oneofInt32\": 1, \"oneofNestedMessage\": null}", builder); + TestOneof message = builder.build(); + assertThat(message.getOneofInt32()).isEqualTo(1); + } + + @Test + public void testParserRejectDuplicatedFields() throws Exception { + // TODO(xiaofeng): The parser we are currently using (GSON) will accept and keep the last + // one if multiple entries have the same name. This is not the desired behavior but it can + // only be fixed by using our own parser. Here we only test the cases where the names are + // different but still referring to the same field. + + // Duplicated optional fields. + try { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + mergeFromJson( + "{\n" + + " \"optionalNestedMessage\": {},\n" + + " \"optional_nested_message\": {}\n" + + "}", + builder); + assertWithMessage("expected exception").fail(); + } catch (InvalidProtocolBufferException e) { + // Exception expected. + } + + // Duplicated repeated fields. + try { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + mergeFromJson( + "{\n" + + " \"repeatedInt32\": [1, 2],\n" + + " \"repeated_int32\": [5, 6]\n" + + "}", + builder); + assertWithMessage("expected exception").fail(); + } catch (InvalidProtocolBufferException e) { + // Exception expected. + } + + // Duplicated oneof fields, same name. + try { + TestOneof.Builder builder = TestOneof.newBuilder(); + mergeFromJson("{\n" + " \"oneofInt32\": 1,\n" + " \"oneof_int32\": 2\n" + "}", builder); + assertWithMessage("expected exception").fail(); + } catch (InvalidProtocolBufferException e) { + // Exception expected. + } + + // Duplicated oneof fields, different name. + try { + TestOneof.Builder builder = TestOneof.newBuilder(); + mergeFromJson( + "{\n" + " \"oneofInt32\": 1,\n" + " \"oneofNullValue\": null\n" + "}", builder); + assertWithMessage("expected exception").fail(); + } catch (InvalidProtocolBufferException e) { + // Exception expected. + } + } + + @Test + public void testMapFields() throws Exception { + TestMap.Builder builder = TestMap.newBuilder(); + builder.putInt32ToInt32Map(1, 10); + builder.putInt64ToInt32Map(1234567890123456789L, 10); + builder.putUint32ToInt32Map(2, 20); + builder.putUint64ToInt32Map(2234567890123456789L, 20); + builder.putSint32ToInt32Map(3, 30); + builder.putSint64ToInt32Map(3234567890123456789L, 30); + builder.putFixed32ToInt32Map(4, 40); + builder.putFixed64ToInt32Map(4234567890123456789L, 40); + builder.putSfixed32ToInt32Map(5, 50); + builder.putSfixed64ToInt32Map(5234567890123456789L, 50); + builder.putBoolToInt32Map(false, 6); + builder.putStringToInt32Map("Hello", 10); + + builder.putInt32ToInt64Map(1, 1234567890123456789L); + builder.putInt32ToUint32Map(2, 20); + builder.putInt32ToUint64Map(2, 2234567890123456789L); + builder.putInt32ToSint32Map(3, 30); + builder.putInt32ToSint64Map(3, 3234567890123456789L); + builder.putInt32ToFixed32Map(4, 40); + builder.putInt32ToFixed64Map(4, 4234567890123456789L); + builder.putInt32ToSfixed32Map(5, 50); + builder.putInt32ToSfixed64Map(5, 5234567890123456789L); + builder.putInt32ToFloatMap(6, 1.5f); + builder.putInt32ToDoubleMap(6, 1.25); + builder.putInt32ToBoolMap(7, false); + builder.putInt32ToStringMap(7, "World"); + builder.putInt32ToBytesMap(8, ByteString.copyFrom(new byte[] {1, 2, 3})); + builder.putInt32ToMessageMap(8, NestedMessage.newBuilder().setValue(1234).build()); + builder.putInt32ToEnumMap(9, NestedEnum.BAR); + TestMap message = builder.build(); + + assertThat(toJsonString(message)) + .isEqualTo( + "{\n" + + " \"int32ToInt32Map\": {\n" + + " \"1\": 10\n" + + " },\n" + + " \"int64ToInt32Map\": {\n" + + " \"1234567890123456789\": 10\n" + + " },\n" + + " \"uint32ToInt32Map\": {\n" + + " \"2\": 20\n" + + " },\n" + + " \"uint64ToInt32Map\": {\n" + + " \"2234567890123456789\": 20\n" + + " },\n" + + " \"sint32ToInt32Map\": {\n" + + " \"3\": 30\n" + + " },\n" + + " \"sint64ToInt32Map\": {\n" + + " \"3234567890123456789\": 30\n" + + " },\n" + + " \"fixed32ToInt32Map\": {\n" + + " \"4\": 40\n" + + " },\n" + + " \"fixed64ToInt32Map\": {\n" + + " \"4234567890123456789\": 40\n" + + " },\n" + + " \"sfixed32ToInt32Map\": {\n" + + " \"5\": 50\n" + + " },\n" + + " \"sfixed64ToInt32Map\": {\n" + + " \"5234567890123456789\": 50\n" + + " },\n" + + " \"boolToInt32Map\": {\n" + + " \"false\": 6\n" + + " },\n" + + " \"stringToInt32Map\": {\n" + + " \"Hello\": 10\n" + + " },\n" + + " \"int32ToInt64Map\": {\n" + + " \"1\": \"1234567890123456789\"\n" + + " },\n" + + " \"int32ToUint32Map\": {\n" + + " \"2\": 20\n" + + " },\n" + + " \"int32ToUint64Map\": {\n" + + " \"2\": \"2234567890123456789\"\n" + + " },\n" + + " \"int32ToSint32Map\": {\n" + + " \"3\": 30\n" + + " },\n" + + " \"int32ToSint64Map\": {\n" + + " \"3\": \"3234567890123456789\"\n" + + " },\n" + + " \"int32ToFixed32Map\": {\n" + + " \"4\": 40\n" + + " },\n" + + " \"int32ToFixed64Map\": {\n" + + " \"4\": \"4234567890123456789\"\n" + + " },\n" + + " \"int32ToSfixed32Map\": {\n" + + " \"5\": 50\n" + + " },\n" + + " \"int32ToSfixed64Map\": {\n" + + " \"5\": \"5234567890123456789\"\n" + + " },\n" + + " \"int32ToFloatMap\": {\n" + + " \"6\": 1.5\n" + + " },\n" + + " \"int32ToDoubleMap\": {\n" + + " \"6\": 1.25\n" + + " },\n" + + " \"int32ToBoolMap\": {\n" + + " \"7\": false\n" + + " },\n" + + " \"int32ToStringMap\": {\n" + + " \"7\": \"World\"\n" + + " },\n" + + " \"int32ToBytesMap\": {\n" + + " \"8\": \"AQID\"\n" + + " },\n" + + " \"int32ToMessageMap\": {\n" + + " \"8\": {\n" + + " \"value\": 1234\n" + + " }\n" + + " },\n" + + " \"int32ToEnumMap\": {\n" + + " \"9\": \"BAR\"\n" + + " }\n" + + "}"); + assertRoundTripEquals(message); + + // Test multiple entries. + builder = TestMap.newBuilder(); + builder.putInt32ToInt32Map(1, 2); + builder.putInt32ToInt32Map(3, 4); + message = builder.build(); + + assertThat(toJsonString(message)) + .isEqualTo( + "{\n" + + " \"int32ToInt32Map\": {\n" + + " \"1\": 2,\n" + + " \"3\": 4\n" + + " }\n" + + "}"); + assertRoundTripEquals(message); + } + + @Test + public void testMapNullValueIsRejected() throws Exception { + try { + TestMap.Builder builder = TestMap.newBuilder(); + mergeFromJson( + "{\n" + + " \"int32ToInt32Map\": {null: 1},\n" + + " \"int32ToMessageMap\": {null: 2}\n" + + "}", + builder); + assertWithMessage("expected exception").fail(); + } catch (InvalidProtocolBufferException e) { + // Exception expected. + } + + try { + TestMap.Builder builder = TestMap.newBuilder(); + mergeFromJson( + "{\n" + + " \"int32ToInt32Map\": {\"1\": null},\n" + + " \"int32ToMessageMap\": {\"2\": null}\n" + + "}", + builder); + assertWithMessage("expected exception").fail(); + + } catch (InvalidProtocolBufferException e) { + // Exception expected. + } + } + + @Test + public void testMapEnumNullValueIsIgnored() throws Exception { + TestMap.Builder builder = TestMap.newBuilder(); + mergeFromJsonIgnoringUnknownFields( + "{\n" + " \"int32ToEnumMap\": {\"1\": null}\n" + "}", builder); + TestMap map = builder.build(); + assertThat(map.getInt32ToEnumMapMap()).isEmpty(); + } + + @Test + public void testParserAcceptNonQuotedObjectKey() throws Exception { + TestMap.Builder builder = TestMap.newBuilder(); + mergeFromJson( + "{\n" + " int32ToInt32Map: {1: 2},\n" + " stringToInt32Map: {hello: 3}\n" + "}", builder); + TestMap message = builder.build(); + assertThat(message.getInt32ToInt32MapMap().get(1).intValue()).isEqualTo(2); + assertThat(message.getStringToInt32MapMap().get("hello").intValue()).isEqualTo(3); + } + + @Test + public void testWrappers() throws Exception { + TestWrappers.Builder builder = TestWrappers.newBuilder(); + builder.getBoolValueBuilder().setValue(false); + builder.getInt32ValueBuilder().setValue(0); + builder.getInt64ValueBuilder().setValue(0); + builder.getUint32ValueBuilder().setValue(0); + builder.getUint64ValueBuilder().setValue(0); + builder.getFloatValueBuilder().setValue(0.0f); + builder.getDoubleValueBuilder().setValue(0.0); + builder.getStringValueBuilder().setValue(""); + builder.getBytesValueBuilder().setValue(ByteString.EMPTY); + TestWrappers message = builder.build(); + + assertThat(toJsonString(message)) + .isEqualTo( + "{\n" + + " \"int32Value\": 0,\n" + + " \"uint32Value\": 0,\n" + + " \"int64Value\": \"0\",\n" + + " \"uint64Value\": \"0\",\n" + + " \"floatValue\": 0.0,\n" + + " \"doubleValue\": 0.0,\n" + + " \"boolValue\": false,\n" + + " \"stringValue\": \"\",\n" + + " \"bytesValue\": \"\"\n" + + "}"); + assertRoundTripEquals(message); + + builder = TestWrappers.newBuilder(); + builder.getBoolValueBuilder().setValue(true); + builder.getInt32ValueBuilder().setValue(1); + builder.getInt64ValueBuilder().setValue(2); + builder.getUint32ValueBuilder().setValue(3); + builder.getUint64ValueBuilder().setValue(4); + builder.getFloatValueBuilder().setValue(5.0f); + builder.getDoubleValueBuilder().setValue(6.0); + builder.getStringValueBuilder().setValue("7"); + builder.getBytesValueBuilder().setValue(ByteString.copyFrom(new byte[] {8})); + message = builder.build(); + + assertThat(toJsonString(message)) + .isEqualTo( + "{\n" + + " \"int32Value\": 1,\n" + + " \"uint32Value\": 3,\n" + + " \"int64Value\": \"2\",\n" + + " \"uint64Value\": \"4\",\n" + + " \"floatValue\": 5.0,\n" + + " \"doubleValue\": 6.0,\n" + + " \"boolValue\": true,\n" + + " \"stringValue\": \"7\",\n" + + " \"bytesValue\": \"CA==\"\n" + + "}"); + assertRoundTripEquals(message); + } + + @Test + public void testTimestamp() throws Exception { + TestTimestamp message = + TestTimestamp.newBuilder() + .setTimestampValue(Timestamps.parse("1970-01-01T00:00:00Z")) + .build(); + + assertThat(toJsonString(message)) + .isEqualTo("{\n" + " \"timestampValue\": \"1970-01-01T00:00:00Z\"\n" + "}"); + assertRoundTripEquals(message); + } + + @Test + public void testTimestampMergeError() throws Exception { + final String incorrectTimestampString = "{\"seconds\":1800,\"nanos\":0}"; + try { + TestTimestamp.Builder builder = TestTimestamp.newBuilder(); + mergeFromJson(String.format("{\"timestamp_value\": %s}", incorrectTimestampString), builder); + assertWithMessage("expected exception").fail(); + } catch (InvalidProtocolBufferException e) { + // Exception expected. + assertThat(e) + .hasMessageThat() + .isEqualTo("Failed to parse timestamp: " + incorrectTimestampString); + } + } + + @Test + public void testDuration() throws Exception { + TestDuration message = + TestDuration.newBuilder().setDurationValue(Durations.parse("12345s")).build(); + + assertThat(toJsonString(message)).isEqualTo("{\n" + " \"durationValue\": \"12345s\"\n" + "}"); + assertRoundTripEquals(message); + } + + @Test + public void testDurationMergeError() throws Exception { + final String incorrectDurationString = "{\"seconds\":10,\"nanos\":500}"; + try { + TestDuration.Builder builder = TestDuration.newBuilder(); + mergeFromJson(String.format("{\"duration_value\": %s}", incorrectDurationString), builder); + assertWithMessage("expected exception").fail(); + } catch (InvalidProtocolBufferException e) { + // Exception expected. + assertThat(e) + .hasMessageThat() + .isEqualTo("Failed to parse duration: " + incorrectDurationString); + } + } + + @Test + public void testFieldMask() throws Exception { + TestFieldMask message = + TestFieldMask.newBuilder() + .setFieldMaskValue(FieldMaskUtil.fromString("foo.bar,baz,foo_bar.baz")) + .build(); + + assertThat(toJsonString(message)) + .isEqualTo("{\n" + " \"fieldMaskValue\": \"foo.bar,baz,fooBar.baz\"\n" + "}"); + assertRoundTripEquals(message); + } + + @Test + public void testStruct() throws Exception { + // Build a struct with all possible values. + TestStruct.Builder builder = TestStruct.newBuilder(); + Struct.Builder structBuilder = builder.getStructValueBuilder(); + structBuilder.putFields("null_value", Value.newBuilder().setNullValueValue(0).build()); + structBuilder.putFields("number_value", Value.newBuilder().setNumberValue(1.25).build()); + structBuilder.putFields("string_value", Value.newBuilder().setStringValue("hello").build()); + Struct.Builder subStructBuilder = Struct.newBuilder(); + subStructBuilder.putFields("number_value", Value.newBuilder().setNumberValue(1234).build()); + structBuilder.putFields( + "struct_value", Value.newBuilder().setStructValue(subStructBuilder.build()).build()); + ListValue.Builder listBuilder = ListValue.newBuilder(); + listBuilder.addValues(Value.newBuilder().setNumberValue(1.125).build()); + listBuilder.addValues(Value.newBuilder().setNullValueValue(0).build()); + structBuilder.putFields( + "list_value", Value.newBuilder().setListValue(listBuilder.build()).build()); + TestStruct message = builder.build(); + + assertThat(toJsonString(message)) + .isEqualTo( + "{\n" + + " \"structValue\": {\n" + + " \"null_value\": null,\n" + + " \"number_value\": 1.25,\n" + + " \"string_value\": \"hello\",\n" + + " \"struct_value\": {\n" + + " \"number_value\": 1234.0\n" + + " },\n" + + " \"list_value\": [1.125, null]\n" + + " }\n" + + "}"); + assertRoundTripEquals(message); + + builder = TestStruct.newBuilder(); + builder.setValue(Value.newBuilder().setNullValueValue(0).build()); + message = builder.build(); + assertThat(toJsonString(message)).isEqualTo("{\n" + " \"value\": null\n" + "}"); + assertRoundTripEquals(message); + + builder = TestStruct.newBuilder(); + listBuilder = builder.getListValueBuilder(); + listBuilder.addValues(Value.newBuilder().setNumberValue(31831.125).build()); + listBuilder.addValues(Value.newBuilder().setNullValueValue(0).build()); + message = builder.build(); + assertThat(toJsonString(message)) + .isEqualTo("{\n" + " \"listValue\": [31831.125, null]\n" + "}"); + assertRoundTripEquals(message); + } + + + @Test + public void testAnyFieldsWithCustomAddedTypeRegistry() throws Exception { + TestAllTypes content = TestAllTypes.newBuilder().setOptionalInt32(1234).build(); + TestAny message = TestAny.newBuilder().setAnyValue(Any.pack(content)).build(); + + com.google.protobuf.TypeRegistry registry = + com.google.protobuf.TypeRegistry.newBuilder().add(content.getDescriptorForType()).build(); + JsonFormat.Printer printer = JsonFormat.printer().usingTypeRegistry(registry); + + assertThat(printer.print(message)) + .isEqualTo( + "{\n" + + " \"anyValue\": {\n" + + " \"@type\": \"type.googleapis.com/json_test.TestAllTypes\",\n" + + " \"optionalInt32\": 1234\n" + + " }\n" + + "}"); + assertRoundTripEquals(message, registry); + + TestAny messageWithDefaultAnyValue = + TestAny.newBuilder().setAnyValue(Any.getDefaultInstance()).build(); + assertThat(printer.print(messageWithDefaultAnyValue)) + .isEqualTo("{\n" + " \"anyValue\": {}\n" + "}"); + assertRoundTripEquals(messageWithDefaultAnyValue, registry); + + // Well-known types have a special formatting when embedded in Any. + // + // 1. Any in Any. + Any anyMessage = Any.pack(Any.pack(content)); + assertThat(printer.print(anyMessage)) + .isEqualTo( + "{\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.Any\",\n" + + " \"value\": {\n" + + " \"@type\": \"type.googleapis.com/json_test.TestAllTypes\",\n" + + " \"optionalInt32\": 1234\n" + + " }\n" + + "}"); + assertRoundTripEquals(anyMessage, registry); + } + + @Test + public void testAnyFields() throws Exception { + TestAllTypes content = TestAllTypes.newBuilder().setOptionalInt32(1234).build(); + TestAny message = TestAny.newBuilder().setAnyValue(Any.pack(content)).build(); + + // A TypeRegistry must be provided in order to convert Any types. + try { + toJsonString(message); + assertWithMessage("Exception is expected.").fail(); + } catch (IOException e) { + // Expected. + } + + JsonFormat.TypeRegistry registry = + JsonFormat.TypeRegistry.newBuilder().add(TestAllTypes.getDescriptor()).build(); + JsonFormat.Printer printer = JsonFormat.printer().usingTypeRegistry(registry); + + assertThat(printer.print(message)) + .isEqualTo( + "{\n" + + " \"anyValue\": {\n" + + " \"@type\": \"type.googleapis.com/json_test.TestAllTypes\",\n" + + " \"optionalInt32\": 1234\n" + + " }\n" + + "}"); + assertRoundTripEquals(message, registry); + + TestAny messageWithDefaultAnyValue = + TestAny.newBuilder().setAnyValue(Any.getDefaultInstance()).build(); + assertThat(printer.print(messageWithDefaultAnyValue)) + .isEqualTo("{\n" + " \"anyValue\": {}\n" + "}"); + assertRoundTripEquals(messageWithDefaultAnyValue, registry); + + // Well-known types have a special formatting when embedded in Any. + // + // 1. Any in Any. + Any anyMessage = Any.pack(Any.pack(content)); + assertThat(printer.print(anyMessage)) + .isEqualTo( + "{\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.Any\",\n" + + " \"value\": {\n" + + " \"@type\": \"type.googleapis.com/json_test.TestAllTypes\",\n" + + " \"optionalInt32\": 1234\n" + + " }\n" + + "}"); + assertRoundTripEquals(anyMessage, registry); + + // 2. Wrappers in Any. + anyMessage = Any.pack(Int32Value.of(12345)); + assertThat(printer.print(anyMessage)) + .isEqualTo( + "{\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.Int32Value\",\n" + + " \"value\": 12345\n" + + "}"); + assertRoundTripEquals(anyMessage, registry); + anyMessage = Any.pack(UInt32Value.of(12345)); + assertThat(printer.print(anyMessage)) + .isEqualTo( + "{\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.UInt32Value\",\n" + + " \"value\": 12345\n" + + "}"); + assertRoundTripEquals(anyMessage, registry); + anyMessage = Any.pack(Int64Value.of(12345)); + assertThat(printer.print(anyMessage)) + .isEqualTo( + "{\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.Int64Value\",\n" + + " \"value\": \"12345\"\n" + + "}"); + assertRoundTripEquals(anyMessage, registry); + anyMessage = Any.pack(UInt64Value.newBuilder().setValue(12345).build()); + assertThat(printer.print(anyMessage)) + .isEqualTo( + "{\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.UInt64Value\",\n" + + " \"value\": \"12345\"\n" + + "}"); + assertRoundTripEquals(anyMessage, registry); + anyMessage = Any.pack(FloatValue.newBuilder().setValue(12345).build()); + assertThat(printer.print(anyMessage)) + .isEqualTo( + "{\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.FloatValue\",\n" + + " \"value\": 12345.0\n" + + "}"); + assertRoundTripEquals(anyMessage, registry); + anyMessage = Any.pack(DoubleValue.newBuilder().setValue(12345).build()); + assertThat(printer.print(anyMessage)) + .isEqualTo( + "{\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.DoubleValue\",\n" + + " \"value\": 12345.0\n" + + "}"); + assertRoundTripEquals(anyMessage, registry); + anyMessage = Any.pack(BoolValue.of(true)); + assertThat(printer.print(anyMessage)) + .isEqualTo( + "{\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.BoolValue\",\n" + + " \"value\": true\n" + + "}"); + assertRoundTripEquals(anyMessage, registry); + anyMessage = Any.pack(StringValue.of("Hello")); + assertThat(printer.print(anyMessage)) + .isEqualTo( + "{\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.StringValue\",\n" + + " \"value\": \"Hello\"\n" + + "}"); + assertRoundTripEquals(anyMessage, registry); + anyMessage = Any.pack(BytesValue.of(ByteString.copyFrom(new byte[] {1, 2}))); + assertThat(printer.print(anyMessage)) + .isEqualTo( + "{\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.BytesValue\",\n" + + " \"value\": \"AQI=\"\n" + + "}"); + assertRoundTripEquals(anyMessage, registry); + + // 3. Timestamp in Any. + anyMessage = Any.pack(Timestamps.parse("1969-12-31T23:59:59Z")); + assertThat(printer.print(anyMessage)) + .isEqualTo( + "{\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.Timestamp\",\n" + + " \"value\": \"1969-12-31T23:59:59Z\"\n" + + "}"); + assertRoundTripEquals(anyMessage, registry); + + // 4. Duration in Any + anyMessage = Any.pack(Durations.parse("12345.10s")); + assertThat(printer.print(anyMessage)) + .isEqualTo( + "{\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.Duration\",\n" + + " \"value\": \"12345.100s\"\n" + + "}"); + assertRoundTripEquals(anyMessage, registry); + + // 5. FieldMask in Any + anyMessage = Any.pack(FieldMaskUtil.fromString("foo.bar,baz")); + assertThat(printer.print(anyMessage)) + .isEqualTo( + "{\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.FieldMask\",\n" + + " \"value\": \"foo.bar,baz\"\n" + + "}"); + assertRoundTripEquals(anyMessage, registry); + + // 6. Struct in Any + Struct.Builder structBuilder = Struct.newBuilder(); + structBuilder.putFields("number", Value.newBuilder().setNumberValue(1.125).build()); + anyMessage = Any.pack(structBuilder.build()); + assertThat(printer.print(anyMessage)) + .isEqualTo( + "{\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.Struct\",\n" + + " \"value\": {\n" + + " \"number\": 1.125\n" + + " }\n" + + "}"); + assertRoundTripEquals(anyMessage, registry); + + // 7. Value (number type) in Any + Value.Builder valueBuilder = Value.newBuilder(); + valueBuilder.setNumberValue(1); + anyMessage = Any.pack(valueBuilder.build()); + assertThat(printer.print(anyMessage)) + .isEqualTo( + "{\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.Value\",\n" + + " \"value\": 1.0\n" + + "}"); + assertRoundTripEquals(anyMessage, registry); + + // 8. Value (null type) in Any + anyMessage = Any.pack(Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build()); + assertThat(printer.print(anyMessage)) + .isEqualTo( + "{\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.Value\",\n" + + " \"value\": null\n" + + "}"); + assertRoundTripEquals(anyMessage, registry); + } + + @Test + public void testAnyInMaps() throws Exception { + JsonFormat.TypeRegistry registry = + JsonFormat.TypeRegistry.newBuilder().add(TestAllTypes.getDescriptor()).build(); + JsonFormat.Printer printer = JsonFormat.printer().usingTypeRegistry(registry); + + TestAny.Builder testAny = TestAny.newBuilder(); + testAny.putAnyMap("int32_wrapper", Any.pack(Int32Value.of(123))); + testAny.putAnyMap("int64_wrapper", Any.pack(Int64Value.of(456))); + testAny.putAnyMap("timestamp", Any.pack(Timestamps.parse("1969-12-31T23:59:59Z"))); + testAny.putAnyMap("duration", Any.pack(Durations.parse("12345.1s"))); + testAny.putAnyMap("field_mask", Any.pack(FieldMaskUtil.fromString("foo.bar,baz"))); + Value numberValue = Value.newBuilder().setNumberValue(1.125).build(); + Struct.Builder struct = Struct.newBuilder(); + struct.putFields("number", numberValue); + testAny.putAnyMap("struct", Any.pack(struct.build())); + Value nullValue = Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build(); + testAny.putAnyMap( + "list_value", + Any.pack(ListValue.newBuilder().addValues(numberValue).addValues(nullValue).build())); + testAny.putAnyMap("number_value", Any.pack(numberValue)); + testAny.putAnyMap("any_value_number", Any.pack(Any.pack(numberValue))); + testAny.putAnyMap("any_value_default", Any.pack(Any.getDefaultInstance())); + testAny.putAnyMap("default", Any.getDefaultInstance()); + + assertThat(printer.print(testAny.build())) + .isEqualTo( + "{\n" + + " \"anyMap\": {\n" + + " \"int32_wrapper\": {\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.Int32Value\",\n" + + " \"value\": 123\n" + + " },\n" + + " \"int64_wrapper\": {\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.Int64Value\",\n" + + " \"value\": \"456\"\n" + + " },\n" + + " \"timestamp\": {\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.Timestamp\",\n" + + " \"value\": \"1969-12-31T23:59:59Z\"\n" + + " },\n" + + " \"duration\": {\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.Duration\",\n" + + " \"value\": \"12345.100s\"\n" + + " },\n" + + " \"field_mask\": {\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.FieldMask\",\n" + + " \"value\": \"foo.bar,baz\"\n" + + " },\n" + + " \"struct\": {\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.Struct\",\n" + + " \"value\": {\n" + + " \"number\": 1.125\n" + + " }\n" + + " },\n" + + " \"list_value\": {\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.ListValue\",\n" + + " \"value\": [1.125, null]\n" + + " },\n" + + " \"number_value\": {\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.Value\",\n" + + " \"value\": 1.125\n" + + " },\n" + + " \"any_value_number\": {\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.Any\",\n" + + " \"value\": {\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.Value\",\n" + + " \"value\": 1.125\n" + + " }\n" + + " },\n" + + " \"any_value_default\": {\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.Any\",\n" + + " \"value\": {}\n" + + " },\n" + + " \"default\": {}\n" + + " }\n" + + "}"); + assertRoundTripEquals(testAny.build(), registry); + } + + @Test + public void testParserMissingTypeUrl() throws Exception { + try { + Any.Builder builder = Any.newBuilder(); + mergeFromJson("{\n" + " \"optionalInt32\": 1234\n" + "}", builder); + assertWithMessage("Exception is expected.").fail(); + } catch (IOException e) { + // Expected. + } + } + + @Test + public void testParserUnexpectedTypeUrl() throws Exception { + try { + Any.Builder builder = Any.newBuilder(); + mergeFromJson( + "{\n" + + " \"@type\": \"type.googleapis.com/json_test.UnexpectedTypes\",\n" + + " \"optionalInt32\": 12345\n" + + "}", + builder); + assertWithMessage("Exception is expected.").fail(); + } catch (IOException e) { + // Expected. + } + } + + @Test + public void testParserRejectTrailingComma() throws Exception { + try { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + mergeFromJson("{\n" + " \"optionalInt32\": 12345,\n" + "}", builder); + assertWithMessage("Exception is expected.").fail(); + } catch (IOException e) { + // Expected. + } + + // TODO(xiaofeng): GSON allows trailing comma in arrays even after I set + // the JsonReader to non-lenient mode. If we want to enforce strict JSON + // compliance, we might want to switch to a different JSON parser or + // implement one by ourselves. + // try { + // TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + // JsonFormat.merge( + // "{\n" + // + " \"repeatedInt32\": [12345,]\n" + // + "}", builder); + // fail("Exception is expected."); + // } catch (IOException e) { + // // Expected. + // } + } + + @Test + public void testParserRejectInvalidBase64() throws Exception { + assertRejects("optionalBytes", "!@#$"); + } + + @Test + public void testParserAcceptBase64Variants() throws Exception { + assertAccepts("optionalBytes", "AQI"); // No padding + assertAccepts("optionalBytes", "-_w"); // base64Url, no padding + } + + @Test + public void testParserRejectInvalidEnumValue() throws Exception { + try { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + mergeFromJson("{\n" + " \"optionalNestedEnum\": \"XXX\"\n" + "}", builder); + assertWithMessage("Exception is expected.").fail(); + } catch (InvalidProtocolBufferException e) { + // Expected. + } + } + + @Test + public void testParserUnknownFields() throws Exception { + try { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + String json = "{\n" + " \"unknownField\": \"XXX\"\n" + "}"; + JsonFormat.parser().merge(json, builder); + assertWithMessage("Exception is expected.").fail(); + } catch (InvalidProtocolBufferException e) { + // Expected. + } + } + + @Test + public void testParserIgnoringUnknownFields() throws Exception { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + String json = "{\n" + " \"unknownField\": \"XXX\"\n" + "}"; + JsonFormat.parser().ignoringUnknownFields().merge(json, builder); + } + + @Test + public void testParserIgnoringUnknownEnums() throws Exception { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + String json = "{\n" + " \"optionalNestedEnum\": \"XXX\"\n" + "}"; + JsonFormat.parser().ignoringUnknownFields().merge(json, builder); + assertThat(builder.getOptionalNestedEnumValue()).isEqualTo(0); + } + + @Test + public void testParserSupportAliasEnums() throws Exception { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + String json = "{\n" + " \"optionalAliasedEnum\": \"QUX\"\n" + "}"; + JsonFormat.parser().merge(json, builder); + assertThat(builder.getOptionalAliasedEnum()).isEqualTo(AliasedEnum.ALIAS_BAZ); + + builder = TestAllTypes.newBuilder(); + json = "{\n" + " \"optionalAliasedEnum\": \"qux\"\n" + "}"; + JsonFormat.parser().merge(json, builder); + assertThat(builder.getOptionalAliasedEnum()).isEqualTo(AliasedEnum.ALIAS_BAZ); + + builder = TestAllTypes.newBuilder(); + json = "{\n" + " \"optionalAliasedEnum\": \"bAz\"\n" + "}"; + JsonFormat.parser().merge(json, builder); + assertThat(builder.getOptionalAliasedEnum()).isEqualTo(AliasedEnum.ALIAS_BAZ); + } + + @Test + public void testUnknownEnumMap() throws Exception { + TestMap.Builder builder = TestMap.newBuilder(); + JsonFormat.parser() + .ignoringUnknownFields() + .merge("{\n" + " \"int32ToEnumMap\": {1: XXX, 2: FOO}" + "}", builder); + + assertThat(builder.getInt32ToEnumMapMap()).containsEntry(2, NestedEnum.FOO); + assertThat(builder.getInt32ToEnumMapMap()).hasSize(1); + } + + @Test + public void testRepeatedUnknownEnum() throws Exception { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + JsonFormat.parser() + .ignoringUnknownFields() + .merge("{\n" + " \"repeatedNestedEnum\": [XXX, FOO, BAR, BAZ]" + "}", builder); + + assertThat(builder.getRepeatedNestedEnum(0)).isEqualTo(NestedEnum.FOO); + assertThat(builder.getRepeatedNestedEnum(1)).isEqualTo(NestedEnum.BAR); + assertThat(builder.getRepeatedNestedEnum(2)).isEqualTo(NestedEnum.BAZ); + assertThat(builder.getRepeatedNestedEnumList()).hasSize(3); + } + + @Test + public void testParserIntegerEnumValue() throws Exception { + TestAllTypes.Builder actualBuilder = TestAllTypes.newBuilder(); + mergeFromJson("{\n" + " \"optionalNestedEnum\": 2\n" + "}", actualBuilder); + + TestAllTypes expected = TestAllTypes.newBuilder().setOptionalNestedEnum(NestedEnum.BAZ).build(); + assertThat(actualBuilder.build()).isEqualTo(expected); + } + + @Test + public void testCustomJsonName() throws Exception { + TestCustomJsonName message = TestCustomJsonName.newBuilder().setValue(12345).build(); + assertThat(JsonFormat.printer().print(message)) + .isEqualTo("{\n" + " \"@value\": 12345\n" + "}"); + assertRoundTripEquals(message); + } + + // Regression test for b/73832901. Make sure html tags are escaped. + @Test + public void testHtmlEscape() throws Exception { + TestAllTypes message = TestAllTypes.newBuilder().setOptionalString("").build(); + assertThat(toJsonString(message)) + .isEqualTo("{\n \"optionalString\": \"\\u003c/script\\u003e\"\n}"); + + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + JsonFormat.parser().merge(toJsonString(message), builder); + assertThat(builder.getOptionalString()).isEqualTo(message.getOptionalString()); + } + + @Test + public void testIncludingDefaultValueFields() throws Exception { + TestAllTypes message = TestAllTypes.getDefaultInstance(); + assertThat(JsonFormat.printer().print(message)).isEqualTo("{\n}"); + assertThat(JsonFormat.printer().includingDefaultValueFields().print(message)) + .isEqualTo( + "{\n" + + " \"optionalInt32\": 0,\n" + + " \"optionalInt64\": \"0\",\n" + + " \"optionalUint32\": 0,\n" + + " \"optionalUint64\": \"0\",\n" + + " \"optionalSint32\": 0,\n" + + " \"optionalSint64\": \"0\",\n" + + " \"optionalFixed32\": 0,\n" + + " \"optionalFixed64\": \"0\",\n" + + " \"optionalSfixed32\": 0,\n" + + " \"optionalSfixed64\": \"0\",\n" + + " \"optionalFloat\": 0.0,\n" + + " \"optionalDouble\": 0.0,\n" + + " \"optionalBool\": false,\n" + + " \"optionalString\": \"\",\n" + + " \"optionalBytes\": \"\",\n" + + " \"optionalNestedEnum\": \"FOO\",\n" + + " \"repeatedInt32\": [],\n" + + " \"repeatedInt64\": [],\n" + + " \"repeatedUint32\": [],\n" + + " \"repeatedUint64\": [],\n" + + " \"repeatedSint32\": [],\n" + + " \"repeatedSint64\": [],\n" + + " \"repeatedFixed32\": [],\n" + + " \"repeatedFixed64\": [],\n" + + " \"repeatedSfixed32\": [],\n" + + " \"repeatedSfixed64\": [],\n" + + " \"repeatedFloat\": [],\n" + + " \"repeatedDouble\": [],\n" + + " \"repeatedBool\": [],\n" + + " \"repeatedString\": [],\n" + + " \"repeatedBytes\": [],\n" + + " \"repeatedNestedMessage\": [],\n" + + " \"repeatedNestedEnum\": [],\n" + + " \"optionalAliasedEnum\": \"ALIAS_FOO\"\n" + + "}"); + + Set fixedFields = new HashSet<>(); + for (FieldDescriptor fieldDesc : TestAllTypes.getDescriptor().getFields()) { + if (fieldDesc.getName().contains("_fixed")) { + fixedFields.add(fieldDesc); + } + } + + assertThat(JsonFormat.printer().includingDefaultValueFields(fixedFields).print(message)) + .isEqualTo( + "{\n" + + " \"optionalFixed32\": 0,\n" + + " \"optionalFixed64\": \"0\",\n" + + " \"repeatedFixed32\": [],\n" + + " \"repeatedFixed64\": []\n" + + "}"); + + TestAllTypes messageNonDefaults = + message.toBuilder().setOptionalInt64(1234).setOptionalFixed32(3232).build(); + assertThat( + JsonFormat.printer().includingDefaultValueFields(fixedFields).print(messageNonDefaults)) + .isEqualTo( + "{\n" + + " \"optionalInt64\": \"1234\",\n" + + " \"optionalFixed32\": 3232,\n" + + " \"optionalFixed64\": \"0\",\n" + + " \"repeatedFixed32\": [],\n" + + " \"repeatedFixed64\": []\n" + + "}"); + + try { + JsonFormat.printer().includingDefaultValueFields().includingDefaultValueFields(); + assertWithMessage("IllegalStateException is expected.").fail(); + } catch (IllegalStateException e) { + // Expected. + assertWithMessage("Exception message should mention includingDefaultValueFields.") + .that(e.getMessage().contains("includingDefaultValueFields")) + .isTrue(); + } + + try { + JsonFormat.printer().includingDefaultValueFields().includingDefaultValueFields(fixedFields); + assertWithMessage("IllegalStateException is expected.").fail(); + } catch (IllegalStateException e) { + // Expected. + assertWithMessage("Exception message should mention includingDefaultValueFields.") + .that(e.getMessage().contains("includingDefaultValueFields")) + .isTrue(); + } + + try { + JsonFormat.printer().includingDefaultValueFields(fixedFields).includingDefaultValueFields(); + assertWithMessage("IllegalStateException is expected.").fail(); + } catch (IllegalStateException e) { + // Expected. + assertWithMessage("Exception message should mention includingDefaultValueFields.") + .that(e.getMessage().contains("includingDefaultValueFields")) + .isTrue(); + } + + try { + JsonFormat.printer() + .includingDefaultValueFields(fixedFields) + .includingDefaultValueFields(fixedFields); + assertWithMessage("IllegalStateException is expected.").fail(); + } catch (IllegalStateException e) { + // Expected. + assertWithMessage("Exception message should mention includingDefaultValueFields.") + .that(e.getMessage().contains("includingDefaultValueFields")) + .isTrue(); + } + + Set intFields = new HashSet<>(); + for (FieldDescriptor fieldDesc : TestAllTypes.getDescriptor().getFields()) { + if (fieldDesc.getName().contains("_int")) { + intFields.add(fieldDesc); + } + } + + try { + JsonFormat.printer() + .includingDefaultValueFields(intFields) + .includingDefaultValueFields(fixedFields); + assertWithMessage("IllegalStateException is expected.").fail(); + } catch (IllegalStateException e) { + // Expected. + assertWithMessage("Exception message should mention includingDefaultValueFields.") + .that(e.getMessage().contains("includingDefaultValueFields")) + .isTrue(); + } + + try { + JsonFormat.printer().includingDefaultValueFields(null); + assertWithMessage("IllegalArgumentException is expected.").fail(); + } catch (IllegalArgumentException e) { + // Expected. + assertWithMessage("Exception message should mention includingDefaultValueFields.") + .that(e.getMessage().contains("includingDefaultValueFields")) + .isTrue(); + } + + try { + JsonFormat.printer().includingDefaultValueFields(Collections.emptySet()); + assertWithMessage("IllegalArgumentException is expected.").fail(); + } catch (IllegalArgumentException e) { + // Expected. + assertWithMessage("Exception message should mention includingDefaultValueFields.") + .that(e.getMessage().contains("includingDefaultValueFields")) + .isTrue(); + } + + TestMap mapMessage = TestMap.getDefaultInstance(); + assertThat(JsonFormat.printer().print(mapMessage)).isEqualTo("{\n}"); + assertThat(JsonFormat.printer().includingDefaultValueFields().print(mapMessage)) + .isEqualTo( + "{\n" + + " \"int32ToInt32Map\": {\n" + + " },\n" + + " \"int64ToInt32Map\": {\n" + + " },\n" + + " \"uint32ToInt32Map\": {\n" + + " },\n" + + " \"uint64ToInt32Map\": {\n" + + " },\n" + + " \"sint32ToInt32Map\": {\n" + + " },\n" + + " \"sint64ToInt32Map\": {\n" + + " },\n" + + " \"fixed32ToInt32Map\": {\n" + + " },\n" + + " \"fixed64ToInt32Map\": {\n" + + " },\n" + + " \"sfixed32ToInt32Map\": {\n" + + " },\n" + + " \"sfixed64ToInt32Map\": {\n" + + " },\n" + + " \"boolToInt32Map\": {\n" + + " },\n" + + " \"stringToInt32Map\": {\n" + + " },\n" + + " \"int32ToInt64Map\": {\n" + + " },\n" + + " \"int32ToUint32Map\": {\n" + + " },\n" + + " \"int32ToUint64Map\": {\n" + + " },\n" + + " \"int32ToSint32Map\": {\n" + + " },\n" + + " \"int32ToSint64Map\": {\n" + + " },\n" + + " \"int32ToFixed32Map\": {\n" + + " },\n" + + " \"int32ToFixed64Map\": {\n" + + " },\n" + + " \"int32ToSfixed32Map\": {\n" + + " },\n" + + " \"int32ToSfixed64Map\": {\n" + + " },\n" + + " \"int32ToFloatMap\": {\n" + + " },\n" + + " \"int32ToDoubleMap\": {\n" + + " },\n" + + " \"int32ToBoolMap\": {\n" + + " },\n" + + " \"int32ToStringMap\": {\n" + + " },\n" + + " \"int32ToBytesMap\": {\n" + + " },\n" + + " \"int32ToMessageMap\": {\n" + + " },\n" + + " \"int32ToEnumMap\": {\n" + + " }\n" + + "}"); + + TestOneof oneofMessage = TestOneof.getDefaultInstance(); + assertThat(JsonFormat.printer().print(oneofMessage)).isEqualTo("{\n}"); + assertThat(JsonFormat.printer().includingDefaultValueFields().print(oneofMessage)) + .isEqualTo("{\n}"); + + oneofMessage = TestOneof.newBuilder().setOneofInt32(42).build(); + assertThat(JsonFormat.printer().print(oneofMessage)).isEqualTo("{\n \"oneofInt32\": 42\n}"); + assertThat(JsonFormat.printer().includingDefaultValueFields().print(oneofMessage)) + .isEqualTo("{\n \"oneofInt32\": 42\n}"); + + TestOneof.Builder oneofBuilder = TestOneof.newBuilder(); + mergeFromJson("{\n" + " \"oneofNullValue\": null \n" + "}", oneofBuilder); + oneofMessage = oneofBuilder.build(); + assertThat(JsonFormat.printer().print(oneofMessage)) + .isEqualTo("{\n \"oneofNullValue\": null\n}"); + assertThat(JsonFormat.printer().includingDefaultValueFields().print(oneofMessage)) + .isEqualTo("{\n \"oneofNullValue\": null\n}"); + } + + @Test + public void testPreservingProtoFieldNames() throws Exception { + TestAllTypes message = TestAllTypes.newBuilder().setOptionalInt32(12345).build(); + assertThat(JsonFormat.printer().print(message)) + .isEqualTo("{\n" + " \"optionalInt32\": 12345\n" + "}"); + assertThat(JsonFormat.printer().preservingProtoFieldNames().print(message)) + .isEqualTo("{\n" + " \"optional_int32\": 12345\n" + "}"); + + // The json_name field option is ignored when configured to use original proto field names. + TestCustomJsonName messageWithCustomJsonName = + TestCustomJsonName.newBuilder().setValue(12345).build(); + assertThat(JsonFormat.printer().preservingProtoFieldNames().print(messageWithCustomJsonName)) + .isEqualTo("{\n" + " \"value\": 12345\n" + "}"); + + // Parsers accept both original proto field names and lowerCamelCase names. + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + JsonFormat.parser().merge("{\"optionalInt32\": 12345}", builder); + assertThat(builder.getOptionalInt32()).isEqualTo(12345); + builder.clear(); + JsonFormat.parser().merge("{\"optional_int32\": 54321}", builder); + assertThat(builder.getOptionalInt32()).isEqualTo(54321); + } + + @Test + public void testPrintingEnumsAsInts() throws Exception { + TestAllTypes message = TestAllTypes.newBuilder().setOptionalNestedEnum(NestedEnum.BAR).build(); + assertThat(JsonFormat.printer().printingEnumsAsInts().print(message)) + .isEqualTo("{\n" + " \"optionalNestedEnum\": 1\n" + "}"); + } + + @Test + public void testOmittingInsignificantWhiteSpace() throws Exception { + TestAllTypes message = TestAllTypes.newBuilder().setOptionalInt32(12345).build(); + assertThat(JsonFormat.printer().omittingInsignificantWhitespace().print(message)) + .isEqualTo("{" + "\"optionalInt32\":12345" + "}"); + TestAllTypes message1 = TestAllTypes.getDefaultInstance(); + assertThat(JsonFormat.printer().omittingInsignificantWhitespace().print(message1)) + .isEqualTo("{}"); + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + setAllFields(builder); + TestAllTypes message2 = builder.build(); + assertThat(toCompactJsonString(message2)) + .isEqualTo( + "{" + + "\"optionalInt32\":1234," + + "\"optionalInt64\":\"1234567890123456789\"," + + "\"optionalUint32\":5678," + + "\"optionalUint64\":\"2345678901234567890\"," + + "\"optionalSint32\":9012," + + "\"optionalSint64\":\"3456789012345678901\"," + + "\"optionalFixed32\":3456," + + "\"optionalFixed64\":\"4567890123456789012\"," + + "\"optionalSfixed32\":7890," + + "\"optionalSfixed64\":\"5678901234567890123\"," + + "\"optionalFloat\":1.5," + + "\"optionalDouble\":1.25," + + "\"optionalBool\":true," + + "\"optionalString\":\"Hello world!\"," + + "\"optionalBytes\":\"AAEC\"," + + "\"optionalNestedMessage\":{" + + "\"value\":100" + + "}," + + "\"optionalNestedEnum\":\"BAR\"," + + "\"repeatedInt32\":[1234,234]," + + "\"repeatedInt64\":[\"1234567890123456789\",\"234567890123456789\"]," + + "\"repeatedUint32\":[5678,678]," + + "\"repeatedUint64\":[\"2345678901234567890\",\"345678901234567890\"]," + + "\"repeatedSint32\":[9012,10]," + + "\"repeatedSint64\":[\"3456789012345678901\",\"456789012345678901\"]," + + "\"repeatedFixed32\":[3456,456]," + + "\"repeatedFixed64\":[\"4567890123456789012\",\"567890123456789012\"]," + + "\"repeatedSfixed32\":[7890,890]," + + "\"repeatedSfixed64\":[\"5678901234567890123\",\"678901234567890123\"]," + + "\"repeatedFloat\":[1.5,11.5]," + + "\"repeatedDouble\":[1.25,11.25]," + + "\"repeatedBool\":[true,true]," + + "\"repeatedString\":[\"Hello world!\",\"ello world!\"]," + + "\"repeatedBytes\":[\"AAEC\",\"AQI=\"]," + + "\"repeatedNestedMessage\":[{" + + "\"value\":100" + + "},{" + + "\"value\":200" + + "}]," + + "\"repeatedNestedEnum\":[\"BAR\",\"BAZ\"]" + + "}"); + } + + // Regression test for b/29892357 + @Test + public void testEmptyWrapperTypesInAny() throws Exception { + JsonFormat.TypeRegistry registry = + JsonFormat.TypeRegistry.newBuilder().add(TestAllTypes.getDescriptor()).build(); + JsonFormat.Parser parser = JsonFormat.parser().usingTypeRegistry(registry); + + Any.Builder builder = Any.newBuilder(); + parser.merge( + "{\n" + + " \"@type\": \"type.googleapis.com/google.protobuf.BoolValue\",\n" + + " \"value\": false\n" + + "}\n", + builder); + Any any = builder.build(); + assertThat(any.getValue().size()).isEqualTo(0); + } + + @Test + public void testRecursionLimit() throws Exception { + String input = + "{\n" + + " \"nested\": {\n" + + " \"nested\": {\n" + + " \"nested\": {\n" + + " \"nested\": {\n" + + " \"value\": 1234\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "}\n"; + + JsonFormat.Parser parser = JsonFormat.parser(); + TestRecursive.Builder builder = TestRecursive.newBuilder(); + parser.merge(input, builder); + TestRecursive message = builder.build(); + assertThat(message.getNested().getNested().getNested().getNested().getValue()).isEqualTo(1234); + + parser = JsonFormat.parser().usingRecursionLimit(3); + builder = TestRecursive.newBuilder(); + try { + parser.merge(input, builder); + assertWithMessage("Exception is expected.").fail(); + } catch (InvalidProtocolBufferException e) { + // Expected. + } + } + + // Test that we are not leaking out JSON exceptions. + @Test + public void testJsonException() throws Exception { + InputStream throwingInputStream = + new InputStream() { + @Override + public int read() throws IOException { + throw new IOException("12345"); + } + }; + InputStreamReader throwingReader = new InputStreamReader(throwingInputStream); + // When the underlying reader throws IOException, JsonFormat should forward + // through this IOException. + try { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + JsonFormat.parser().merge(throwingReader, builder); + assertWithMessage("Exception is expected.").fail(); + } catch (IOException e) { + assertThat(e).hasMessageThat().isEqualTo("12345"); + } + + Reader invalidJsonReader = new StringReader("{ xxx - yyy }"); + // When the JSON parser throws parser exceptions, JsonFormat should turn + // that into InvalidProtocolBufferException. + try { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + JsonFormat.parser().merge(invalidJsonReader, builder); + assertWithMessage("Exception is expected.").fail(); + } catch (InvalidProtocolBufferException e) { + // Expected. + } + } + + // Test that an error is thrown if a nested JsonObject is parsed as a primitive field. + @Test + public void testJsonObjectForPrimitiveField() throws Exception { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + try { + mergeFromJson( + "{\n" + + " \"optionalString\": {\n" + + " \"invalidNestedString\": \"Hello world\"\n" + + " }\n" + + "}\n", + builder); + } catch (InvalidProtocolBufferException e) { + // Expected. + } + } + + @Test + public void testSortedMapKeys() throws Exception { + TestMap.Builder mapBuilder = TestMap.newBuilder(); + mapBuilder.putStringToInt32Map("\ud834\udd20", 3); // utf-8 F0 9D 84 A0 + mapBuilder.putStringToInt32Map("foo", 99); + mapBuilder.putStringToInt32Map("xxx", 123); + mapBuilder.putStringToInt32Map("\u20ac", 1); // utf-8 E2 82 AC + mapBuilder.putStringToInt32Map("abc", 20); + mapBuilder.putStringToInt32Map("19", 19); + mapBuilder.putStringToInt32Map("8", 8); + mapBuilder.putStringToInt32Map("\ufb00", 2); // utf-8 EF AC 80 + mapBuilder.putInt32ToInt32Map(3, 3); + mapBuilder.putInt32ToInt32Map(10, 10); + mapBuilder.putInt32ToInt32Map(5, 5); + mapBuilder.putInt32ToInt32Map(4, 4); + mapBuilder.putInt32ToInt32Map(1, 1); + mapBuilder.putInt32ToInt32Map(2, 2); + mapBuilder.putInt32ToInt32Map(-3, -3); + TestMap mapMessage = mapBuilder.build(); + assertThat(toSortedJsonString(mapMessage)) + .isEqualTo( + "{\n" + + " \"int32ToInt32Map\": {\n" + + " \"-3\": -3,\n" + + " \"1\": 1,\n" + + " \"2\": 2,\n" + + " \"3\": 3,\n" + + " \"4\": 4,\n" + + " \"5\": 5,\n" + + " \"10\": 10\n" + + " },\n" + + " \"stringToInt32Map\": {\n" + + " \"19\": 19,\n" + + " \"8\": 8,\n" + + " \"abc\": 20,\n" + + " \"foo\": 99,\n" + + " \"xxx\": 123,\n" + + " \"\u20ac\": 1,\n" + + " \"\ufb00\": 2,\n" + + " \"\ud834\udd20\": 3\n" + + " }\n" + + "}"); + + TestMap emptyMap = TestMap.getDefaultInstance(); + assertThat(toSortedJsonString(emptyMap)).isEqualTo("{\n}"); + } + + @Test + public void testPrintingEnumsAsIntsChainedAfterIncludingDefaultValueFields() throws Exception { + TestAllTypes message = TestAllTypes.newBuilder().setOptionalBool(false).build(); + + assertThat( + JsonFormat.printer() + .includingDefaultValueFields( + ImmutableSet.of( + message.getDescriptorForType().findFieldByName("optional_bool"))) + .printingEnumsAsInts() + .print(message)) + .isEqualTo("{\n" + " \"optionalBool\": false\n" + "}"); + } + + @Test + public void testPreservesFloatingPointNegative0() throws Exception { + TestAllTypes message = + TestAllTypes.newBuilder().setOptionalFloat(-0.0f).setOptionalDouble(-0.0).build(); + assertThat(JsonFormat.printer().print(message)) + .isEqualTo("{\n \"optionalFloat\": -0.0,\n \"optionalDouble\": -0.0\n}"); + } +} diff --git a/tools/env-vars-generator/protobuf/js/binary/arith_test.js b/tools/env-vars-generator/protobuf/js/binary/arith_test.js new file mode 100644 index 0000000..dd5791a --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/binary/arith_test.js @@ -0,0 +1,354 @@ +// 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. + +/** + * @fileoverview Test cases for Int64-manipulation functions. + * + * Test suite is written using Jasmine -- see http://jasmine.github.io/ + * + * @author cfallin@google.com (Chris Fallin) + */ + +goog.require('jspb.arith.Int64'); +goog.require('jspb.arith.UInt64'); + + +describe('binaryArithTest', function() { + /** + * Tests comparison operations. + */ + it('testCompare', function() { + var a = new jspb.arith.UInt64(1234, 5678); + var b = new jspb.arith.UInt64(1234, 5678); + expect(a.cmp(b)).toEqual(0); + expect(b.cmp(a)).toEqual(0); + b.lo -= 1; + expect(a.cmp(b)).toEqual(1); + expect(b.cmp(a)).toEqual(-1); + b.lo += 2; + expect(a.cmp(b)).toEqual(-1); + expect(b.cmp(a)).toEqual(1); + b.lo = a.lo; + b.hi = a.hi - 1; + expect(a.cmp(b)).toEqual(1); + expect(b.cmp(a)).toEqual(-1); + + expect(a.zero()).toEqual(false); + expect(a.msb()).toEqual(false); + expect(a.lsb()).toEqual(false); + a.hi = 0; + a.lo = 0; + expect(a.zero()).toEqual(true); + a.hi = 0x80000000; + expect(a.zero()).toEqual(false); + expect(a.msb()).toEqual(true); + a.lo = 0x00000001; + expect(a.lsb()).toEqual(true); + }); + + + /** + * Tests shifts. + */ + it('testShifts', function() { + var a = new jspb.arith.UInt64(1, 0); + expect(a.lo).toEqual(1); + expect(a.hi).toEqual(0); + var orig = a; + a = a.leftShift(); + expect(orig.lo).toEqual(1); // original unmodified. + expect(orig.hi).toEqual(0); + expect(a.lo).toEqual(2); + expect(a.hi).toEqual(0); + a = a.leftShift(); + expect(a.lo).toEqual(4); + expect(a.hi).toEqual(0); + for (var i = 0; i < 29; i++) { + a = a.leftShift(); + } + expect(a.lo).toEqual(0x80000000); + expect(a.hi).toEqual(0); + a = a.leftShift(); + expect(a.lo).toEqual(0); + expect(a.hi).toEqual(1); + a = a.leftShift(); + expect(a.lo).toEqual(0); + expect(a.hi).toEqual(2); + a = a.rightShift(); + a = a.rightShift(); + expect(a.lo).toEqual(0x80000000); + expect(a.hi).toEqual(0); + a = a.rightShift(); + expect(a.lo).toEqual(0x40000000); + expect(a.hi).toEqual(0); + }); + + + /** + * Tests additions. + */ + it('testAdd', function() { + var a = new jspb.arith.UInt64(/* lo = */ 0x89abcdef, + /* hi = */ 0x01234567); + var b = new jspb.arith.UInt64(/* lo = */ 0xff52ab91, + /* hi = */ 0x92fa2123); + // Addition with carry. + var c = a.add(b); + expect(a.lo).toEqual(0x89abcdef); // originals unmodified. + expect(a.hi).toEqual(0x01234567); + expect(b.lo).toEqual(0xff52ab91); + expect(b.hi).toEqual(0x92fa2123); + expect(c.lo).toEqual(0x88fe7980); + expect(c.hi).toEqual(0x941d668b); + + // Simple addition without carry. + a.lo = 2; + a.hi = 0; + b.lo = 3; + b.hi = 0; + c = a.add(b); + expect(c.lo).toEqual(5); + expect(c.hi).toEqual(0); + }); + + + /** + * Test subtractions. + */ + it('testSub', function() { + var kLength = 10; + var hiValues = [0x1682ef32, + 0x583902f7, + 0xb62f5955, + 0x6ea99bbf, + 0x25a39c20, + 0x0700a08b, + 0x00f7304d, + 0x91a5b5af, + 0x89077fd2, + 0xe09e347c]; + var loValues = [0xe1538b18, + 0xbeacd556, + 0x74100758, + 0x96e3cb26, + 0x56c37c3f, + 0xe00b3f7d, + 0x859f25d7, + 0xc2ee614a, + 0xe1d21cd7, + 0x30aae6a4]; + for (var i = 0; i < kLength; i++) { + for (var j = 0; j < kLength; j++) { + var a = new jspb.arith.UInt64(loValues[i], hiValues[j]); + var b = new jspb.arith.UInt64(loValues[j], hiValues[i]); + var c = a.add(b).sub(b); + expect(c.hi).toEqual(a.hi); + expect(c.lo).toEqual(a.lo); + } + } + }); + + + /** + * Tests 32-by-32 multiplication. + */ + it('testMul32x32', function() { + var testData = [ + // a b low(a*b) high(a*b) + [0xc0abe2f8, 0x1607898a, 0x5de711b0, 0x109471b8], + [0x915eb3cb, 0x4fb66d0e, 0xbd0d441a, 0x2d43d0bc], + [0xfe4efe70, 0x80b48c37, 0xbcddea10, 0x7fdada0c], + [0xe222fd4a, 0xe43d524a, 0xd5e0eb64, 0xc99d549c], + [0xd171f469, 0xb94ebd01, 0x4be17969, 0x979bc4fa], + [0x829cc1df, 0xe2598b38, 0xf4157dc8, 0x737c12ad], + [0xf10c3767, 0x8382881e, 0x942b3612, 0x7bd428b8], + [0xb0f6dd24, 0x232597e1, 0x079c98a4, 0x184bbce7], + [0xfcdb05a7, 0x902f55bc, 0x636199a4, 0x8e69f412], + [0x0dd0bfa9, 0x916e27b1, 0x6e2542d9, 0x07d92e65] + ]; + + for (var i = 0; i < testData.length; i++) { + var a = testData[i][0] >>> 0; + var b = testData[i][1] >>> 0; + var cLow = testData[i][2] >>> 0; + var cHigh = testData[i][3] >>> 0; + var c = jspb.arith.UInt64.mul32x32(a, b); + expect(c.lo).toEqual(cLow); + expect(c.hi).toEqual(cHigh); + } + }); + + + /** + * Tests 64-by-32 multiplication. + */ + it('testMul', function() { + // 64x32 bits produces 96 bits of product. The multiplication function under + // test truncates the top 32 bits, so we compare against a 64-bit expected + // product. + var testData = [ + // low(a) high(a) low(a*b) high(a*b) + [0xec10955b, 0x360eb168, 0x4b7f3f5b, 0xbfcb7c59, 0x9517da5f], + [0x42b000fc, 0x9d101642, 0x6fa1ab72, 0x2584c438, 0x6a9e6d2b], + [0xf42d4fb4, 0xae366403, 0xa65a1000, 0x92434000, 0x1ff978df], + [0x17e2f56b, 0x25487693, 0xf13f98c7, 0x73794e2d, 0xa96b0c6a], + [0x492f241f, 0x76c0eb67, 0x7377ac44, 0xd4336c3c, 0xfc4b1ebe], + [0xd6b92321, 0xe184fa48, 0xd6e76904, 0x93141584, 0xcbf44da1], + [0x4bf007ea, 0x968c0a9e, 0xf5e4026a, 0x4fdb1ae4, 0x61b9fb7d], + [0x10a83be7, 0x2d685ba6, 0xc9e5fb7f, 0x2ad43499, 0x3742473d], + [0x2f261829, 0x1aca681a, 0x3d3494e3, 0x8213205b, 0x283719f8], + [0xe4f2ce21, 0x2e74b7bd, 0xd801b38b, 0xbc17feeb, 0xc6c44e0f] + ]; + + for (var i = 0; i < testData.length; i++) { + var a = new jspb.arith.UInt64(testData[i][0], testData[i][1]); + var prod = a.mul(testData[i][2]); + expect(prod.lo).toEqual(testData[i][3]); + expect(prod.hi).toEqual(testData[i][4]); + } + }); + + + /** + * Tests 64-div-by-32 division. + */ + it('testDiv', function() { + // Compute a/b, yielding quot = a/b and rem = a%b. + var testData = [ + // --- divisors in (0, 2^32-1) to test full divisor range + // low(a) high(a) b low(quot) high(quot) rem + [0x712443f1, 0xe85cefcc, 0xc1a7050b, 0x332c79ad, 0x00000001, 0x92ffa882], + [0x11912915, 0xb2699eb5, 0x30467cbe, 0xb21b4be4, 0x00000003, 0x283465dd], + [0x0d917982, 0x201f2a6e, 0x3f35bf03, 0x8217c8e4, 0x00000000, 0x153402d6], + [0xa072c108, 0x74020c96, 0xc60568fd, 0x95f9613e, 0x00000000, 0x3f4676c2], + [0xd845d5d8, 0xcdd235c4, 0x20426475, 0x6154e78b, 0x00000006, 0x202fb751], + [0xa4dbf71f, 0x9e90465e, 0xf08e022f, 0xa8be947f, 0x00000000, 0xbe43b5ce], + [0x3dbe627f, 0xa791f4b9, 0x28a5bd89, 0x1f5dfe93, 0x00000004, 0x02bf9ed4], + [0x5c1c53ee, 0xccf5102e, 0x198576e7, 0x07e3ae31, 0x00000008, 0x02ea8fb7], + [0xfef1e581, 0x04714067, 0xca6540c1, 0x059e73ec, 0x00000000, 0x31658095], + [0x1e2dd90c, 0x13dd6667, 0x8b2184c3, 0x248d1a42, 0x00000000, 0x4ca6d0c6], + // --- divisors in (0, 2^16-1) to test larger quotient high-words + // low(a) high(a) b low(quot) high(quot) rem + [0x86722b47, 0x2cd57c9a, 0x00003123, 0x2ae41b7a, 0x0000e995, 0x00000f99], + [0x1dd7884c, 0xf5e839bc, 0x00009eeb, 0x5c886242, 0x00018c21, 0x000099b6], + [0x5c53d625, 0x899fc7e5, 0x000087d7, 0xd625007a, 0x0001035c, 0x000019af], + [0x6932d932, 0x9d0a5488, 0x000051fb, 0x9d976143, 0x0001ea63, 0x00004981], + [0x4d18bb85, 0x0c92fb31, 0x00001d9f, 0x03265ab4, 0x00006cac, 0x000001b9], + [0xbe756768, 0xdea67ccb, 0x00008a03, 0x58add442, 0x00019cff, 0x000056a2], + [0xe2466f9a, 0x2521f114, 0x0000c350, 0xa0c0860d, 0x000030ab, 0x0000a48a], + [0xf00ddad1, 0xe2f5446a, 0x00002cfc, 0x762697a6, 0x00050b96, 0x00000b69], + [0xa879152a, 0x0a70e0a5, 0x00007cdf, 0xb44151b3, 0x00001567, 0x0000363d], + [0x7179a74c, 0x46083fff, 0x0000253c, 0x4d39ba6e, 0x0001e17f, 0x00000f84] + ]; + + for (var i = 0; i < testData.length; i++) { + var a = new jspb.arith.UInt64(testData[i][0], testData[i][1]); + var result = a.div(testData[i][2]); + var quotient = result[0]; + var remainder = result[1]; + expect(quotient.lo).toEqual(testData[i][3]); + expect(quotient.hi).toEqual(testData[i][4]); + expect(remainder.lo).toEqual(testData[i][5]); + } + }); + + + /** + * Tests .toString() and .fromString(). + */ + it('testStrings', function() { + var testData = [ + [0x5e84c935, 0xcae33d0e, '14619595947299359029'], + [0x62b3b8b8, 0x93480544, '10612738313170434232'], + [0x319bfb13, 0xc01c4172, '13843011313344445203'], + [0x5b8a65fb, 0xa5885b31, '11927883880638080507'], + [0x6bdb80f1, 0xb0d1b16b, '12741159895737008369'], + [0x4b82b442, 0x2e0d8c97, '3318463081876730946'], + [0x780d5208, 0x7d76752c, '9040542135845999112'], + [0x2e46800f, 0x0993778d, '690026616168284175'], + [0xf00a7e32, 0xcd8e3931, '14811839111111540274'], + [0x1baeccd6, 0x923048c4, '10533999535534820566'], + [0x03669d29, 0xbff3ab72, '13831587386756603177'], + [0x2526073e, 0x01affc81, '121593346566522686'], + [0xc24244e0, 0xd7f40d0e, '15561076969511732448'], + [0xc56a341e, 0xa68b66a7, '12000798502816461854'], + [0x8738d64d, 0xbfe78604, '13828168534871037517'], + [0x5baff03b, 0xd7572aea, '15516918227177304123'], + [0x4a843d8a, 0x864e132b, '9677693725920476554'], + [0x25b4e94d, 0x22b54dc6, '2500990681505655117'], + [0x6bbe664b, 0x55a5cc0e, '6171563226690381387'], + [0xee916c81, 0xb00aabb3, '12685140089732426881'] + ]; + + for (var i = 0; i < testData.length; i++) { + var a = new jspb.arith.UInt64(testData[i][0], testData[i][1]); + var roundtrip = jspb.arith.UInt64.fromString(a.toString()); + expect(roundtrip.lo).toEqual(a.lo); + expect(roundtrip.hi).toEqual(a.hi); + expect(a.toString()).toEqual(testData[i][2]); + } + }); + + + /** + * Tests signed Int64s. These are built on UInt64s, so we only need to test + * the explicit overrides: .toString() and .fromString(). + */ + it('testSignedInt64', function() { + var testStrings = [ + '-7847499644178593666', + '3771946501229139523', + '2872856549054995060', + '-5780049594274350904', + '3383785956695105201', + '2973055184857072610', + '-3879428459215627206', + '4589812431064156631', + '8484075557333689940', + '1075325817098092407', + '-4346697501012292314', + '2488620459718316637', + '6112655187423520672', + '-3655278273928612104', + '3439154019435803196', + '1004112478843763757', + '-6587790776614368413', + '664320065099714586', + '4760412909973292912', + '-7911903989602274672' + ]; + + for (var i = 0; i < testStrings.length; i++) { + var roundtrip = + jspb.arith.Int64.fromString(testStrings[i]).toString(); + expect(roundtrip).toEqual(testStrings[i]); + } + }); +}); diff --git a/tools/env-vars-generator/protobuf/js/binary/encoder.js b/tools/env-vars-generator/protobuf/js/binary/encoder.js new file mode 100644 index 0000000..726481b --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/binary/encoder.js @@ -0,0 +1,510 @@ +// 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. + +/** + * @fileoverview BinaryEncode defines methods for encoding Javascript values + * into arrays of bytes compatible with the Protocol Buffer wire format. + * + * @author aappleby@google.com (Austin Appleby) + */ + +goog.provide('jspb.BinaryEncoder'); + +goog.require('goog.asserts'); +goog.require('jspb.BinaryConstants'); +goog.require('jspb.utils'); + + + +/** + * BinaryEncoder implements encoders for all the wire types specified in + * https://developers.google.com/protocol-buffers/docs/encoding. + * + * @constructor + * @struct + */ +jspb.BinaryEncoder = function() { + /** @private {!Array} */ + this.buffer_ = []; +}; + + +/** + * @return {number} + */ +jspb.BinaryEncoder.prototype.length = function() { + return this.buffer_.length; +}; + + +/** + * @return {!Array} + */ +jspb.BinaryEncoder.prototype.end = function() { + var buffer = this.buffer_; + this.buffer_ = []; + return buffer; +}; + + +/** + * Encodes a 64-bit integer in 32:32 split representation into its wire-format + * varint representation and stores it in the buffer. + * @param {number} lowBits The low 32 bits of the int. + * @param {number} highBits The high 32 bits of the int. + */ +jspb.BinaryEncoder.prototype.writeSplitVarint64 = function(lowBits, highBits) { + goog.asserts.assert(lowBits == Math.floor(lowBits)); + goog.asserts.assert(highBits == Math.floor(highBits)); + goog.asserts.assert((lowBits >= 0) && + (lowBits < jspb.BinaryConstants.TWO_TO_32)); + goog.asserts.assert((highBits >= 0) && + (highBits < jspb.BinaryConstants.TWO_TO_32)); + + // Break the binary representation into chunks of 7 bits, set the 8th bit + // in each chunk if it's not the final chunk, and append to the result. + while (highBits > 0 || lowBits > 127) { + this.buffer_.push((lowBits & 0x7f) | 0x80); + lowBits = ((lowBits >>> 7) | (highBits << 25)) >>> 0; + highBits = highBits >>> 7; + } + this.buffer_.push(lowBits); +}; + + +/** + * Encodes a 64-bit integer in 32:32 split representation into its wire-format + * fixed representation and stores it in the buffer. + * @param {number} lowBits The low 32 bits of the int. + * @param {number} highBits The high 32 bits of the int. + */ +jspb.BinaryEncoder.prototype.writeSplitFixed64 = function(lowBits, highBits) { + goog.asserts.assert(lowBits == Math.floor(lowBits)); + goog.asserts.assert(highBits == Math.floor(highBits)); + goog.asserts.assert((lowBits >= 0) && + (lowBits < jspb.BinaryConstants.TWO_TO_32)); + goog.asserts.assert((highBits >= 0) && + (highBits < jspb.BinaryConstants.TWO_TO_32)); + this.writeUint32(lowBits); + this.writeUint32(highBits); +}; + + +/** + * Encodes a 32-bit unsigned integer into its wire-format varint representation + * and stores it in the buffer. + * @param {number} value The integer to convert. + */ +jspb.BinaryEncoder.prototype.writeUnsignedVarint32 = function(value) { + goog.asserts.assert(value == Math.floor(value)); + goog.asserts.assert((value >= 0) && + (value < jspb.BinaryConstants.TWO_TO_32)); + + while (value > 127) { + this.buffer_.push((value & 0x7f) | 0x80); + value = value >>> 7; + } + + this.buffer_.push(value); +}; + + +/** + * Encodes a 32-bit signed integer into its wire-format varint representation + * and stores it in the buffer. + * @param {number} value The integer to convert. + */ +jspb.BinaryEncoder.prototype.writeSignedVarint32 = function(value) { + goog.asserts.assert(value == Math.floor(value)); + goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_31) && + (value < jspb.BinaryConstants.TWO_TO_31)); + + // Use the unsigned version if the value is not negative. + if (value >= 0) { + this.writeUnsignedVarint32(value); + return; + } + + // Write nine bytes with a _signed_ right shift so we preserve the sign bit. + for (var i = 0; i < 9; i++) { + this.buffer_.push((value & 0x7f) | 0x80); + value = value >> 7; + } + + // The above loop writes out 63 bits, so the last byte is always the sign bit + // which is always set for negative numbers. + this.buffer_.push(1); +}; + + +/** + * Encodes a 64-bit unsigned integer into its wire-format varint representation + * and stores it in the buffer. Integers that are not representable in 64 bits + * will be truncated. + * @param {number} value The integer to convert. + */ +jspb.BinaryEncoder.prototype.writeUnsignedVarint64 = function(value) { + goog.asserts.assert(value == Math.floor(value)); + goog.asserts.assert((value >= 0) && + (value < jspb.BinaryConstants.TWO_TO_64)); + jspb.utils.splitInt64(value); + this.writeSplitVarint64(jspb.utils.split64Low, + jspb.utils.split64High); +}; + + +/** + * Encodes a 64-bit signed integer into its wire-format varint representation + * and stores it in the buffer. Integers that are not representable in 64 bits + * will be truncated. + * @param {number} value The integer to convert. + */ +jspb.BinaryEncoder.prototype.writeSignedVarint64 = function(value) { + goog.asserts.assert(value == Math.floor(value)); + goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_63) && + (value < jspb.BinaryConstants.TWO_TO_63)); + jspb.utils.splitInt64(value); + this.writeSplitVarint64(jspb.utils.split64Low, + jspb.utils.split64High); +}; + + +/** + * Encodes a JavaScript integer into its wire-format, zigzag-encoded varint + * representation and stores it in the buffer. + * @param {number} value The integer to convert. + */ +jspb.BinaryEncoder.prototype.writeZigzagVarint32 = function(value) { + goog.asserts.assert(value == Math.floor(value)); + goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_31) && + (value < jspb.BinaryConstants.TWO_TO_31)); + this.writeUnsignedVarint32(((value << 1) ^ (value >> 31)) >>> 0); +}; + + +/** + * Encodes a JavaScript integer into its wire-format, zigzag-encoded varint + * representation and stores it in the buffer. Integers not representable in 64 + * bits will be truncated. + * @param {number} value The integer to convert. + */ +jspb.BinaryEncoder.prototype.writeZigzagVarint64 = function(value) { + goog.asserts.assert(value == Math.floor(value)); + goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_63) && + (value < jspb.BinaryConstants.TWO_TO_63)); + jspb.utils.splitZigzag64(value); + this.writeSplitVarint64(jspb.utils.split64Low, + jspb.utils.split64High); +}; + + +/** + * Encodes a JavaScript decimal string into its wire-format, zigzag-encoded + * varint representation and stores it in the buffer. Integers not representable + * in 64 bits will be truncated. + * @param {string} value The integer to convert. + */ +jspb.BinaryEncoder.prototype.writeZigzagVarint64String = function(value) { + this.writeZigzagVarintHash64(jspb.utils.decimalStringToHash64(value)); +}; + + +/** + * Writes a 64-bit hash string (8 characters @ 8 bits of data each) to the + * buffer as a zigzag varint. + * @param {string} hash The hash to write. + */ +jspb.BinaryEncoder.prototype.writeZigzagVarintHash64 = function(hash) { + var self = this; + jspb.utils.splitHash64(hash); + jspb.utils.toZigzag64( + jspb.utils.split64Low, jspb.utils.split64High, function(lo, hi) { + self.writeSplitVarint64(lo >>> 0, hi >>> 0); + }); +}; + + +/** + * Writes an 8-bit unsigned integer to the buffer. Numbers outside the range + * [0,2^8) will be truncated. + * @param {number} value The value to write. + */ +jspb.BinaryEncoder.prototype.writeUint8 = function(value) { + goog.asserts.assert(value == Math.floor(value)); + goog.asserts.assert((value >= 0) && (value < 256)); + this.buffer_.push((value >>> 0) & 0xFF); +}; + + +/** + * Writes a 16-bit unsigned integer to the buffer. Numbers outside the + * range [0,2^16) will be truncated. + * @param {number} value The value to write. + */ +jspb.BinaryEncoder.prototype.writeUint16 = function(value) { + goog.asserts.assert(value == Math.floor(value)); + goog.asserts.assert((value >= 0) && (value < 65536)); + this.buffer_.push((value >>> 0) & 0xFF); + this.buffer_.push((value >>> 8) & 0xFF); +}; + + +/** + * Writes a 32-bit unsigned integer to the buffer. Numbers outside the + * range [0,2^32) will be truncated. + * @param {number} value The value to write. + */ +jspb.BinaryEncoder.prototype.writeUint32 = function(value) { + goog.asserts.assert(value == Math.floor(value)); + goog.asserts.assert((value >= 0) && + (value < jspb.BinaryConstants.TWO_TO_32)); + this.buffer_.push((value >>> 0) & 0xFF); + this.buffer_.push((value >>> 8) & 0xFF); + this.buffer_.push((value >>> 16) & 0xFF); + this.buffer_.push((value >>> 24) & 0xFF); +}; + + +/** + * Writes a 64-bit unsigned integer to the buffer. Numbers outside the + * range [0,2^64) will be truncated. + * @param {number} value The value to write. + */ +jspb.BinaryEncoder.prototype.writeUint64 = function(value) { + goog.asserts.assert(value == Math.floor(value)); + goog.asserts.assert((value >= 0) && + (value < jspb.BinaryConstants.TWO_TO_64)); + jspb.utils.splitUint64(value); + this.writeUint32(jspb.utils.split64Low); + this.writeUint32(jspb.utils.split64High); +}; + + +/** + * Writes an 8-bit integer to the buffer. Numbers outside the range + * [-2^7,2^7) will be truncated. + * @param {number} value The value to write. + */ +jspb.BinaryEncoder.prototype.writeInt8 = function(value) { + goog.asserts.assert(value == Math.floor(value)); + goog.asserts.assert((value >= -128) && (value < 128)); + this.buffer_.push((value >>> 0) & 0xFF); +}; + + +/** + * Writes a 16-bit integer to the buffer. Numbers outside the range + * [-2^15,2^15) will be truncated. + * @param {number} value The value to write. + */ +jspb.BinaryEncoder.prototype.writeInt16 = function(value) { + goog.asserts.assert(value == Math.floor(value)); + goog.asserts.assert((value >= -32768) && (value < 32768)); + this.buffer_.push((value >>> 0) & 0xFF); + this.buffer_.push((value >>> 8) & 0xFF); +}; + + +/** + * Writes a 32-bit integer to the buffer. Numbers outside the range + * [-2^31,2^31) will be truncated. + * @param {number} value The value to write. + */ +jspb.BinaryEncoder.prototype.writeInt32 = function(value) { + goog.asserts.assert(value == Math.floor(value)); + goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_31) && + (value < jspb.BinaryConstants.TWO_TO_31)); + this.buffer_.push((value >>> 0) & 0xFF); + this.buffer_.push((value >>> 8) & 0xFF); + this.buffer_.push((value >>> 16) & 0xFF); + this.buffer_.push((value >>> 24) & 0xFF); +}; + + +/** + * Writes a 64-bit integer to the buffer. Numbers outside the range + * [-2^63,2^63) will be truncated. + * @param {number} value The value to write. + */ +jspb.BinaryEncoder.prototype.writeInt64 = function(value) { + goog.asserts.assert(value == Math.floor(value)); + goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_63) && + (value < jspb.BinaryConstants.TWO_TO_63)); + jspb.utils.splitInt64(value); + this.writeSplitFixed64(jspb.utils.split64Low, jspb.utils.split64High); +}; + + +/** + * Writes a 64-bit integer decimal strings to the buffer. Numbers outside the + * range [-2^63,2^63) will be truncated. + * @param {string} value The value to write. + */ +jspb.BinaryEncoder.prototype.writeInt64String = function(value) { + goog.asserts.assert(value == Math.floor(value)); + goog.asserts.assert((+value >= -jspb.BinaryConstants.TWO_TO_63) && + (+value < jspb.BinaryConstants.TWO_TO_63)); + jspb.utils.splitHash64(jspb.utils.decimalStringToHash64(value)); + this.writeSplitFixed64(jspb.utils.split64Low, jspb.utils.split64High); +}; + + +/** + * Writes a single-precision floating point value to the buffer. Numbers + * requiring more than 32 bits of precision will be truncated. + * @param {number} value The value to write. + */ +jspb.BinaryEncoder.prototype.writeFloat = function(value) { + goog.asserts.assert( + value === Infinity || value === -Infinity || isNaN(value) || + ((value >= -jspb.BinaryConstants.FLOAT32_MAX) && + (value <= jspb.BinaryConstants.FLOAT32_MAX))); + jspb.utils.splitFloat32(value); + this.writeUint32(jspb.utils.split64Low); +}; + + +/** + * Writes a double-precision floating point value to the buffer. As this is + * the native format used by JavaScript, no precision will be lost. + * @param {number} value The value to write. + */ +jspb.BinaryEncoder.prototype.writeDouble = function(value) { + goog.asserts.assert( + value === Infinity || value === -Infinity || isNaN(value) || + ((value >= -jspb.BinaryConstants.FLOAT64_MAX) && + (value <= jspb.BinaryConstants.FLOAT64_MAX))); + jspb.utils.splitFloat64(value); + this.writeUint32(jspb.utils.split64Low); + this.writeUint32(jspb.utils.split64High); +}; + + +/** + * Writes a boolean value to the buffer as a varint. We allow numbers as input + * because the JSPB code generator uses 0/1 instead of true/false to save space + * in the string representation of the proto. + * @param {boolean|number} value The value to write. + */ +jspb.BinaryEncoder.prototype.writeBool = function(value) { + goog.asserts.assert(typeof value === 'boolean' || typeof value === 'number'); + this.buffer_.push(value ? 1 : 0); +}; + + +/** + * Writes an enum value to the buffer as a varint. + * @param {number} value The value to write. + */ +jspb.BinaryEncoder.prototype.writeEnum = function(value) { + goog.asserts.assert(value == Math.floor(value)); + goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_31) && + (value < jspb.BinaryConstants.TWO_TO_31)); + this.writeSignedVarint32(value); +}; + + +/** + * Writes an arbitrary byte array to the buffer. + * @param {!Uint8Array} bytes The array of bytes to write. + */ +jspb.BinaryEncoder.prototype.writeBytes = function(bytes) { + this.buffer_.push.apply(this.buffer_, bytes); +}; + + +/** + * Writes a 64-bit hash string (8 characters @ 8 bits of data each) to the + * buffer as a varint. + * @param {string} hash The hash to write. + */ +jspb.BinaryEncoder.prototype.writeVarintHash64 = function(hash) { + jspb.utils.splitHash64(hash); + this.writeSplitVarint64(jspb.utils.split64Low, + jspb.utils.split64High); +}; + + +/** + * Writes a 64-bit hash string (8 characters @ 8 bits of data each) to the + * buffer as a fixed64. + * @param {string} hash The hash to write. + */ +jspb.BinaryEncoder.prototype.writeFixedHash64 = function(hash) { + jspb.utils.splitHash64(hash); + this.writeUint32(jspb.utils.split64Low); + this.writeUint32(jspb.utils.split64High); +}; + + +/** + * Writes a UTF16 Javascript string to the buffer encoded as UTF8. + * TODO(aappleby): Add support for surrogate pairs, reject unpaired surrogates. + * @param {string} value The string to write. + * @return {number} The number of bytes used to encode the string. + */ +jspb.BinaryEncoder.prototype.writeString = function(value) { + var oldLength = this.buffer_.length; + + for (var i = 0; i < value.length; i++) { + + var c = value.charCodeAt(i); + + if (c < 128) { + this.buffer_.push(c); + } else if (c < 2048) { + this.buffer_.push((c >> 6) | 192); + this.buffer_.push((c & 63) | 128); + } else if (c < 65536) { + // Look for surrogates + if (c >= 0xD800 && c <= 0xDBFF && i + 1 < value.length) { + var second = value.charCodeAt(i + 1); + if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate + // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + c = (c - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + + this.buffer_.push((c >> 18) | 240); + this.buffer_.push(((c >> 12) & 63 ) | 128); + this.buffer_.push(((c >> 6) & 63) | 128); + this.buffer_.push((c & 63) | 128); + i++; + } + } + else { + this.buffer_.push((c >> 12) | 224); + this.buffer_.push(((c >> 6) & 63) | 128); + this.buffer_.push((c & 63) | 128); + } + } + } + + var length = this.buffer_.length - oldLength; + return length; +}; diff --git a/tools/env-vars-generator/protobuf/js/binary/proto_test.js b/tools/env-vars-generator/protobuf/js/binary/proto_test.js new file mode 100644 index 0000000..aee327a --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/binary/proto_test.js @@ -0,0 +1,665 @@ +// 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. + +// Test suite is written using Jasmine -- see http://jasmine.github.io/ + +goog.require('goog.crypt.base64'); +goog.require('goog.testing.asserts'); +goog.require('jspb.BinaryWriter'); +goog.require('jspb.Message'); + +// CommonJS-LoadFromFile: ../testbinary_pb proto.jspb.test +goog.require('proto.jspb.test.ExtendsWithMessage'); +goog.require('proto.jspb.test.ForeignEnum'); +goog.require('proto.jspb.test.ForeignMessage'); +goog.require('proto.jspb.test.TestAllTypes'); +goog.require('proto.jspb.test.TestExtendable'); +goog.require('proto.jspb.test.extendOptionalBool'); +goog.require('proto.jspb.test.extendOptionalBytes'); +goog.require('proto.jspb.test.extendOptionalDouble'); +goog.require('proto.jspb.test.extendOptionalFixed32'); +goog.require('proto.jspb.test.extendOptionalFixed64'); +goog.require('proto.jspb.test.extendOptionalFloat'); +goog.require('proto.jspb.test.extendOptionalForeignEnum'); +goog.require('proto.jspb.test.extendOptionalInt32'); +goog.require('proto.jspb.test.extendOptionalInt64'); +goog.require('proto.jspb.test.extendOptionalSfixed32'); +goog.require('proto.jspb.test.extendOptionalSfixed64'); +goog.require('proto.jspb.test.extendOptionalSint32'); +goog.require('proto.jspb.test.extendOptionalSint64'); +goog.require('proto.jspb.test.extendOptionalString'); +goog.require('proto.jspb.test.extendOptionalUint32'); +goog.require('proto.jspb.test.extendOptionalUint64'); +goog.require('proto.jspb.test.extendPackedRepeatedBoolList'); +goog.require('proto.jspb.test.extendPackedRepeatedDoubleList'); +goog.require('proto.jspb.test.extendPackedRepeatedFixed32List'); +goog.require('proto.jspb.test.extendPackedRepeatedFixed64List'); +goog.require('proto.jspb.test.extendPackedRepeatedFloatList'); +goog.require('proto.jspb.test.extendPackedRepeatedForeignEnumList'); +goog.require('proto.jspb.test.extendPackedRepeatedInt32List'); +goog.require('proto.jspb.test.extendPackedRepeatedInt64List'); +goog.require('proto.jspb.test.extendPackedRepeatedSfixed32List'); +goog.require('proto.jspb.test.extendPackedRepeatedSfixed64List'); +goog.require('proto.jspb.test.extendPackedRepeatedSint32List'); +goog.require('proto.jspb.test.extendPackedRepeatedSint64List'); +goog.require('proto.jspb.test.extendPackedRepeatedUint32List'); +goog.require('proto.jspb.test.extendPackedRepeatedUint64List'); +goog.require('proto.jspb.test.extendRepeatedBoolList'); +goog.require('proto.jspb.test.extendRepeatedBytesList'); +goog.require('proto.jspb.test.extendRepeatedDoubleList'); +goog.require('proto.jspb.test.extendRepeatedFixed32List'); +goog.require('proto.jspb.test.extendRepeatedFixed64List'); +goog.require('proto.jspb.test.extendRepeatedFloatList'); +goog.require('proto.jspb.test.extendRepeatedForeignEnumList'); +goog.require('proto.jspb.test.extendRepeatedInt32List'); +goog.require('proto.jspb.test.extendRepeatedInt64List'); +goog.require('proto.jspb.test.extendRepeatedSfixed32List'); +goog.require('proto.jspb.test.extendRepeatedSfixed64List'); +goog.require('proto.jspb.test.extendRepeatedSint32List'); +goog.require('proto.jspb.test.extendRepeatedSint64List'); +goog.require('proto.jspb.test.extendRepeatedStringList'); +goog.require('proto.jspb.test.extendRepeatedUint32List'); +goog.require('proto.jspb.test.extendRepeatedUint64List'); + +// CommonJS-LoadFromFile: ../node_modules/google-protobuf/google/protobuf/any_pb proto.google.protobuf +goog.require('proto.google.protobuf.Any'); + + +var suite = {}; + +var BYTES = new Uint8Array([1, 2, 8, 9]); + +var BYTES_B64 = goog.crypt.base64.encodeByteArray(BYTES); + + +/** + * Helper: fill all fields on a TestAllTypes message. + * @param {proto.jspb.test.TestAllTypes} msg + */ +function fillAllFields(msg) { + msg.setOptionalInt32(-42); + // can be exactly represented by JS number (64-bit double, i.e., 52-bit + // mantissa). + msg.setOptionalInt64(-0x7fffffff00000000); + msg.setOptionalUint32(0x80000000); + msg.setOptionalUint64(0xf000000000000000); + msg.setOptionalSint32(-100); + msg.setOptionalSint64(-0x8000000000000000); + msg.setOptionalFixed32(1234); + msg.setOptionalFixed64(0x1234567800000000); + msg.setOptionalSfixed32(-1234); + msg.setOptionalSfixed64(-0x1234567800000000); + msg.setOptionalFloat(1.5); + msg.setOptionalDouble(-1.5); + msg.setOptionalBool(true); + msg.setOptionalString('hello world'); + msg.setOptionalBytes(BYTES); + msg.setOptionalGroup(new proto.jspb.test.TestAllTypes.OptionalGroup()); + msg.getOptionalGroup().setA(100); + var submsg = new proto.jspb.test.ForeignMessage(); + submsg.setC(16); + msg.setOptionalForeignMessage(submsg); + msg.setOptionalForeignEnum(proto.jspb.test.ForeignEnum.FOREIGN_FOO); + msg.setOneofString('oneof'); + + + msg.setRepeatedInt32List([-42]); + msg.setRepeatedInt64List([-0x7fffffff00000000]); + msg.setRepeatedUint32List([0x80000000]); + msg.setRepeatedUint64List([0xf000000000000000]); + msg.setRepeatedSint32List([-100]); + msg.setRepeatedSint64List([-0x8000000000000000]); + msg.setRepeatedFixed32List([1234]); + msg.setRepeatedFixed64List([0x1234567800000000]); + msg.setRepeatedSfixed32List([-1234]); + msg.setRepeatedSfixed64List([-0x1234567800000000]); + msg.setRepeatedFloatList([1.5]); + msg.setRepeatedDoubleList([-1.5]); + msg.setRepeatedBoolList([true]); + msg.setRepeatedStringList(['hello world']); + msg.setRepeatedBytesList([BYTES, BYTES]); + msg.setRepeatedGroupList([new proto.jspb.test.TestAllTypes.RepeatedGroup()]); + msg.getRepeatedGroupList()[0].setA(100); + submsg = new proto.jspb.test.ForeignMessage(); + submsg.setC(1000); + msg.setRepeatedForeignMessageList([submsg]); + msg.setRepeatedForeignEnumList([proto.jspb.test.ForeignEnum.FOREIGN_FOO]); + + msg.setPackedRepeatedInt32List([-42]); + msg.setPackedRepeatedInt64List([-0x7fffffff00000000]); + msg.setPackedRepeatedUint32List([0x80000000]); + msg.setPackedRepeatedUint64List([0xf000000000000000]); + msg.setPackedRepeatedSint32List([-100]); + msg.setPackedRepeatedSint64List([-0x8000000000000000]); + msg.setPackedRepeatedFixed32List([1234]); + msg.setPackedRepeatedFixed64List([0x1234567800000000]); + msg.setPackedRepeatedSfixed32List([-1234]); + msg.setPackedRepeatedSfixed64List([-0x1234567800000000]); + msg.setPackedRepeatedFloatList([1.5]); + msg.setPackedRepeatedDoubleList([-1.5]); + msg.setPackedRepeatedBoolList([true]); + +} + + +/** + * Helper: compare a bytes field to an expected value + * @param {Uint8Array|string} arr + * @param {Uint8Array} expected + * @return {boolean} + */ +function bytesCompare(arr, expected) { + if (typeof arr === 'string') { + arr = goog.crypt.base64.decodeStringToUint8Array(arr); + } + if (arr.length != expected.length) { + return false; + } + for (var i = 0; i < arr.length; i++) { + if (arr[i] != expected[i]) { + return false; + } + } + return true; +} + + +/** + * Helper: verify contents of given TestAllTypes message as set by + * fillAllFields(). + * @param {proto.jspb.test.TestAllTypes} original + * @param {proto.jspb.test.TestAllTypes} copy + */ +function checkAllFields(original, copy) { + assertEquals(copy.getOptionalInt32(), -42); + assertEquals(copy.getOptionalInt64(), -0x7fffffff00000000); + assertEquals(copy.getOptionalUint32(), 0x80000000); + assertEquals(copy.getOptionalUint64(), 0xf000000000000000); + assertEquals(copy.getOptionalSint32(), -100); + assertEquals(copy.getOptionalSint64(), -0x8000000000000000); + assertEquals(copy.getOptionalFixed32(), 1234); + assertEquals(copy.getOptionalFixed64(), 0x1234567800000000); + assertEquals(copy.getOptionalSfixed32(), -1234); + assertEquals(copy.getOptionalSfixed64(), -0x1234567800000000); + assertEquals(copy.getOptionalFloat(), 1.5); + assertEquals(copy.getOptionalDouble(), -1.5); + assertEquals(copy.getOptionalBool(), true); + assertEquals(copy.getOptionalString(), 'hello world'); + assertEquals(true, bytesCompare(copy.getOptionalBytes(), BYTES)); + assertEquals(true, bytesCompare(copy.getOptionalBytes_asU8(), BYTES)); + assertEquals( + copy.getOptionalBytes_asB64(), goog.crypt.base64.encodeByteArray(BYTES)); + + assertEquals(copy.getOptionalGroup().getA(), 100); + assertEquals(copy.getOptionalForeignMessage().getC(), 16); + assertEquals(copy.getOptionalForeignEnum(), + proto.jspb.test.ForeignEnum.FOREIGN_FOO); + + + assertEquals(copy.getOneofString(), 'oneof'); + assertEquals(copy.getOneofFieldCase(), + proto.jspb.test.TestAllTypes.OneofFieldCase.ONEOF_STRING); + + assertElementsEquals(copy.getRepeatedInt32List(), [-42]); + assertElementsEquals(copy.getRepeatedInt64List(), [-0x7fffffff00000000]); + assertElementsEquals(copy.getRepeatedUint32List(), [0x80000000]); + assertElementsEquals(copy.getRepeatedUint64List(), [0xf000000000000000]); + assertElementsEquals(copy.getRepeatedSint32List(), [-100]); + assertElementsEquals(copy.getRepeatedSint64List(), [-0x8000000000000000]); + assertElementsEquals(copy.getRepeatedFixed32List(), [1234]); + assertElementsEquals(copy.getRepeatedFixed64List(), [0x1234567800000000]); + assertElementsEquals(copy.getRepeatedSfixed32List(), [-1234]); + assertElementsEquals(copy.getRepeatedSfixed64List(), [-0x1234567800000000]); + assertElementsEquals(copy.getRepeatedFloatList(), [1.5]); + assertElementsEquals(copy.getRepeatedDoubleList(), [-1.5]); + assertElementsEquals(copy.getRepeatedBoolList(), [true]); + assertElementsEquals(copy.getRepeatedStringList(), ['hello world']); + assertEquals(copy.getRepeatedBytesList().length, 2); + assertEquals(true, bytesCompare(copy.getRepeatedBytesList_asU8()[0], BYTES)); + assertEquals(true, bytesCompare(copy.getRepeatedBytesList()[0], BYTES)); + assertEquals(true, bytesCompare(copy.getRepeatedBytesList_asU8()[1], BYTES)); + assertEquals(copy.getRepeatedBytesList_asB64()[0], BYTES_B64); + assertEquals(copy.getRepeatedBytesList_asB64()[1], BYTES_B64); + assertEquals(copy.getRepeatedGroupList().length, 1); + assertEquals(copy.getRepeatedGroupList()[0].getA(), 100); + assertEquals(copy.getRepeatedForeignMessageList().length, 1); + assertEquals(copy.getRepeatedForeignMessageList()[0].getC(), 1000); + assertElementsEquals(copy.getRepeatedForeignEnumList(), + [proto.jspb.test.ForeignEnum.FOREIGN_FOO]); + + assertElementsEquals(copy.getPackedRepeatedInt32List(), [-42]); + assertElementsEquals(copy.getPackedRepeatedInt64List(), + [-0x7fffffff00000000]); + assertElementsEquals(copy.getPackedRepeatedUint32List(), [0x80000000]); + assertElementsEquals(copy.getPackedRepeatedUint64List(), + [0xf000000000000000]); + assertElementsEquals(copy.getPackedRepeatedSint32List(), [-100]); + assertElementsEquals(copy.getPackedRepeatedSint64List(), + [-0x8000000000000000]); + assertElementsEquals(copy.getPackedRepeatedFixed32List(), [1234]); + assertElementsEquals(copy.getPackedRepeatedFixed64List(), + [0x1234567800000000]); + assertElementsEquals(copy.getPackedRepeatedSfixed32List(), [-1234]); + assertElementsEquals(copy.getPackedRepeatedSfixed64List(), + [-0x1234567800000000]); + assertElementsEquals(copy.getPackedRepeatedFloatList(), [1.5]); + assertElementsEquals(copy.getPackedRepeatedDoubleList(), [-1.5]); + + + // Check last so we get more granular errors first. + assertTrue(jspb.Message.equals(original, copy)); +} + + +/** + * Helper: verify that all expected extensions are present. + * @param {!proto.jspb.test.TestExtendable} msg + */ +function checkExtensions(msg) { + assertEquals(0, msg.getExtension(proto.jspb.test.extendOptionalInt32)); + assertEquals(-0x7fffffff00000000, + msg.getExtension(proto.jspb.test.extendOptionalInt64)); + assertEquals(0x80000000, + msg.getExtension(proto.jspb.test.extendOptionalUint32)); + assertEquals(0xf000000000000000, + msg.getExtension(proto.jspb.test.extendOptionalUint64)); + assertEquals(-100, + msg.getExtension(proto.jspb.test.extendOptionalSint32)); + assertEquals(-0x8000000000000000, + msg.getExtension(proto.jspb.test.extendOptionalSint64)); + assertEquals(1234, + msg.getExtension(proto.jspb.test.extendOptionalFixed32)); + assertEquals(0x1234567800000000, + msg.getExtension(proto.jspb.test.extendOptionalFixed64)); + assertEquals(-1234, + msg.getExtension(proto.jspb.test.extendOptionalSfixed32)); + assertEquals(-0x1234567800000000, + msg.getExtension(proto.jspb.test.extendOptionalSfixed64)); + assertEquals(1.5, + msg.getExtension(proto.jspb.test.extendOptionalFloat)); + assertEquals(-1.5, + msg.getExtension(proto.jspb.test.extendOptionalDouble)); + assertEquals(true, + msg.getExtension(proto.jspb.test.extendOptionalBool)); + assertEquals('hello world', + msg.getExtension(proto.jspb.test.extendOptionalString)); + assertEquals( + true, bytesCompare( + msg.getExtension(proto.jspb.test.extendOptionalBytes), BYTES)); + assertEquals(16, + msg.getExtension( + proto.jspb.test.ExtendsWithMessage.optionalExtension).getFoo()); + + + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedInt32List), + [-42]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedInt64List), + [-0x7fffffff00000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedUint32List), + [0x80000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedUint64List), + [0xf000000000000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedSint32List), + [-100]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedSint64List), + [-0x8000000000000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedFixed32List), + [1234]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedFixed64List), + [0x1234567800000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedSfixed32List), + [-1234]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedSfixed64List), + [-0x1234567800000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedFloatList), + [1.5]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedDoubleList), + [-1.5]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedBoolList), + [true]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedStringList), + ['hello world']); + assertEquals( + true, + bytesCompare( + msg.getExtension(proto.jspb.test.extendRepeatedBytesList)[0], BYTES)); + assertEquals(1000, + msg.getExtension( + proto.jspb.test.ExtendsWithMessage.repeatedExtensionList)[0] + .getFoo()); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedForeignEnumList), + [proto.jspb.test.ForeignEnum.FOREIGN_FOO]); + + + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedInt32List), + [-42]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedInt64List), + [-0x7fffffff00000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedUint32List), + [0x80000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedUint64List), + [0xf000000000000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedSint32List), + [-100]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedSint64List), + [-0x8000000000000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedFixed32List), + [1234]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedFixed64List), + [0x1234567800000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedSfixed32List), + [-1234]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedSfixed64List), + [-0x1234567800000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedFloatList), + [1.5]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedDoubleList), + [-1.5]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedBoolList), + [true]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedForeignEnumList), + [proto.jspb.test.ForeignEnum.FOREIGN_FOO]); + +} + + +describe('protoBinaryTest', function() { + /** + * Tests a basic serialization-deserializaton round-trip with all supported + * field types (on the TestAllTypes message type). + */ + it('testRoundTrip', function() { + var msg = new proto.jspb.test.TestAllTypes(); + fillAllFields(msg); + var encoded = msg.serializeBinary(); + var decoded = proto.jspb.test.TestAllTypes.deserializeBinary(encoded); + checkAllFields(msg, decoded); + }); + + /** + * Test that base64 string and Uint8Array are interchangeable in bytes fields. + */ + it('testBytesFieldsGettersInterop', function() { + var msg = new proto.jspb.test.TestAllTypes(); + // Set from a base64 string and check all the getters work. + msg.setOptionalBytes(BYTES_B64); + assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES)); + assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES)); + assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); + + // Test binary serialize round trip doesn't break it. + msg = proto.jspb.test.TestAllTypes.deserializeBinary(msg.serializeBinary()); + assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES)); + assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES)); + assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); + + msg = new proto.jspb.test.TestAllTypes(); + // Set from a Uint8Array and check all the getters work. + msg.setOptionalBytes(BYTES); + assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES)); + assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES)); + assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); + + }); + + /** + * Test that bytes setters will receive result of any of the getters. + */ + it('testBytesFieldsSettersInterop', function() { + var msg = new proto.jspb.test.TestAllTypes(); + msg.setOptionalBytes(BYTES); + assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); + + msg.setOptionalBytes(msg.getOptionalBytes()); + assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); + msg.setOptionalBytes(msg.getOptionalBytes_asB64()); + assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); + msg.setOptionalBytes(msg.getOptionalBytes_asU8()); + assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); + }); + + /** + * Test that bytes setters will receive result of any of the getters. + */ + it('testRepeatedBytesGetters', function() { + var msg = new proto.jspb.test.TestAllTypes(); + + function assertGetters() { + assertTrue(typeof msg.getRepeatedBytesList_asB64()[0] === 'string'); + assertTrue(typeof msg.getRepeatedBytesList_asB64()[1] === 'string'); + assertTrue(msg.getRepeatedBytesList_asU8()[0] instanceof Uint8Array); + assertTrue(msg.getRepeatedBytesList_asU8()[1] instanceof Uint8Array); + + assertTrue(bytesCompare(msg.getRepeatedBytesList()[0], BYTES)); + assertTrue(bytesCompare(msg.getRepeatedBytesList()[1], BYTES)); + assertTrue(bytesCompare(msg.getRepeatedBytesList_asB64()[0], BYTES)); + assertTrue(bytesCompare(msg.getRepeatedBytesList_asB64()[1], BYTES)); + assertTrue(bytesCompare(msg.getRepeatedBytesList_asU8()[0], BYTES)); + assertTrue(bytesCompare(msg.getRepeatedBytesList_asU8()[1], BYTES)); + } + + msg.setRepeatedBytesList([BYTES, BYTES]); + assertGetters(); + + msg.setRepeatedBytesList([BYTES_B64, BYTES_B64]); + assertGetters(); + + msg.setRepeatedBytesList([]); + assertEquals(0, msg.getRepeatedBytesList().length); + assertEquals(0, msg.getRepeatedBytesList_asB64().length); + assertEquals(0, msg.getRepeatedBytesList_asU8().length); + }); + + /** + * Helper: fill all extension values. + * @param {proto.jspb.test.TestExtendable} msg + */ + function fillExtensions(msg) { + msg.setExtension(proto.jspb.test.extendOptionalInt32, 0); + msg.setExtension( + proto.jspb.test.extendOptionalInt64, -0x7fffffff00000000); + msg.setExtension( + proto.jspb.test.extendOptionalUint32, 0x80000000); + msg.setExtension( + proto.jspb.test.extendOptionalUint64, 0xf000000000000000); + msg.setExtension( + proto.jspb.test.extendOptionalSint32, -100); + msg.setExtension( + proto.jspb.test.extendOptionalSint64, -0x8000000000000000); + msg.setExtension( + proto.jspb.test.extendOptionalFixed32, 1234); + msg.setExtension( + proto.jspb.test.extendOptionalFixed64, 0x1234567800000000); + msg.setExtension( + proto.jspb.test.extendOptionalSfixed32, -1234); + msg.setExtension( + proto.jspb.test.extendOptionalSfixed64, -0x1234567800000000); + msg.setExtension( + proto.jspb.test.extendOptionalFloat, 1.5); + msg.setExtension( + proto.jspb.test.extendOptionalDouble, -1.5); + msg.setExtension( + proto.jspb.test.extendOptionalBool, true); + msg.setExtension( + proto.jspb.test.extendOptionalString, 'hello world'); + msg.setExtension(proto.jspb.test.extendOptionalBytes, BYTES); + var submsg = new proto.jspb.test.ExtendsWithMessage(); + submsg.setFoo(16); + msg.setExtension( + proto.jspb.test.ExtendsWithMessage.optionalExtension, submsg); + msg.setExtension( + proto.jspb.test.extendOptionalForeignEnum, + proto.jspb.test.ForeignEnum.FOREIGN_FOO); + + + msg.setExtension( + proto.jspb.test.extendRepeatedInt32List, [-42]); + msg.setExtension( + proto.jspb.test.extendRepeatedInt64List, [-0x7fffffff00000000]); + msg.setExtension( + proto.jspb.test.extendRepeatedUint32List, [0x80000000]); + msg.setExtension( + proto.jspb.test.extendRepeatedUint64List, [0xf000000000000000]); + msg.setExtension( + proto.jspb.test.extendRepeatedSint32List, [-100]); + msg.setExtension( + proto.jspb.test.extendRepeatedSint64List, [-0x8000000000000000]); + msg.setExtension( + proto.jspb.test.extendRepeatedFixed32List, [1234]); + msg.setExtension( + proto.jspb.test.extendRepeatedFixed64List, [0x1234567800000000]); + msg.setExtension( + proto.jspb.test.extendRepeatedSfixed32List, [-1234]); + msg.setExtension( + proto.jspb.test.extendRepeatedSfixed64List, [-0x1234567800000000]); + msg.setExtension( + proto.jspb.test.extendRepeatedFloatList, [1.5]); + msg.setExtension( + proto.jspb.test.extendRepeatedDoubleList, [-1.5]); + msg.setExtension( + proto.jspb.test.extendRepeatedBoolList, [true]); + msg.setExtension( + proto.jspb.test.extendRepeatedStringList, ['hello world']); + msg.setExtension(proto.jspb.test.extendRepeatedBytesList, [BYTES]); + submsg = new proto.jspb.test.ExtendsWithMessage(); + submsg.setFoo(1000); + msg.setExtension( + proto.jspb.test.ExtendsWithMessage.repeatedExtensionList, [submsg]); + msg.setExtension(proto.jspb.test.extendRepeatedForeignEnumList, + [proto.jspb.test.ForeignEnum.FOREIGN_FOO]); + + + msg.setExtension( + proto.jspb.test.extendPackedRepeatedInt32List, [-42]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedInt64List, [-0x7fffffff00000000]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedUint32List, [0x80000000]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedUint64List, [0xf000000000000000]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedSint32List, [-100]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedSint64List, [-0x8000000000000000]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedFixed32List, [1234]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedFixed64List, [0x1234567800000000]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedSfixed32List, [-1234]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedSfixed64List, + [-0x1234567800000000]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedFloatList, [1.5]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedDoubleList, [-1.5]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedBoolList, [true]); + msg.setExtension(proto.jspb.test.extendPackedRepeatedForeignEnumList, + [proto.jspb.test.ForeignEnum.FOREIGN_FOO]); + + } + + + /** + * Tests extension serialization and deserialization. + */ + it('testExtensions', function() { + var msg = new proto.jspb.test.TestExtendable(); + fillExtensions(msg); + var encoded = msg.serializeBinary(); + var decoded = proto.jspb.test.TestExtendable.deserializeBinary(encoded); + checkExtensions(decoded); + }); + + /** + * Tests that unknown extensions don't cause deserialization failure. + */ + it('testUnknownExtension', function() { + var msg = new proto.jspb.test.TestExtendable(); + fillExtensions(msg); + var writer = new jspb.BinaryWriter(); + writer.writeBool((1 << 29) - 1, true); + proto.jspb.test.TestExtendable.serializeBinaryToWriter(msg, writer); + var encoded = writer.getResultBuffer(); + var decoded = proto.jspb.test.TestExtendable.deserializeBinary(encoded); + checkExtensions(decoded); + }); + + it('testAnyWellKnownType', function() { + var any = new proto.google.protobuf.Any(); + var msg = new proto.jspb.test.TestAllTypes(); + + fillAllFields(msg); + + any.pack(msg.serializeBinary(), 'jspb.test.TestAllTypes'); + + assertEquals('type.googleapis.com/jspb.test.TestAllTypes', + any.getTypeUrl()); + + var msg2 = any.unpack( + proto.jspb.test.TestAllTypes.deserializeBinary, + 'jspb.test.TestAllTypes'); + + checkAllFields(msg, msg2); + + }); + +}); diff --git a/tools/env-vars-generator/protobuf/js/commonjs/export.js b/tools/env-vars-generator/protobuf/js/commonjs/export.js new file mode 100644 index 0000000..2025d9a --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/commonjs/export.js @@ -0,0 +1,31 @@ +/** + * @fileoverview Export symbols needed by generated code in CommonJS style. + * + * This effectively is our canonical list of what we publicly export from + * the google-protobuf.js file that we build at distribution time. + */ + +goog.provide('jspb.Export'); + +goog.require('goog.object'); +goog.require('jspb.BinaryReader'); +goog.require('jspb.BinaryWriter'); +goog.require('jspb.ExtensionFieldBinaryInfo'); +goog.require('jspb.ExtensionFieldInfo'); +goog.require('jspb.Message'); +goog.require('jspb.Map'); + +if ( typeof exports === 'object' ) { + exports.Map = jspb.Map; + exports.Message = jspb.Message; + exports.BinaryReader = jspb.BinaryReader; + exports.BinaryWriter = jspb.BinaryWriter; + exports.ExtensionFieldInfo = jspb.ExtensionFieldInfo; + exports.ExtensionFieldBinaryInfo = jspb.ExtensionFieldBinaryInfo; + + // These are used by generated code but should not be used directly by clients. + exports.exportSymbol = goog.exportSymbol; + exports.inherits = goog.inherits; + exports.object = {extend: goog.object.extend}; + exports.typeOf = goog.typeOf; +} \ No newline at end of file diff --git a/tools/env-vars-generator/protobuf/js/compatibility_tests/v3.0.0/commonjs/rewrite_tests_for_commonjs.js b/tools/env-vars-generator/protobuf/js/compatibility_tests/v3.0.0/commonjs/rewrite_tests_for_commonjs.js new file mode 100644 index 0000000..b6d90d2 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/compatibility_tests/v3.0.0/commonjs/rewrite_tests_for_commonjs.js @@ -0,0 +1,97 @@ +/** + * @fileoverview Utility to translate test files to CommonJS imports. + * + * This is a somewhat hacky tool designed to do one very specific thing. + * All of the test files in *_test.js are written with Closure-style + * imports (goog.require()). This works great for running the tests + * against Closure-style generated code, but we also want to run the + * tests against CommonJS-style generated code without having to fork + * the tests. + * + * Closure-style imports import each individual type by name. This is + * very different than CommonJS imports which are by file. So we put + * special comments in these tests like: + * + * // CommonJS-LoadFromFile: test_pb + * goog.require('proto.jspb.test.CloneExtension'); + * goog.require('proto.jspb.test.Complex'); + * goog.require('proto.jspb.test.DefaultValues'); + * + * This script parses that special comment and uses it to generate proper + * CommonJS require() statements so that the tests can run and pass using + * CommonJS imports. The script will change the above statements into: + * + * var test_pb = require('test_pb'); + * googleProtobuf.exportSymbol('proto.jspb.test.CloneExtension', test_pb.CloneExtension, global); + * googleProtobuf.exportSymbol('proto.jspb.test.Complex', test_pb.Complex, global); + * googleProtobuf.exportSymbol('proto.jspb.test.DefaultValues', test_pb.DefaultValues, global); + * + * (The "exportSymbol" function will define the given names in the global + * namespace, taking care not to overwrite any previous value for + * "proto.jspb.test"). + */ + +var lineReader = require('readline').createInterface({ + input: process.stdin, + output: process.stdout +}); + +function tryStripPrefix(str, prefix) { + if (str.lastIndexOf(prefix) !== 0) { + throw "String: " + str + " didn't start with: " + prefix; + } + return str.substr(prefix.length); +} + +function camelCase(str) { + var ret = ''; + var ucaseNext = false; + for (var i = 0; i < str.length; i++) { + if (str[i] == '-') { + ucaseNext = true; + } else if (ucaseNext) { + ret += str[i].toUpperCase(); + ucaseNext = false; + } else { + ret += str[i]; + } + } + return ret; +} + +var module = null; +var pkg = null; + +// Header: goes in every file at the top. +console.log("var global = Function('return this')();"); +console.log("var googleProtobuf = require('google-protobuf');"); +console.log("var testdeps = require('testdeps_commonjs');"); +console.log("global.goog = testdeps.goog;"); +console.log("global.jspb = testdeps.jspb;"); +console.log("var asserts = require('closure_asserts_commonjs');"); +console.log(""); +console.log("// Bring asserts into the global namespace."); +console.log("googleProtobuf.object.extend(global, asserts);"); + +lineReader.on('line', function(line) { + var isRequire = line.match(/goog\.require\('([^']*)'\)/); + var isLoadFromFile = line.match(/CommonJS-LoadFromFile: (\S*) (.*)/); + var isSetTestOnly = line.match(/goog.setTestOnly()/); + if (isRequire) { + if (module) { // Skip goog.require() lines before the first directive. + var fullSym = isRequire[1]; + var sym = tryStripPrefix(fullSym, pkg); + console.log("googleProtobuf.exportSymbol('" + fullSym + "', " + module + sym + ', global);'); + } + } else if (isLoadFromFile) { + var module_path = isLoadFromFile[1].split('/'); + module = camelCase(module_path[module_path.length - 1]); + pkg = isLoadFromFile[2]; + + if (module != "googleProtobuf") { // We unconditionally require this in the header. + console.log("var " + module + " = require('./" + isLoadFromFile[1] + "');"); + } + } else if (!isSetTestOnly) { // Remove goog.setTestOnly() lines. + console.log(line); + } +}); diff --git a/tools/env-vars-generator/protobuf/js/compatibility_tests/v3.0.0/commonjs/test7/test7.proto b/tools/env-vars-generator/protobuf/js/compatibility_tests/v3.0.0/commonjs/test7/test7.proto new file mode 100644 index 0000000..f5574a3 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/compatibility_tests/v3.0.0/commonjs/test7/test7.proto @@ -0,0 +1,42 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2016 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +option java_package = "com.google.apps.jspb.proto"; +option java_multiple_files = true; + +package jspb.test.framing; + +import "test6/test6.proto"; + +message FramingMessage { + jspb.test.importing.ImportedMessage imported_message = 1; +} diff --git a/tools/env-vars-generator/protobuf/js/compatibility_tests/v3.1.0/data.proto b/tools/env-vars-generator/protobuf/js/compatibility_tests/v3.1.0/data.proto new file mode 100644 index 0000000..74a8a99 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/compatibility_tests/v3.1.0/data.proto @@ -0,0 +1,51 @@ +// 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: mwr@google.com (Mark Rawling) + +syntax = "proto2"; + +option java_package = "com.google.apps.jspb.proto"; +option java_multiple_files = true; + +package jspb.test; + +// legacy data, must be nested +message data { + message NestedData { + required string str = 1; + } +} + +// new data, does not require nesting +message UnnestedData { + required string str = 1; +} + diff --git a/tools/env-vars-generator/protobuf/js/compatibility_tests/v3.1.0/message_test.js b/tools/env-vars-generator/protobuf/js/compatibility_tests/v3.1.0/message_test.js new file mode 100644 index 0000000..9830a02 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/compatibility_tests/v3.1.0/message_test.js @@ -0,0 +1,1060 @@ +// 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. + +// Test suite is written using Jasmine -- see http://jasmine.github.io/ + +goog.setTestOnly(); + +goog.require('goog.json'); +goog.require('goog.testing.asserts'); +goog.require('goog.userAgent'); + +// CommonJS-LoadFromFile: google-protobuf jspb +goog.require('jspb.Message'); + +// CommonJS-LoadFromFile: test5_pb proto.jspb.exttest.beta +goog.require('proto.jspb.exttest.beta.floatingStrField'); + +// CommonJS-LoadFromFile: test3_pb proto.jspb.exttest +goog.require('proto.jspb.exttest.floatingMsgField'); + +// CommonJS-LoadFromFile: test4_pb proto.jspb.exttest +goog.require('proto.jspb.exttest.floatingMsgFieldTwo'); + +// CommonJS-LoadFromFile: test_pb proto.jspb.test +goog.require('proto.jspb.test.CloneExtension'); +goog.require('proto.jspb.test.Complex'); +goog.require('proto.jspb.test.DefaultValues'); +goog.require('proto.jspb.test.Empty'); +goog.require('proto.jspb.test.EnumContainer'); +goog.require('proto.jspb.test.floatingMsgField'); +goog.require('proto.jspb.test.FloatingPointFields'); +goog.require('proto.jspb.test.floatingStrField'); +goog.require('proto.jspb.test.HasExtensions'); +goog.require('proto.jspb.test.IndirectExtension'); +goog.require('proto.jspb.test.IsExtension'); +goog.require('proto.jspb.test.OptionalFields'); +goog.require('proto.jspb.test.OuterEnum'); +goog.require('proto.jspb.test.OuterMessage.Complex'); +goog.require('proto.jspb.test.Simple1'); +goog.require('proto.jspb.test.Simple2'); +goog.require('proto.jspb.test.SpecialCases'); +goog.require('proto.jspb.test.TestClone'); +goog.require('proto.jspb.test.TestGroup'); +goog.require('proto.jspb.test.TestGroup1'); +goog.require('proto.jspb.test.TestMessageWithOneof'); +goog.require('proto.jspb.test.TestReservedNames'); +goog.require('proto.jspb.test.TestReservedNamesExtension'); + +// CommonJS-LoadFromFile: test2_pb proto.jspb.test +goog.require('proto.jspb.test.ExtensionMessage'); +goog.require('proto.jspb.test.TestExtensionsMessage'); +goog.require('proto.jspb.test.simple1'); + + + +describe('Message test suite', function() { + it('testEmptyProto', function() { + var empty1 = new proto.jspb.test.Empty([]); + var empty2 = new proto.jspb.test.Empty([]); + assertObjectEquals({}, empty1.toObject()); + assertObjectEquals('Message should not be corrupted:', empty2, empty1); + }); + + it('testTopLevelEnum', function() { + var response = new proto.jspb.test.EnumContainer([]); + response.setOuterEnum(proto.jspb.test.OuterEnum.FOO); + assertEquals(proto.jspb.test.OuterEnum.FOO, response.getOuterEnum()); + }); + + it('testByteStrings', function() { + var data = new proto.jspb.test.DefaultValues([]); + data.setBytesField('some_bytes'); + assertEquals('some_bytes', data.getBytesField()); + }); + + it('testComplexConversion', function() { + var data1 = ['a', , , [, 11], [[, 22], [, 33]], , ['s1', 's2'], , true]; + var data2 = ['a', , , [, 11], [[, 22], [, 33]], , ['s1', 's2'], , true]; + var foo = new proto.jspb.test.Complex(data1); + var bar = new proto.jspb.test.Complex(data2); + var result = foo.toObject(); + assertObjectEquals( + { + aString: 'a', + anOutOfOrderBool: true, + aNestedMessage: {anInt: 11}, + aRepeatedMessageList: [{anInt: 22}, {anInt: 33}], + aRepeatedStringList: ['s1', 's2'] + }, + result); + + // Now test with the jspb instances included. + result = foo.toObject(true /* opt_includeInstance */); + assertObjectEquals( + { + aString: 'a', + anOutOfOrderBool: true, + aNestedMessage: + {anInt: 11, $jspbMessageInstance: foo.getANestedMessage()}, + aRepeatedMessageList: [ + {anInt: 22, $jspbMessageInstance: foo.getARepeatedMessageList()[0]}, + {anInt: 33, $jspbMessageInstance: foo.getARepeatedMessageList()[1]} + ], + aRepeatedStringList: ['s1', 's2'], + $jspbMessageInstance: foo + }, + result); + }); + + it('testMissingFields', function() { + var foo = new proto.jspb.test.Complex([ + undefined, undefined, undefined, [], undefined, undefined, undefined, + undefined + ]); + var bar = new proto.jspb.test.Complex([ + undefined, undefined, undefined, [], undefined, undefined, undefined, + undefined + ]); + var result = foo.toObject(); + assertObjectEquals( + { + aString: undefined, + anOutOfOrderBool: undefined, + aNestedMessage: {anInt: undefined}, + // Note: JsPb converts undefined repeated fields to empty arrays. + aRepeatedMessageList: [], + aRepeatedStringList: [] + }, + result); + }); + + it('testNestedComplexMessage', function() { + // Instantiate the message and set a unique field, just to ensure that we + // are not getting jspb.test.Complex instead. + var msg = new proto.jspb.test.OuterMessage.Complex(); + msg.setInnerComplexField(5); + }); + + it('testSpecialCases', function() { + // Note: Some property names are reserved in JavaScript. + // These names are converted to the Js property named pb_. + var special = new proto.jspb.test.SpecialCases( + ['normal', 'default', 'function', 'var']); + var result = special.toObject(); + assertObjectEquals( + { + normal: 'normal', + pb_default: 'default', + pb_function: 'function', + pb_var: 'var' + }, + result); + }); + + it('testDefaultValues', function() { + var defaultString = 'default<>\'"abc'; + var response = new proto.jspb.test.DefaultValues(); + + // Test toObject + var expectedObject = { + stringField: defaultString, + boolField: true, + intField: 11, + enumField: 13, + emptyField: '', + bytesField: 'bW9v' + }; + assertObjectEquals(expectedObject, response.toObject()); + + + // Test getters + response = new proto.jspb.test.DefaultValues(); + assertEquals(defaultString, response.getStringField()); + assertEquals(true, response.getBoolField()); + assertEquals(11, response.getIntField()); + assertEquals(13, response.getEnumField()); + assertEquals('', response.getEmptyField()); + assertEquals('bW9v', response.getBytesField()); + + function makeDefault(values) { + return new proto.jspb.test.DefaultValues(values); + } + + // Test with undefined values, + // Use push to workaround IE treating undefined array elements as holes. + response = makeDefault([undefined, undefined, undefined, undefined]); + assertEquals(defaultString, response.getStringField()); + assertEquals(true, response.getBoolField()); + assertEquals(11, response.getIntField()); + assertEquals(13, response.getEnumField()); + assertFalse(response.hasStringField()); + assertFalse(response.hasBoolField()); + assertFalse(response.hasIntField()); + assertFalse(response.hasEnumField()); + + // Test with null values, as would be returned by a JSON serializer. + response = makeDefault([null, null, null, null]); + assertEquals(defaultString, response.getStringField()); + assertEquals(true, response.getBoolField()); + assertEquals(11, response.getIntField()); + assertEquals(13, response.getEnumField()); + assertFalse(response.hasStringField()); + assertFalse(response.hasBoolField()); + assertFalse(response.hasIntField()); + assertFalse(response.hasEnumField()); + + // Test with false-like values. + response = makeDefault(['', false, 0, 0]); + assertEquals('', response.getStringField()); + assertEquals(false, response.getBoolField()); + assertEquals(true, response.getIntField() == 0); + assertEquals(true, response.getEnumField() == 0); + assertTrue(response.hasStringField()); + assertTrue(response.hasBoolField()); + assertTrue(response.hasIntField()); + assertTrue(response.hasEnumField()); + + // Test that clearing the values reverts them to the default state. + response = makeDefault(['blah', false, 111, 77]); + response.clearStringField(); + response.clearBoolField(); + response.clearIntField(); + response.clearEnumField(); + assertEquals(defaultString, response.getStringField()); + assertEquals(true, response.getBoolField()); + assertEquals(11, response.getIntField()); + assertEquals(13, response.getEnumField()); + assertFalse(response.hasStringField()); + assertFalse(response.hasBoolField()); + assertFalse(response.hasIntField()); + assertFalse(response.hasEnumField()); + + // Test that setFoo(null) clears the values. + response = makeDefault(['blah', false, 111, 77]); + response.setStringField(null); + response.setBoolField(null); + response.setIntField(undefined); + response.setEnumField(undefined); + assertEquals(defaultString, response.getStringField()); + assertEquals(true, response.getBoolField()); + assertEquals(11, response.getIntField()); + assertEquals(13, response.getEnumField()); + assertFalse(response.hasStringField()); + assertFalse(response.hasBoolField()); + assertFalse(response.hasIntField()); + assertFalse(response.hasEnumField()); + }); + + it('testClearFields', function() { + var data = ['str', true, [11], [[22], [33]], ['s1', 's2']]; + var foo = new proto.jspb.test.OptionalFields(data); + foo.clearAString(); + foo.clearABool(); + foo.clearANestedMessage(); + foo.clearARepeatedMessageList(); + foo.clearARepeatedStringList(); + assertEquals('', foo.getAString()); + assertEquals(false, foo.getABool()); + assertUndefined(foo.getANestedMessage()); + assertFalse(foo.hasAString()); + assertFalse(foo.hasABool()); + assertObjectEquals([], foo.getARepeatedMessageList()); + assertObjectEquals([], foo.getARepeatedStringList()); + // NOTE: We want the missing fields in 'expected' to be undefined, + // but we actually get a sparse array instead. We could use something + // like [1,undefined,2] to avoid this, except that this is still + // sparse on IE. No comment... + var expected = [, , , [], []]; + expected[0] = expected[1] = expected[2] = undefined; + assertObjectEquals(expected, foo.toArray()); + }); + + it('testDifferenceRawObject', /** @suppress {visibility} */ function() { + var p1 = new proto.jspb.test.HasExtensions(['hi', 'diff', {}]); + var p2 = + new proto.jspb.test.HasExtensions(['hi', 'what', {1000: 'unique'}]); + var diff = /** @type {proto.jspb.test.HasExtensions} */ + (jspb.Message.difference(p1, p2)); + assertEquals('', diff.getStr1()); + assertEquals('what', diff.getStr2()); + assertEquals('', diff.getStr3()); + assertEquals('unique', diff.extensionObject_[1000]); + }); + + it('testEqualsSimple', function() { + var s1 = new proto.jspb.test.Simple1(['hi']); + assertTrue(jspb.Message.equals(s1, new proto.jspb.test.Simple1(['hi']))); + assertFalse(jspb.Message.equals(s1, new proto.jspb.test.Simple1(['bye']))); + var s1b = new proto.jspb.test.Simple1(['hi', ['hello']]); + assertTrue(jspb.Message.equals( + s1b, new proto.jspb.test.Simple1(['hi', ['hello']]))); + assertTrue(jspb.Message.equals(s1b, new proto.jspb.test.Simple1([ + 'hi', ['hello', undefined, undefined, undefined] + ]))); + assertFalse(jspb.Message.equals( + s1b, new proto.jspb.test.Simple1(['no', ['hello']]))); + // Test with messages of different types + var s2 = new proto.jspb.test.Simple2(['hi']); + assertFalse(jspb.Message.equals(s1, s2)); + }); + + it('testEquals_softComparison', function() { + var s1 = new proto.jspb.test.Simple1(['hi', [], null]); + assertTrue( + jspb.Message.equals(s1, new proto.jspb.test.Simple1(['hi', []]))); + + var s1b = new proto.jspb.test.Simple1(['hi', [], true]); + assertTrue( + jspb.Message.equals(s1b, new proto.jspb.test.Simple1(['hi', [], 1]))); + }); + + it('testEqualsComplex', function() { + var data1 = ['a', , , [, 11], [[, 22], [, 33]], , ['s1', 's2'], , 1]; + var data2 = ['a', , , [, 11], [[, 22], [, 34]], , ['s1', 's2'], , 1]; + var data3 = ['a', , , [, 11], [[, 22]], , ['s1', 's2'], , 1]; + var data4 = ['hi']; + var c1a = new proto.jspb.test.Complex(data1); + var c1b = new proto.jspb.test.Complex(data1); + var c2 = new proto.jspb.test.Complex(data2); + var c3 = new proto.jspb.test.Complex(data3); + var s1 = new proto.jspb.test.Simple1(data4); + + assertTrue(jspb.Message.equals(c1a, c1b)); + assertFalse(jspb.Message.equals(c1a, c2)); + assertFalse(jspb.Message.equals(c2, c3)); + assertFalse(jspb.Message.equals(c1a, s1)); + }); + + it('testEqualsExtensionsConstructed', function() { + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions([]), + new proto.jspb.test.HasExtensions([{}]))); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]))); + assertFalse(jspb.Message.equals( + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'b'}]}]))); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}]))); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions([, , , {100: [{200: 'a'}]}]))); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions([, , , {100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}]))); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions(['hi', , , {100: [{200: 'a'}]}]))); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions(['hi', , , {100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]))); + }); + + it('testEqualsExtensionsUnconstructed', function() { + assertTrue(jspb.Message.compareFields([], [{}])); + assertTrue(jspb.Message.compareFields([, , , {}], [])); + assertTrue(jspb.Message.compareFields([, , , {}], [, , {}])); + assertTrue(jspb.Message.compareFields( + ['hi', {100: [{200: 'a'}]}], ['hi', {100: [{200: 'a'}]}])); + assertFalse(jspb.Message.compareFields( + ['hi', {100: [{200: 'a'}]}], ['hi', {100: [{200: 'b'}]}])); + assertTrue(jspb.Message.compareFields( + [{100: [{200: 'a'}]}], [{100: [{200: 'a'}]}])); + assertTrue(jspb.Message.compareFields( + [{100: [{200: 'a'}]}], [, , , {100: [{200: 'a'}]}])); + assertTrue(jspb.Message.compareFields( + [, , , {100: [{200: 'a'}]}], [{100: [{200: 'a'}]}])); + assertTrue(jspb.Message.compareFields( + ['hi', {100: [{200: 'a'}]}], ['hi', , , {100: [{200: 'a'}]}])); + assertTrue(jspb.Message.compareFields( + ['hi', , , {100: [{200: 'a'}]}], ['hi', {100: [{200: 'a'}]}])); + }); + + it('testToMap', function() { + var p1 = new proto.jspb.test.Simple1(['k', ['v']]); + var p2 = new proto.jspb.test.Simple1(['k1', ['v1', 'v2']]); + var soymap = jspb.Message.toMap( + [p1, p2], proto.jspb.test.Simple1.prototype.getAString, + proto.jspb.test.Simple1.prototype.toObject); + assertEquals('k', soymap['k'].aString); + assertArrayEquals(['v'], soymap['k'].aRepeatedStringList); + var protomap = jspb.Message.toMap( + [p1, p2], proto.jspb.test.Simple1.prototype.getAString); + assertEquals('k', protomap['k'].getAString()); + assertArrayEquals(['v'], protomap['k'].getARepeatedStringList()); + }); + + it('testClone', function() { + var supportsUint8Array = + !goog.userAgent.IE || goog.userAgent.isVersionOrHigher('10'); + var original = new proto.jspb.test.TestClone(); + original.setStr('v1'); + var simple1 = new proto.jspb.test.Simple1(['x1', ['y1', 'z1']]); + var simple2 = new proto.jspb.test.Simple1(['x2', ['y2', 'z2']]); + var simple3 = new proto.jspb.test.Simple1(['x3', ['y3', 'z3']]); + original.setSimple1(simple1); + original.setSimple2List([simple2, simple3]); + var bytes1 = supportsUint8Array ? new Uint8Array([1, 2, 3]) : '123'; + original.setBytesField(bytes1); + var extension = new proto.jspb.test.CloneExtension(); + extension.setExt('e1'); + original.setExtension(proto.jspb.test.IsExtension.extField, extension); + var clone = original.clone(); + assertArrayEquals( + [ + 'v1', , ['x1', ['y1', 'z1']], , + [['x2', ['y2', 'z2']], ['x3', ['y3', 'z3']]], bytes1, , + {100: [, 'e1']} + ], + clone.toArray()); + clone.setStr('v2'); + var simple4 = new proto.jspb.test.Simple1(['a1', ['b1', 'c1']]); + var simple5 = new proto.jspb.test.Simple1(['a2', ['b2', 'c2']]); + var simple6 = new proto.jspb.test.Simple1(['a3', ['b3', 'c3']]); + clone.setSimple1(simple4); + clone.setSimple2List([simple5, simple6]); + if (supportsUint8Array) { + clone.getBytesField()[0] = 4; + assertObjectEquals(bytes1, original.getBytesField()); + } + var bytes2 = supportsUint8Array ? new Uint8Array([4, 5, 6]) : '456'; + clone.setBytesField(bytes2); + var newExtension = new proto.jspb.test.CloneExtension(); + newExtension.setExt('e2'); + clone.setExtension(proto.jspb.test.CloneExtension.extField, newExtension); + assertArrayEquals( + [ + 'v2', , ['a1', ['b1', 'c1']], , + [['a2', ['b2', 'c2']], ['a3', ['b3', 'c3']]], bytes2, , + {100: [, 'e2']} + ], + clone.toArray()); + assertArrayEquals( + [ + 'v1', , ['x1', ['y1', 'z1']], , + [['x2', ['y2', 'z2']], ['x3', ['y3', 'z3']]], bytes1, , + {100: [, 'e1']} + ], + original.toArray()); + }); + + it('testCopyInto', function() { + var supportsUint8Array = + !goog.userAgent.IE || goog.userAgent.isVersionOrHigher('10'); + var original = new proto.jspb.test.TestClone(); + original.setStr('v1'); + var dest = new proto.jspb.test.TestClone(); + dest.setStr('override'); + var simple1 = new proto.jspb.test.Simple1(['x1', ['y1', 'z1']]); + var simple2 = new proto.jspb.test.Simple1(['x2', ['y2', 'z2']]); + var simple3 = new proto.jspb.test.Simple1(['x3', ['y3', 'z3']]); + var destSimple1 = new proto.jspb.test.Simple1(['ox1', ['oy1', 'oz1']]); + var destSimple2 = new proto.jspb.test.Simple1(['ox2', ['oy2', 'oz2']]); + var destSimple3 = new proto.jspb.test.Simple1(['ox3', ['oy3', 'oz3']]); + original.setSimple1(simple1); + original.setSimple2List([simple2, simple3]); + dest.setSimple1(destSimple1); + dest.setSimple2List([destSimple2, destSimple3]); + var bytes1 = supportsUint8Array ? new Uint8Array([1, 2, 3]) : '123'; + var bytes2 = supportsUint8Array ? new Uint8Array([4, 5, 6]) : '456'; + original.setBytesField(bytes1); + dest.setBytesField(bytes2); + var extension = new proto.jspb.test.CloneExtension(); + extension.setExt('e1'); + original.setExtension(proto.jspb.test.CloneExtension.extField, extension); + + jspb.Message.copyInto(original, dest); + assertArrayEquals(original.toArray(), dest.toArray()); + assertEquals('x1', dest.getSimple1().getAString()); + assertEquals( + 'e1', + dest.getExtension(proto.jspb.test.CloneExtension.extField).getExt()); + dest.getSimple1().setAString('new value'); + assertNotEquals( + dest.getSimple1().getAString(), original.getSimple1().getAString()); + if (supportsUint8Array) { + dest.getBytesField()[0] = 7; + assertObjectEquals(bytes1, original.getBytesField()); + assertObjectEquals(new Uint8Array([7, 2, 3]), dest.getBytesField()); + } else { + dest.setBytesField('789'); + assertObjectEquals(bytes1, original.getBytesField()); + assertObjectEquals('789', dest.getBytesField()); + } + dest.getExtension(proto.jspb.test.CloneExtension.extField) + .setExt('new value'); + assertNotEquals( + dest.getExtension(proto.jspb.test.CloneExtension.extField).getExt(), + original.getExtension(proto.jspb.test.CloneExtension.extField) + .getExt()); + }); + + it('testCopyInto_notSameType', function() { + var a = new proto.jspb.test.TestClone(); + var b = new proto.jspb.test.Simple1(['str', ['s1', 's2']]); + + var e = assertThrows(function() { + jspb.Message.copyInto(a, b); + }); + assertContains('should have the same type', e.message); + }); + + it('testExtensions', function() { + var extension1 = new proto.jspb.test.IsExtension(['ext1field']); + var extension2 = new proto.jspb.test.Simple1(['str', ['s1', 's2']]); + var extendable = new proto.jspb.test.HasExtensions(['v1', 'v2', 'v3']); + extendable.setExtension(proto.jspb.test.IsExtension.extField, extension1); + extendable.setExtension( + proto.jspb.test.IndirectExtension.simple, extension2); + extendable.setExtension(proto.jspb.test.IndirectExtension.str, 'xyzzy'); + extendable.setExtension( + proto.jspb.test.IndirectExtension.repeatedStrList, ['a', 'b']); + var s1 = new proto.jspb.test.Simple1(['foo', ['s1', 's2']]); + var s2 = new proto.jspb.test.Simple1(['bar', ['t1', 't2']]); + extendable.setExtension( + proto.jspb.test.IndirectExtension.repeatedSimpleList, [s1, s2]); + assertObjectEquals( + extension1, + extendable.getExtension(proto.jspb.test.IsExtension.extField)); + assertObjectEquals( + extension2, + extendable.getExtension(proto.jspb.test.IndirectExtension.simple)); + assertObjectEquals( + 'xyzzy', + extendable.getExtension(proto.jspb.test.IndirectExtension.str)); + assertObjectEquals( + ['a', 'b'], + extendable.getExtension( + proto.jspb.test.IndirectExtension.repeatedStrList)); + assertObjectEquals( + [s1, s2], + extendable.getExtension( + proto.jspb.test.IndirectExtension.repeatedSimpleList)); + // Not supported yet, but it should work... + extendable.setExtension(proto.jspb.test.IndirectExtension.simple, null); + assertNull( + extendable.getExtension(proto.jspb.test.IndirectExtension.simple)); + extendable.setExtension(proto.jspb.test.IndirectExtension.str, null); + assertNull(extendable.getExtension(proto.jspb.test.IndirectExtension.str)); + + + // Extension fields with jspb.ignore = true are ignored. + assertUndefined(proto.jspb.test.IndirectExtension['ignored']); + assertUndefined(proto.jspb.test.HasExtensions['ignoredFloating']); + }); + + it('testFloatingExtensions', function() { + // From an autogenerated container. + var extendable = new proto.jspb.test.HasExtensions(['v1', 'v2', 'v3']); + var extension = new proto.jspb.test.Simple1(['foo', ['s1', 's2']]); + extendable.setExtension(proto.jspb.test.simple1, extension); + assertObjectEquals( + extension, extendable.getExtension(proto.jspb.test.simple1)); + + // From _lib mode. + extension = new proto.jspb.test.ExtensionMessage(['s1']); + extendable = new proto.jspb.test.TestExtensionsMessage([16]); + extendable.setExtension(proto.jspb.test.floatingMsgField, extension); + extendable.setExtension(proto.jspb.test.floatingStrField, 's2'); + assertObjectEquals( + extension, extendable.getExtension(proto.jspb.test.floatingMsgField)); + assertObjectEquals( + 's2', extendable.getExtension(proto.jspb.test.floatingStrField)); + assertNotUndefined(proto.jspb.exttest.floatingMsgField); + assertNotUndefined(proto.jspb.exttest.floatingMsgFieldTwo); + assertNotUndefined(proto.jspb.exttest.beta.floatingStrField); + }); + + it('testToObject_extendedObject', function() { + var extension1 = new proto.jspb.test.IsExtension(['ext1field']); + var extension2 = new proto.jspb.test.Simple1(['str', ['s1', 's2'], true]); + var extendable = new proto.jspb.test.HasExtensions(['v1', 'v2', 'v3']); + extendable.setExtension(proto.jspb.test.IsExtension.extField, extension1); + extendable.setExtension( + proto.jspb.test.IndirectExtension.simple, extension2); + extendable.setExtension(proto.jspb.test.IndirectExtension.str, 'xyzzy'); + extendable.setExtension( + proto.jspb.test.IndirectExtension.repeatedStrList, ['a', 'b']); + var s1 = new proto.jspb.test.Simple1(['foo', ['s1', 's2'], true]); + var s2 = new proto.jspb.test.Simple1(['bar', ['t1', 't2'], false]); + extendable.setExtension( + proto.jspb.test.IndirectExtension.repeatedSimpleList, [s1, s2]); + assertObjectEquals( + { + str1: 'v1', + str2: 'v2', + str3: 'v3', + extField: {ext1: 'ext1field'}, + simple: { + aString: 'str', + aRepeatedStringList: ['s1', 's2'], + aBoolean: true + }, + str: 'xyzzy', + repeatedStrList: ['a', 'b'], + repeatedSimpleList: [ + {aString: 'foo', aRepeatedStringList: ['s1', 's2'], aBoolean: true}, + {aString: 'bar', aRepeatedStringList: ['t1', 't2'], aBoolean: false} + ] + }, + extendable.toObject()); + + // Now, with instances included. + assertObjectEquals( + { + str1: 'v1', + str2: 'v2', + str3: 'v3', + extField: { + ext1: 'ext1field', + $jspbMessageInstance: + extendable.getExtension(proto.jspb.test.IsExtension.extField) + }, + simple: { + aString: 'str', + aRepeatedStringList: ['s1', 's2'], + aBoolean: true, + $jspbMessageInstance: extendable.getExtension( + proto.jspb.test.IndirectExtension.simple) + }, + str: 'xyzzy', + repeatedStrList: ['a', 'b'], + repeatedSimpleList: [ + { + aString: 'foo', + aRepeatedStringList: ['s1', 's2'], + aBoolean: true, + $jspbMessageInstance: s1 + }, + { + aString: 'bar', + aRepeatedStringList: ['t1', 't2'], + aBoolean: false, + $jspbMessageInstance: s2 + } + ], + $jspbMessageInstance: extendable + }, + extendable.toObject(true /* opt_includeInstance */)); + }); + + it('testInitialization_emptyArray', function() { + var msg = new proto.jspb.test.HasExtensions([]); + assertArrayEquals([], msg.toArray()); + }); + + it('testInitialization_justExtensionObject', function() { + var msg = new proto.jspb.test.Empty([{1: 'hi'}]); + // The extensionObject is not moved from its original location. + assertArrayEquals([{1: 'hi'}], msg.toArray()); + }); + + it('testInitialization_incompleteList', function() { + var msg = new proto.jspb.test.Empty([1, {4: 'hi'}]); + // The extensionObject is not moved from its original location. + assertArrayEquals([1, {4: 'hi'}], msg.toArray()); + }); + + it('testInitialization_forwardCompatible', function() { + var msg = new proto.jspb.test.Empty([1, 2, 3, {1: 'hi'}]); + assertArrayEquals([1, 2, 3, {1: 'hi'}], msg.toArray()); + }); + + it('testExtendedMessageEnsureObject', + /** @suppress {visibility} */ function() { + var data = + new proto.jspb.test.HasExtensions(['str1', {'a_key': 'an_object'}]); + assertEquals('an_object', data.extensionObject_['a_key']); + }); + + it('testToObject_hasExtensionField', function() { + var data = new proto.jspb.test.HasExtensions(['str1', {100: ['ext1']}]); + var obj = data.toObject(); + assertEquals('str1', obj.str1); + assertEquals('ext1', obj.extField.ext1); + }); + + it('testGetExtension', function() { + var data = new proto.jspb.test.HasExtensions(['str1', {100: ['ext1']}]); + assertEquals('str1', data.getStr1()); + var extension = data.getExtension(proto.jspb.test.IsExtension.extField); + assertNotNull(extension); + assertEquals('ext1', extension.getExt1()); + }); + + it('testSetExtension', function() { + var data = new proto.jspb.test.HasExtensions(); + var extensionMessage = new proto.jspb.test.IsExtension(['is_extension']); + data.setExtension(proto.jspb.test.IsExtension.extField, extensionMessage); + var obj = data.toObject(); + assertNotNull(data.getExtension(proto.jspb.test.IsExtension.extField)); + assertEquals('is_extension', obj.extField.ext1); + }); + + /** + * Note that group is long deprecated, we only support it because JsPb has + * a goal of being able to generate JS classes for all proto descriptors. + */ + it('testGroups', function() { + var group = new proto.jspb.test.TestGroup(); + var someGroup = new proto.jspb.test.TestGroup.RepeatedGroup(); + someGroup.setId('g1'); + someGroup.setSomeBoolList([true, false]); + group.setRepeatedGroupList([someGroup]); + var groups = group.getRepeatedGroupList(); + assertEquals('g1', groups[0].getId()); + assertObjectEquals([true, false], groups[0].getSomeBoolList()); + assertObjectEquals( + {id: 'g1', someBoolList: [true, false]}, groups[0].toObject()); + assertObjectEquals( + { + repeatedGroupList: [{id: 'g1', someBoolList: [true, false]}], + requiredGroup: {id: undefined}, + optionalGroup: undefined, + requiredSimple: {aRepeatedStringList: [], aString: undefined}, + optionalSimple: undefined, + id: undefined + }, + group.toObject()); + var group1 = new proto.jspb.test.TestGroup1(); + group1.setGroup(someGroup); + assertEquals(someGroup, group1.getGroup()); + }); + + it('testNonExtensionFieldsAfterExtensionRange', function() { + var data = [{'1': 'a_string'}]; + var message = new proto.jspb.test.Complex(data); + assertArrayEquals([], message.getARepeatedStringList()); + }); + + it('testReservedGetterNames', function() { + var message = new proto.jspb.test.TestReservedNames(); + message.setExtension$(11); + message.setExtension(proto.jspb.test.TestReservedNamesExtension.foo, 12); + assertEquals(11, message.getExtension$()); + assertEquals( + 12, + message.getExtension(proto.jspb.test.TestReservedNamesExtension.foo)); + assertObjectEquals({extension: 11, foo: 12}, message.toObject()); + }); + + it('testInitializeMessageWithUnsetOneof', function() { + var message = new proto.jspb.test.TestMessageWithOneof([]); + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase + .PARTIAL_ONEOF_NOT_SET, + message.getPartialOneofCase()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.RecursiveOneofCase + .RECURSIVE_ONEOF_NOT_SET, + message.getRecursiveOneofCase()); + }); + + it('testInitializeMessageWithSingleValueSetInOneof', function() { + var message = new proto.jspb.test.TestMessageWithOneof([, , 'x']); + + assertEquals('x', message.getPone()); + assertEquals('', message.getPthree()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PONE, + message.getPartialOneofCase()); + }); + + it('testKeepsLastWireValueSetInUnion_multipleValues', function() { + var message = new proto.jspb.test.TestMessageWithOneof([, , 'x', , 'y']); + + assertEquals('', message.getPone()); + assertEquals('y', message.getPthree()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PTHREE, + message.getPartialOneofCase()); + }); + + it('testSettingOneofFieldClearsOthers', function() { + var message = new proto.jspb.test.TestMessageWithOneof; + assertEquals('', message.getPone()); + assertEquals('', message.getPthree()); + assertFalse(message.hasPone()); + assertFalse(message.hasPthree()); + + message.setPone('hi'); + assertEquals('hi', message.getPone()); + assertEquals('', message.getPthree()); + assertTrue(message.hasPone()); + assertFalse(message.hasPthree()); + + message.setPthree('bye'); + assertEquals('', message.getPone()); + assertEquals('bye', message.getPthree()); + assertFalse(message.hasPone()); + assertTrue(message.hasPthree()); + }); + + it('testSettingOneofFieldDoesNotClearFieldsFromOtherUnions', function() { + var other = new proto.jspb.test.TestMessageWithOneof; + var message = new proto.jspb.test.TestMessageWithOneof; + assertEquals('', message.getPone()); + assertEquals('', message.getPthree()); + assertUndefined(message.getRone()); + assertFalse(message.hasPone()); + assertFalse(message.hasPthree()); + + message.setPone('hi'); + message.setRone(other); + assertEquals('hi', message.getPone()); + assertEquals('', message.getPthree()); + assertEquals(other, message.getRone()); + assertTrue(message.hasPone()); + assertFalse(message.hasPthree()); + + message.setPthree('bye'); + assertEquals('', message.getPone()); + assertEquals('bye', message.getPthree()); + assertEquals(other, message.getRone()); + assertFalse(message.hasPone()); + assertTrue(message.hasPthree()); + }); + + it('testUnsetsOneofCaseWhenFieldIsCleared', function() { + var message = new proto.jspb.test.TestMessageWithOneof; + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase + .PARTIAL_ONEOF_NOT_SET, + message.getPartialOneofCase()); + + message.setPone('hi'); + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PONE, + message.getPartialOneofCase()); + + message.clearPone(); + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase + .PARTIAL_ONEOF_NOT_SET, + message.getPartialOneofCase()); + }); + + it('testMessageWithDefaultOneofValues', function() { + var message = new proto.jspb.test.TestMessageWithOneof; + assertEquals(1234, message.getAone()); + assertEquals(0, message.getAtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofACase + .DEFAULT_ONEOF_A_NOT_SET, + message.getDefaultOneofACase()); + + message.setAone(567); + assertEquals(567, message.getAone()); + assertEquals(0, message.getAtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.AONE, + message.getDefaultOneofACase()); + + message.setAtwo(890); + assertEquals(1234, message.getAone()); + assertEquals(890, message.getAtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.ATWO, + message.getDefaultOneofACase()); + + message.clearAtwo(); + assertEquals(1234, message.getAone()); + assertEquals(0, message.getAtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofACase + .DEFAULT_ONEOF_A_NOT_SET, + message.getDefaultOneofACase()); + }); + + it('testMessageWithDefaultOneofValues_defaultNotOnFirstField', function() { + var message = new proto.jspb.test.TestMessageWithOneof; + assertEquals(0, message.getBone()); + assertEquals(1234, message.getBtwo()); + assertFalse(message.hasBone()); + assertFalse(message.hasBtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase + .DEFAULT_ONEOF_B_NOT_SET, + message.getDefaultOneofBCase()); + + message.setBone(2); + assertEquals(2, message.getBone()); + assertEquals(1234, message.getBtwo()); + assertTrue(message.hasBone()); + assertFalse(message.hasBtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BONE, + message.getDefaultOneofBCase()); + + message.setBtwo(3); + assertEquals(0, message.getBone()); + assertFalse(message.hasBone()); + assertTrue(message.hasBtwo()); + assertEquals(3, message.getBtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BTWO, + message.getDefaultOneofBCase()); + + message.clearBtwo(); + assertEquals(0, message.getBone()); + assertFalse(message.hasBone()); + assertFalse(message.hasBtwo()); + assertEquals(1234, message.getBtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase + .DEFAULT_ONEOF_B_NOT_SET, + message.getDefaultOneofBCase()); + }); + + it('testInitializeMessageWithOneofDefaults', function() { + var message = + new proto.jspb.test.TestMessageWithOneof(new Array(9).concat(567)); + assertEquals(567, message.getAone()); + assertEquals(0, message.getAtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.AONE, + message.getDefaultOneofACase()); + + message = + new proto.jspb.test.TestMessageWithOneof(new Array(10).concat(890)); + assertEquals(1234, message.getAone()); + assertEquals(890, message.getAtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.ATWO, + message.getDefaultOneofACase()); + + message = + new proto.jspb.test.TestMessageWithOneof(new Array(9).concat(567, 890)); + assertEquals(1234, message.getAone()); + assertEquals(890, message.getAtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.ATWO, + message.getDefaultOneofACase()); + }); + + it('testInitializeMessageWithOneofDefaults_defaultNotSetOnFirstField', + function() { + var message; + + message = + new proto.jspb.test.TestMessageWithOneof(new Array(11).concat(567)); + assertEquals(567, message.getBone()); + assertEquals(1234, message.getBtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BONE, + message.getDefaultOneofBCase()); + + message = + new proto.jspb.test.TestMessageWithOneof(new Array(12).concat(890)); + assertEquals(0, message.getBone()); + assertEquals(890, message.getBtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BTWO, + message.getDefaultOneofBCase()); + + message = new proto.jspb.test.TestMessageWithOneof( + new Array(11).concat(567, 890)); + assertEquals(0, message.getBone()); + assertEquals(890, message.getBtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BTWO, + message.getDefaultOneofBCase()); + }); + + it('testOneofContainingAnotherMessage', function() { + var message = new proto.jspb.test.TestMessageWithOneof; + assertEquals( + proto.jspb.test.TestMessageWithOneof.RecursiveOneofCase + .RECURSIVE_ONEOF_NOT_SET, + message.getRecursiveOneofCase()); + + var other = new proto.jspb.test.TestMessageWithOneof; + message.setRone(other); + assertEquals(other, message.getRone()); + assertEquals('', message.getRtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.RecursiveOneofCase.RONE, + message.getRecursiveOneofCase()); + + message.setRtwo('hi'); + assertUndefined(message.getRone()); + assertEquals('hi', message.getRtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.RecursiveOneofCase.RTWO, + message.getRecursiveOneofCase()); + }); + + it('testQueryingOneofCaseEnsuresOnlyOneFieldIsSetInUnderlyingArray', + function() { + var message = new proto.jspb.test.TestMessageWithOneof; + message.setPone('x'); + assertEquals('x', message.getPone()); + assertEquals('', message.getPthree()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PONE, + message.getPartialOneofCase()); + + var array = message.toArray(); + assertEquals('x', array[2]); + assertUndefined(array[4]); + array[4] = 'y'; + + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PTHREE, + message.getPartialOneofCase()); + assertUndefined(array[2]); + assertEquals('y', array[4]); + }); + + it('testFloatingPointFieldsSupportNan', function() { + var assertNan = function(x) { + assertTrue( + 'Expected ' + x + ' (' + goog.typeOf(x) + ') to be NaN.', + typeof x === 'number' && isNaN(x)); + }; + + var message = new proto.jspb.test.FloatingPointFields([ + 'NaN', 'NaN', ['NaN', 'NaN'], 'NaN', 'NaN', 'NaN', ['NaN', 'NaN'], 'NaN' + ]); + assertNan(message.getOptionalFloatField()); + assertNan(message.getRequiredFloatField()); + assertNan(message.getRepeatedFloatFieldList()[0]); + assertNan(message.getRepeatedFloatFieldList()[1]); + assertNan(message.getDefaultFloatField()); + assertNan(message.getOptionalDoubleField()); + assertNan(message.getRequiredDoubleField()); + assertNan(message.getRepeatedDoubleFieldList()[0]); + assertNan(message.getRepeatedDoubleFieldList()[1]); + assertNan(message.getDefaultDoubleField()); + }); +}); diff --git a/tools/env-vars-generator/protobuf/js/compatibility_tests/v3.1.0/proto3_test.js b/tools/env-vars-generator/protobuf/js/compatibility_tests/v3.1.0/proto3_test.js new file mode 100644 index 0000000..696af33 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/compatibility_tests/v3.1.0/proto3_test.js @@ -0,0 +1,329 @@ +// 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. + +goog.require('goog.crypt.base64'); +goog.require('goog.testing.asserts'); + +// CommonJS-LoadFromFile: testbinary_pb proto.jspb.test +goog.require('proto.jspb.test.ForeignMessage'); + +// CommonJS-LoadFromFile: proto3_test_pb proto.jspb.test +goog.require('proto.jspb.test.Proto3Enum'); +goog.require('proto.jspb.test.TestProto3'); + + +var BYTES = new Uint8Array([1, 2, 8, 9]); +var BYTES_B64 = goog.crypt.base64.encodeByteArray(BYTES); + + +/** + * Helper: compare a bytes field to an expected value + * @param {Uint8Array|string} arr + * @param {Uint8Array} expected + * @return {boolean} + */ +function bytesCompare(arr, expected) { + if (typeof arr === 'string') { + arr = goog.crypt.base64.decodeStringToUint8Array(arr); + } + if (arr.length != expected.length) { + return false; + } + for (var i = 0; i < arr.length; i++) { + if (arr[i] != expected[i]) { + return false; + } + } + return true; +} + + +describe('proto3Test', function() { + /** + * Test defaults for proto3 message fields. + */ + it('testProto3FieldDefaults', function() { + var msg = new proto.jspb.test.TestProto3(); + + assertEquals(msg.getOptionalInt32(), 0); + assertEquals(msg.getOptionalInt64(), 0); + assertEquals(msg.getOptionalUint32(), 0); + assertEquals(msg.getOptionalUint64(), 0); + assertEquals(msg.getOptionalSint32(), 0); + assertEquals(msg.getOptionalSint64(), 0); + assertEquals(msg.getOptionalFixed32(), 0); + assertEquals(msg.getOptionalFixed64(), 0); + assertEquals(msg.getOptionalSfixed32(), 0); + assertEquals(msg.getOptionalSfixed64(), 0); + assertEquals(msg.getOptionalFloat(), 0); + assertEquals(msg.getOptionalDouble(), 0); + assertEquals(msg.getOptionalString(), ''); + + // TODO(b/26173701): when we change bytes fields default getter to return + // Uint8Array, we'll want to switch this assertion to match the u8 case. + assertEquals(typeof msg.getOptionalBytes(), 'string'); + assertEquals(msg.getOptionalBytes_asU8() instanceof Uint8Array, true); + assertEquals(typeof msg.getOptionalBytes_asB64(), 'string'); + assertEquals(msg.getOptionalBytes().length, 0); + assertEquals(msg.getOptionalBytes_asU8().length, 0); + assertEquals(msg.getOptionalBytes_asB64(), ''); + + assertEquals(msg.getOptionalForeignEnum(), + proto.jspb.test.Proto3Enum.PROTO3_FOO); + assertEquals(msg.getOptionalForeignMessage(), undefined); + assertEquals(msg.getOptionalForeignMessage(), undefined); + + assertEquals(msg.getRepeatedInt32List().length, 0); + assertEquals(msg.getRepeatedInt64List().length, 0); + assertEquals(msg.getRepeatedUint32List().length, 0); + assertEquals(msg.getRepeatedUint64List().length, 0); + assertEquals(msg.getRepeatedSint32List().length, 0); + assertEquals(msg.getRepeatedSint64List().length, 0); + assertEquals(msg.getRepeatedFixed32List().length, 0); + assertEquals(msg.getRepeatedFixed64List().length, 0); + assertEquals(msg.getRepeatedSfixed32List().length, 0); + assertEquals(msg.getRepeatedSfixed64List().length, 0); + assertEquals(msg.getRepeatedFloatList().length, 0); + assertEquals(msg.getRepeatedDoubleList().length, 0); + assertEquals(msg.getRepeatedStringList().length, 0); + assertEquals(msg.getRepeatedBytesList().length, 0); + assertEquals(msg.getRepeatedForeignEnumList().length, 0); + assertEquals(msg.getRepeatedForeignMessageList().length, 0); + + }); + + + /** + * Test that all fields can be set and read via a serialization roundtrip. + */ + it('testProto3FieldSetGet', function() { + var msg = new proto.jspb.test.TestProto3(); + + msg.setOptionalInt32(-42); + msg.setOptionalInt64(-0x7fffffff00000000); + msg.setOptionalUint32(0x80000000); + msg.setOptionalUint64(0xf000000000000000); + msg.setOptionalSint32(-100); + msg.setOptionalSint64(-0x8000000000000000); + msg.setOptionalFixed32(1234); + msg.setOptionalFixed64(0x1234567800000000); + msg.setOptionalSfixed32(-1234); + msg.setOptionalSfixed64(-0x1234567800000000); + msg.setOptionalFloat(1.5); + msg.setOptionalDouble(-1.5); + msg.setOptionalBool(true); + msg.setOptionalString('hello world'); + msg.setOptionalBytes(BYTES); + var submsg = new proto.jspb.test.ForeignMessage(); + submsg.setC(16); + msg.setOptionalForeignMessage(submsg); + msg.setOptionalForeignEnum(proto.jspb.test.Proto3Enum.PROTO3_BAR); + + msg.setRepeatedInt32List([-42]); + msg.setRepeatedInt64List([-0x7fffffff00000000]); + msg.setRepeatedUint32List([0x80000000]); + msg.setRepeatedUint64List([0xf000000000000000]); + msg.setRepeatedSint32List([-100]); + msg.setRepeatedSint64List([-0x8000000000000000]); + msg.setRepeatedFixed32List([1234]); + msg.setRepeatedFixed64List([0x1234567800000000]); + msg.setRepeatedSfixed32List([-1234]); + msg.setRepeatedSfixed64List([-0x1234567800000000]); + msg.setRepeatedFloatList([1.5]); + msg.setRepeatedDoubleList([-1.5]); + msg.setRepeatedBoolList([true]); + msg.setRepeatedStringList(['hello world']); + msg.setRepeatedBytesList([BYTES]); + submsg = new proto.jspb.test.ForeignMessage(); + submsg.setC(1000); + msg.setRepeatedForeignMessageList([submsg]); + msg.setRepeatedForeignEnumList([proto.jspb.test.Proto3Enum.PROTO3_BAR]); + + msg.setOneofString('asdf'); + + var serialized = msg.serializeBinary(); + msg = proto.jspb.test.TestProto3.deserializeBinary(serialized); + + assertEquals(msg.getOptionalInt32(), -42); + assertEquals(msg.getOptionalInt64(), -0x7fffffff00000000); + assertEquals(msg.getOptionalUint32(), 0x80000000); + assertEquals(msg.getOptionalUint64(), 0xf000000000000000); + assertEquals(msg.getOptionalSint32(), -100); + assertEquals(msg.getOptionalSint64(), -0x8000000000000000); + assertEquals(msg.getOptionalFixed32(), 1234); + assertEquals(msg.getOptionalFixed64(), 0x1234567800000000); + assertEquals(msg.getOptionalSfixed32(), -1234); + assertEquals(msg.getOptionalSfixed64(), -0x1234567800000000); + assertEquals(msg.getOptionalFloat(), 1.5); + assertEquals(msg.getOptionalDouble(), -1.5); + assertEquals(msg.getOptionalBool(), true); + assertEquals(msg.getOptionalString(), 'hello world'); + assertEquals(true, bytesCompare(msg.getOptionalBytes(), BYTES)); + assertEquals(msg.getOptionalForeignMessage().getC(), 16); + assertEquals(msg.getOptionalForeignEnum(), + proto.jspb.test.Proto3Enum.PROTO3_BAR); + + assertElementsEquals(msg.getRepeatedInt32List(), [-42]); + assertElementsEquals(msg.getRepeatedInt64List(), [-0x7fffffff00000000]); + assertElementsEquals(msg.getRepeatedUint32List(), [0x80000000]); + assertElementsEquals(msg.getRepeatedUint64List(), [0xf000000000000000]); + assertElementsEquals(msg.getRepeatedSint32List(), [-100]); + assertElementsEquals(msg.getRepeatedSint64List(), [-0x8000000000000000]); + assertElementsEquals(msg.getRepeatedFixed32List(), [1234]); + assertElementsEquals(msg.getRepeatedFixed64List(), [0x1234567800000000]); + assertElementsEquals(msg.getRepeatedSfixed32List(), [-1234]); + assertElementsEquals(msg.getRepeatedSfixed64List(), [-0x1234567800000000]); + assertElementsEquals(msg.getRepeatedFloatList(), [1.5]); + assertElementsEquals(msg.getRepeatedDoubleList(), [-1.5]); + assertElementsEquals(msg.getRepeatedBoolList(), [true]); + assertElementsEquals(msg.getRepeatedStringList(), ['hello world']); + assertEquals(msg.getRepeatedBytesList().length, 1); + assertEquals(true, bytesCompare(msg.getRepeatedBytesList()[0], BYTES)); + assertEquals(msg.getRepeatedForeignMessageList().length, 1); + assertEquals(msg.getRepeatedForeignMessageList()[0].getC(), 1000); + assertElementsEquals(msg.getRepeatedForeignEnumList(), + [proto.jspb.test.Proto3Enum.PROTO3_BAR]); + + assertEquals(msg.getOneofString(), 'asdf'); + }); + + + /** + * Test that oneofs continue to have a notion of field presence. + */ + it('testOneofs', function() { + var msg = new proto.jspb.test.TestProto3(); + + assertEquals(msg.getOneofUint32(), 0); + assertEquals(msg.getOneofForeignMessage(), undefined); + assertEquals(msg.getOneofString(), ''); + assertEquals(msg.getOneofBytes(), ''); + assertFalse(msg.hasOneofUint32()); + assertFalse(msg.hasOneofString()); + assertFalse(msg.hasOneofBytes()); + + msg.setOneofUint32(42); + assertEquals(msg.getOneofUint32(), 42); + assertEquals(msg.getOneofForeignMessage(), undefined); + assertEquals(msg.getOneofString(), ''); + assertEquals(msg.getOneofBytes(), ''); + assertTrue(msg.hasOneofUint32()); + assertFalse(msg.hasOneofString()); + assertFalse(msg.hasOneofBytes()); + + + var submsg = new proto.jspb.test.ForeignMessage(); + msg.setOneofForeignMessage(submsg); + assertEquals(msg.getOneofUint32(), 0); + assertEquals(msg.getOneofForeignMessage(), submsg); + assertEquals(msg.getOneofString(), ''); + assertEquals(msg.getOneofBytes(), ''); + assertFalse(msg.hasOneofUint32()); + assertFalse(msg.hasOneofString()); + assertFalse(msg.hasOneofBytes()); + + msg.setOneofString('hello'); + assertEquals(msg.getOneofUint32(), 0); + assertEquals(msg.getOneofForeignMessage(), undefined); + assertEquals(msg.getOneofString(), 'hello'); + assertEquals(msg.getOneofBytes(), ''); + assertFalse(msg.hasOneofUint32()); + assertTrue(msg.hasOneofString()); + assertFalse(msg.hasOneofBytes()); + + msg.setOneofBytes(goog.crypt.base64.encodeString('\u00FF\u00FF')); + assertEquals(msg.getOneofUint32(), 0); + assertEquals(msg.getOneofForeignMessage(), undefined); + assertEquals(msg.getOneofString(), ''); + assertEquals(msg.getOneofBytes_asB64(), + goog.crypt.base64.encodeString('\u00FF\u00FF')); + assertFalse(msg.hasOneofUint32()); + assertFalse(msg.hasOneofString()); + assertTrue(msg.hasOneofBytes()); + }); + + + /** + * Test that "default"-valued primitive fields are not emitted on the wire. + */ + it('testNoSerializeDefaults', function() { + var msg = new proto.jspb.test.TestProto3(); + + // Set each primitive to a non-default value, then back to its default, to + // ensure that the serialization is actually checking the value and not just + // whether it has ever been set. + msg.setOptionalInt32(42); + msg.setOptionalInt32(0); + msg.setOptionalDouble(3.14); + msg.setOptionalDouble(0.0); + msg.setOptionalBool(true); + msg.setOptionalBool(false); + msg.setOptionalString('hello world'); + msg.setOptionalString(''); + msg.setOptionalBytes(goog.crypt.base64.encodeString('\u00FF\u00FF')); + msg.setOptionalBytes(''); + msg.setOptionalForeignMessage(new proto.jspb.test.ForeignMessage()); + msg.setOptionalForeignMessage(null); + msg.setOptionalForeignEnum(proto.jspb.test.Proto3Enum.PROTO3_BAR); + msg.setOptionalForeignEnum(proto.jspb.test.Proto3Enum.PROTO3_FOO); + msg.setOneofUint32(32); + msg.clearOneofUint32(); + + + var serialized = msg.serializeBinary(); + assertEquals(0, serialized.length); + }); + + /** + * Test that base64 string and Uint8Array are interchangeable in bytes fields. + */ + it('testBytesFieldsInterop', function() { + var msg = new proto.jspb.test.TestProto3(); + // Set as a base64 string and check all the getters work. + msg.setOptionalBytes(BYTES_B64); + assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES)); + assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES)); + assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); + + // Test binary serialize round trip doesn't break it. + msg = proto.jspb.test.TestProto3.deserializeBinary(msg.serializeBinary()); + assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES)); + assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES)); + assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); + + msg = new proto.jspb.test.TestProto3(); + // Set as a Uint8Array and check all the getters work. + msg.setOptionalBytes(BYTES); + assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES)); + assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES)); + assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); + + }); +}); diff --git a/tools/env-vars-generator/protobuf/js/compatibility_tests/v3.1.0/test.proto b/tools/env-vars-generator/protobuf/js/compatibility_tests/v3.1.0/test.proto new file mode 100644 index 0000000..48cb37e --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/compatibility_tests/v3.1.0/test.proto @@ -0,0 +1,262 @@ +// 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: mwr@google.com (Mark Rawling) + +syntax = "proto2"; + +option java_package = "com.google.apps.jspb.proto"; +option java_multiple_files = true; + +import "google/protobuf/descriptor.proto"; + +package jspb.test; + +message Empty { +} + +enum OuterEnum { + FOO = 1; + BAR = 2; +} + +message EnumContainer { + optional OuterEnum outer_enum = 1; +} + +message Simple1 { + required string a_string = 1; + repeated string a_repeated_string = 2; + optional bool a_boolean = 3; +} + +// A message that differs from Simple1 only by name +message Simple2 { + required string a_string = 1; + repeated string a_repeated_string = 2; +} + +message SpecialCases { + required string normal = 1; + // Examples of Js reserved names that are converted to pb_. + required string default = 2; + required string function = 3; + required string var = 4; +} + +message OptionalFields { + message Nested { + optional int32 an_int = 1; + } + optional string a_string = 1; + required bool a_bool = 2; + optional Nested a_nested_message = 3; + repeated Nested a_repeated_message = 4; + repeated string a_repeated_string = 5; +} + +message HasExtensions { + optional string str1 = 1; + optional string str2 = 2; + optional string str3 = 3; + extensions 10 to max; +} + +message Complex { + message Nested { + required int32 an_int = 2; + } + required string a_string = 1; + required bool an_out_of_order_bool = 9; + optional Nested a_nested_message = 4; + repeated Nested a_repeated_message = 5; + repeated string a_repeated_string = 7; +} + +message OuterMessage { + // Make sure this doesn't conflict with the other Complex message. + message Complex { + optional int32 inner_complex_field = 1; + } +} + +message IsExtension { + extend HasExtensions { + optional IsExtension ext_field = 100; + } + optional string ext1 = 1; + + // Extensions of proto2 Descriptor messages will be ignored. + extend google.protobuf.EnumOptions { + optional string simple_option = 42113038; + } +} + +message IndirectExtension { + extend HasExtensions { + optional Simple1 simple = 101; + optional string str = 102; + repeated string repeated_str = 103; + repeated Simple1 repeated_simple = 104; + } +} + +extend HasExtensions { + optional Simple1 simple1 = 105; +} + +message DefaultValues { + enum Enum { + E1 = 13; + E2 = 77; + } + optional string string_field = 1 [default="default<>\'\"abc"]; + optional bool bool_field = 2 [default=true]; + optional int64 int_field = 3 [default=11]; + optional Enum enum_field = 4 [default=E1]; + optional string empty_field = 6 [default=""]; + optional bytes bytes_field = 8 [default="moo"]; // Base64 encoding is "bW9v" +} + +message FloatingPointFields { + optional float optional_float_field = 1; + required float required_float_field = 2; + repeated float repeated_float_field = 3; + optional float default_float_field = 4 [default = 2.0]; + optional double optional_double_field = 5; + required double required_double_field = 6; + repeated double repeated_double_field = 7; + optional double default_double_field = 8 [default = 2.0]; +} + +message TestClone { + optional string str = 1; + optional Simple1 simple1 = 3; + repeated Simple1 simple2 = 5; + optional bytes bytes_field = 6; + optional string unused = 7; + extensions 10 to max; +} + +message CloneExtension { + extend TestClone { + optional CloneExtension ext_field = 100; + } + optional string ext = 2; +} + +message TestGroup { + repeated group RepeatedGroup = 1 { + required string id = 1; + repeated bool some_bool = 2; + } + required group RequiredGroup = 2 { + required string id = 1; + } + optional group OptionalGroup = 3 { + required string id = 1; + } + optional string id = 4; + required Simple2 required_simple = 5; + optional Simple2 optional_simple = 6; +} + +message TestGroup1 { + optional TestGroup.RepeatedGroup group = 1; +} + +message TestReservedNames { + optional int32 extension = 1; + extensions 10 to max; +} + +message TestReservedNamesExtension { + extend TestReservedNames { + optional int32 foo = 10; + } +} + +message TestMessageWithOneof { + + oneof partial_oneof { + string pone = 3; + string pthree = 5; + } + + oneof recursive_oneof { + TestMessageWithOneof rone = 6; + string rtwo = 7; + } + + optional bool normal_field = 8; + repeated string repeated_field = 9; + + oneof default_oneof_a { + int32 aone = 10 [default = 1234]; + int32 atwo = 11; + } + + oneof default_oneof_b { + int32 bone = 12; + int32 btwo = 13 [default = 1234]; + } +} + +message TestEndsWithBytes { + optional int32 value = 1; + optional bytes data = 2; +} + +message TestMapFieldsNoBinary { + map map_string_string = 1; + map map_string_int32 = 2; + map map_string_int64 = 3; + map map_string_bool = 4; + map map_string_double = 5; + map map_string_enum = 6; + map map_string_msg = 7; + + map map_int32_string = 8; + map map_int64_string = 9; + map map_bool_string = 10; + + optional TestMapFieldsNoBinary test_map_fields = 11; + map map_string_testmapfields = 12; +} + +enum MapValueEnumNoBinary { + MAP_VALUE_FOO_NOBINARY = 0; + MAP_VALUE_BAR_NOBINARY = 1; + MAP_VALUE_BAZ_NOBINARY = 2; +} + +message MapValueMessageNoBinary { + optional int32 foo = 1; +} diff --git a/tools/env-vars-generator/protobuf/js/compatibility_tests/v3.1.0/testempty.proto b/tools/env-vars-generator/protobuf/js/compatibility_tests/v3.1.0/testempty.proto new file mode 100644 index 0000000..960bce4 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/compatibility_tests/v3.1.0/testempty.proto @@ -0,0 +1,34 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto2"; + +package javatests.com.google.apps.jspb; + diff --git a/tools/env-vars-generator/protobuf/js/debug_test.js b/tools/env-vars-generator/protobuf/js/debug_test.js new file mode 100644 index 0000000..5096869 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/debug_test.js @@ -0,0 +1,188 @@ +// 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. + +goog.setTestOnly(); + +goog.require('goog.testing.asserts'); + +// CommonJS-LoadFromFile: google-protobuf +goog.require('jspb.debug'); + +// CommonJS-LoadFromFile: test_pb +goog.require('proto.jspb.test.HasExtensions'); +goog.require('proto.jspb.test.IsExtension'); +goog.require('proto.jspb.test.MapValueMessageNoBinary'); +goog.require('proto.jspb.test.Simple1'); +goog.require('proto.jspb.test.TestMapFieldsNoBinary'); + + +// CommonJS-LoadFromFile: testbinary_pb +goog.require('proto.jspb.test.TestAllTypes'); + +describe('debugTest', function() { + it('testSimple1', function() { + if (COMPILED) { + return; + } + var message = new proto.jspb.test.Simple1(); + message.setAString('foo'); + assertObjectEquals({ + $name: 'proto.jspb.test.Simple1', + 'aString': 'foo', + 'aRepeatedStringList': [] + }, jspb.debug.dump(message)); + + message.setABoolean(true); + message.setARepeatedStringList(['1', '2']); + + assertObjectEquals({ + $name: 'proto.jspb.test.Simple1', + 'aString': 'foo', + 'aRepeatedStringList': ['1', '2'], + 'aBoolean': true + }, jspb.debug.dump(message)); + + message.clearAString(); + + assertObjectEquals({ + $name: 'proto.jspb.test.Simple1', + 'aRepeatedStringList': ['1', '2'], + 'aBoolean': true + }, jspb.debug.dump(message)); + }); + + it('testBytes', function() { + if (COMPILED || typeof Uint8Array == 'undefined') { + return; + } + var message = new proto.jspb.test.TestAllTypes(); + var bytes = new Uint8Array(4); + message.setOptionalBytes(bytes); + assertEquals(jspb.debug.dump(message)['optionalBytes'], bytes); + }); + + it('testExtensions', function() { + if (COMPILED) { + return; + } + var extension = new proto.jspb.test.IsExtension(); + extension.setExt1('ext1field'); + var extendable = new proto.jspb.test.HasExtensions(); + extendable.setStr1('v1'); + extendable.setStr2('v2'); + extendable.setStr3('v3'); + extendable.setExtension(proto.jspb.test.IsExtension.extField, extension); + + assertObjectEquals({ + '$name': 'proto.jspb.test.HasExtensions', + 'str1': 'v1', + 'str2': 'v2', + 'str3': 'v3', + '$extensions': { + 'extField': { + '$name': 'proto.jspb.test.IsExtension', + 'ext1': 'ext1field' + }, + 'repeatedSimpleList': [] + } + }, jspb.debug.dump(extendable)); + }); + + it('testMapsBasicTypes', function() { + if (COMPILED) { + return; + } + + var message = new proto.jspb.test.TestMapFieldsNoBinary(); + message.getMapBoolStringMap().set(true, 'bool_string_value1'); + message.getMapBoolStringMap().set(false, 'bool_string_value2'); + message.getMapStringInt32Map().set('key', 111); + + assertObjectEquals({ + '$name': 'proto.jspb.test.TestMapFieldsNoBinary', + 'mapBoolStringMap': { + true: 'bool_string_value1', + false: 'bool_string_value2' + }, + 'mapInt32StringMap': {}, + 'mapInt64StringMap': {}, + 'mapStringBoolMap': {}, + 'mapStringDoubleMap': {}, + 'mapStringEnumMap': {}, + 'mapStringInt32Map': { + 'key': 111 + }, + 'mapStringInt64Map': {}, + 'mapStringMsgMap': {}, + 'mapStringStringMap': {}, + 'mapStringTestmapfieldsMap': {} + }, jspb.debug.dump(message)); + }); + + it('testMapsMessageValues', function() { + if (COMPILED) { + return; + } + + var value1 = new proto.jspb.test.MapValueMessageNoBinary(); + value1.setFoo(1111); + var value2 = new proto.jspb.test.MapValueMessageNoBinary(); + value2.setFoo(2222); + + var message = new proto.jspb.test.TestMapFieldsNoBinary(); + message.getMapStringMsgMap().set('key1', value1); + message.getMapStringMsgMap().set('key2', value2); + + assertObjectEquals({ + '$name': 'proto.jspb.test.TestMapFieldsNoBinary', + 'mapBoolStringMap': {}, + 'mapInt32StringMap': {}, + 'mapInt64StringMap': {}, + 'mapStringBoolMap': {}, + 'mapStringDoubleMap': {}, + 'mapStringEnumMap': {}, + 'mapStringInt32Map': {}, + 'mapStringInt64Map': {}, + 'mapStringMsgMap': { + 'key1': { + '$name': 'proto.jspb.test.MapValueMessageNoBinary', + 'foo': 1111 + }, + 'key2': { + '$name': 'proto.jspb.test.MapValueMessageNoBinary', + 'foo': 2222 + } + }, + 'mapStringStringMap': {}, + 'mapStringTestmapfieldsMap': {} + }, jspb.debug.dump(message)); + }); + +}); diff --git a/tools/env-vars-generator/protobuf/js/experimental/benchmarks/code_size/apps_jspb/all_types_proto3.js b/tools/env-vars-generator/protobuf/js/experimental/benchmarks/code_size/apps_jspb/all_types_proto3.js new file mode 100644 index 0000000..9eb8126 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/experimental/benchmarks/code_size/apps_jspb/all_types_proto3.js @@ -0,0 +1,312 @@ +/** + * @fileoverview The code size benchmark of apps JSPB for proto3 all types + */ +goog.module('protobuf.benchmark.code_size.apps_jspb.AllTypesProto3'); + +// const ForeignEnum = goog.require('proto.proto3_unittest.ForeignEnum'); +const ForeignMessage = goog.require('proto.proto3_unittest.ForeignMessage'); +const TestAllTypes = goog.require('proto.proto3_unittest.TestAllTypes'); +const TestPackedTypes = goog.require('proto.proto3_unittest.TestPackedTypes'); +const {ensureCommonBaseLine} = goog.require('protobuf.benchmark.codeSize.codeSizeBase'); + +ensureCommonBaseLine(); + +/** + * The testing scenario is the same as kernel one. + * We have + * 1) add element to repeated fields + * 2) add element list to repeated fields + * 3) set fields + * 4) set repeated fields element + * 5) get fields + * 6) get repeated fields element + * 7) get repeated fields length + * @return {string} + */ +function accessAllTypes() { + const msgAllTypes = TestAllTypes.deserialize(''); + const msgPackedTypes = TestPackedTypes.deserialize(''); + + msgPackedTypes.addPackedBool(true); + [true].forEach((e) => msgPackedTypes.addPackedBool(e)); + msgAllTypes.addRepeatedBool(true, 1); + [true].forEach((e) => msgAllTypes.addRepeatedBool(e)); + msgAllTypes.addRepeatedBytes('1', 1); + ['1'].forEach((e) => msgAllTypes.addRepeatedBytes(e)); + msgPackedTypes.addPackedDouble(1.0); + [1.0].forEach((e) => msgPackedTypes.addPackedDouble(e)); + msgAllTypes.addRepeatedDouble(1.0, 1); + [1.0].forEach((e) => msgAllTypes.addRepeatedDouble(e)); + msgPackedTypes.addPackedFixed32(1, 1); + [1].forEach((e) => msgPackedTypes.addPackedFixed32(e)); + msgAllTypes.addRepeatedFixed32(1, 1); + [1].forEach((e) => msgAllTypes.addRepeatedFixed32(e)); + msgPackedTypes.addPackedFixed64(1, 1); + [1].forEach((e) => msgPackedTypes.addPackedFixed64(e)); + msgAllTypes.addRepeatedFixed64(1, 1); + [1].forEach((e) => msgAllTypes.addRepeatedFixed64(e)); + msgPackedTypes.addPackedFloat(1.0, 1); + [1.0].forEach((e) => msgPackedTypes.addPackedFloat(e)); + msgAllTypes.addRepeatedFloat(1.0, 1); + [1.0].forEach((e) => msgAllTypes.addRepeatedFloat(e)); + msgPackedTypes.addPackedInt32(1, 1); + [1].forEach((e) => msgPackedTypes.addPackedInt32(e)); + msgAllTypes.addRepeatedInt32(1, 1); + [1].forEach((e) => msgAllTypes.addRepeatedInt32(e)); + msgPackedTypes.addPackedInt64(1, 1); + [1].forEach((e) => msgPackedTypes.addPackedInt64(e)); + msgAllTypes.addRepeatedInt64(1, 1); + [1].forEach((e) => msgAllTypes.addRepeatedInt64(e)); + // msgPackedTypes.addPackedEnum(ForeignEnum.FOREIGN_BAR); + // [ForeignEnum.FOREIGN_BAR].forEach((e) => msgPackedTypes.addPackedEnum(e)); + // msgAllTypes.addRepeatedForeignEnum(ForeignEnum.FOREIGN_BAR); + // [ForeignEnum.FOREIGN_BAR].forEach( + // (e) => msgAllTypes.addRepeatedForeignEnum(e)); + msgAllTypes.addRepeatedForeignMessage(ForeignMessage.deserialize(''), 1); + [ForeignMessage.deserialize('')].forEach( + (e) => msgAllTypes.addRepeatedForeignMessage(e)); + msgPackedTypes.addPackedSfixed32(1, 1); + [1].forEach((e) => msgPackedTypes.addPackedSfixed32(e)); + msgAllTypes.addRepeatedSfixed32(1, 1); + [1].forEach((e) => msgAllTypes.addRepeatedSfixed32(e)); + msgPackedTypes.addPackedSfixed64(1, 1); + [1].forEach((e) => msgPackedTypes.addPackedSfixed64(e)); + msgAllTypes.addRepeatedSfixed64(1, 1); + [1].forEach((e) => msgAllTypes.addRepeatedSfixed64(e)); + msgPackedTypes.addPackedSint32(1, 1); + [1].forEach((e) => msgPackedTypes.addPackedSint32(e)); + msgAllTypes.addRepeatedSint32(1, 1); + [1].forEach((e) => msgAllTypes.addRepeatedSint32(e)); + msgPackedTypes.addPackedSint64(1, 1); + [1].forEach((e) => msgPackedTypes.addPackedSint64(e)); + msgAllTypes.addRepeatedSint64(1, 1); + [1].forEach((e) => msgAllTypes.addRepeatedSint64(e)); + msgAllTypes.addRepeatedString('', 1); + [''].forEach((e) => msgAllTypes.addRepeatedString(e)); + msgPackedTypes.addPackedUint32(1, 1); + [1].forEach((e) => msgPackedTypes.addPackedUint32(e)); + msgAllTypes.addRepeatedUint32(1, 1); + [1].forEach((e) => msgAllTypes.addRepeatedUint32(e)); + msgPackedTypes.addPackedUint64(1, 1); + [1].forEach((e) => msgPackedTypes.addPackedUint64(e)); + msgAllTypes.addRepeatedUint64(1, 1); + [1].forEach((e) => msgAllTypes.addRepeatedUint64(e)); + + msgAllTypes.setOptionalBool(true); + msgAllTypes.setOptionalBytes(''); + msgAllTypes.setOptionalDouble(1.0); + msgAllTypes.setOptionalFixed32(1); + msgAllTypes.setOptionalFixed64(1); + msgAllTypes.setOptionalFloat(1.0); + msgAllTypes.setOptionalInt32(1); + msgAllTypes.setOptionalInt64(1); + // msgAllTypes.setOptionalForeignEnum(ForeignEnum.FOREIGN_BAR); + msgAllTypes.setOptionalForeignMessage(ForeignMessage.deserialize('')); + msgAllTypes.setOptionalSfixed32(1); + msgAllTypes.setOptionalSfixed64(1); + msgAllTypes.setOptionalSint32(1); + msgAllTypes.setOptionalSint64(1); + msgAllTypes.setOptionalString(''); + msgAllTypes.setOptionalUint32(1); + msgAllTypes.setOptionalUint64(1); + msgPackedTypes.setPackedBoolList([true]); + let arrayVal; + arrayVal = msgPackedTypes.getPackedBoolList(); + arrayVal[0] = true; + msgPackedTypes.setPackedBoolList(arrayVal); + msgAllTypes.setRepeatedBoolList([true]); + arrayVal = msgAllTypes.getRepeatedBoolList(); + arrayVal[0] = true; + msgAllTypes.setRepeatedBoolList(arrayVal); + msgAllTypes.setRepeatedBytesList(['']); + arrayVal = msgAllTypes.getRepeatedBytesList_asB64(); + arrayVal[0] = ''; + msgAllTypes.setRepeatedBytesList(arrayVal); + msgPackedTypes.setPackedDoubleList([1.0]); + arrayVal = msgPackedTypes.getPackedDoubleList(); + arrayVal[0] = 1.0; + msgPackedTypes.setPackedDoubleList(arrayVal); + msgAllTypes.setRepeatedDoubleList([1.0]); + arrayVal = msgAllTypes.getRepeatedDoubleList(); + arrayVal[0] = 1.0; + msgAllTypes.setRepeatedDoubleList(arrayVal); + msgPackedTypes.setPackedFixed32List([1]); + arrayVal = msgPackedTypes.getPackedFixed32List(); + arrayVal[0] = 1; + msgPackedTypes.setPackedFixed32List(arrayVal); + msgAllTypes.setRepeatedFixed32List([1]); + arrayVal = msgAllTypes.getRepeatedFixed32List(); + arrayVal[0] = 1; + msgAllTypes.setRepeatedFixed32List(arrayVal); + msgPackedTypes.setPackedFixed64List([1]); + arrayVal = msgPackedTypes.getPackedFixed64List(); + arrayVal[0] = 1; + msgPackedTypes.setPackedFixed64List(arrayVal); + msgAllTypes.setRepeatedFixed64List([1]); + arrayVal = msgAllTypes.getRepeatedFixed64List(); + arrayVal[0] = 1; + msgAllTypes.setRepeatedFixed64List(arrayVal); + msgPackedTypes.setPackedFloatList([1.0]); + arrayVal = msgPackedTypes.getPackedFloatList(); + arrayVal[0] = 1.0; + msgPackedTypes.setPackedFloatList(arrayVal); + msgAllTypes.setRepeatedFloatList([1.0]); + arrayVal = msgAllTypes.getRepeatedFloatList(); + arrayVal[0] = 1.0; + msgAllTypes.setRepeatedFloatList(arrayVal); + msgPackedTypes.setPackedInt32List([1]); + arrayVal = msgPackedTypes.getPackedInt32List(); + arrayVal[0] = 1; + msgPackedTypes.setPackedInt32List(arrayVal); + msgAllTypes.setRepeatedInt32List([1]); + arrayVal = msgAllTypes.getRepeatedInt32List(); + arrayVal[0] = 1; + msgAllTypes.setRepeatedInt32List(arrayVal); + msgPackedTypes.setPackedInt64List([1]); + arrayVal = msgPackedTypes.getPackedInt64List(); + arrayVal[0] = 1; + msgPackedTypes.setPackedInt64List(arrayVal); + msgAllTypes.setRepeatedInt64List([1]); + arrayVal = msgAllTypes.getRepeatedInt64List(); + arrayVal[0] = 1; + msgAllTypes.setRepeatedInt64List(arrayVal); + // msgPackedTypes.setPackedEnumList([ForeignEnum.FOREIGN_BAR]); + // arrayVal = msgPackedTypes.getPackedEnumList(); + // arrayVal[0] = ForeignEnum.FOREIGN_BAR; + // msgPackedTypes.setPackedEnumList(arrayVal); + // msgAllTypes.setRepeatedForeignEnumList([ForeignEnum.FOREIGN_BAR]); + // arrayVal = msgAllTypes.getRepeatedForeignEnumList(); + // arrayVal[0] = ForeignEnum.FOREIGN_BAR; + // msgAllTypes.setRepeatedForeignEnumList(arrayVal); + msgAllTypes.setRepeatedForeignMessageList([ForeignMessage.deserialize('')]); + arrayVal = msgAllTypes.getRepeatedForeignMessageList(); + arrayVal[0] = ForeignMessage.deserialize(''); + msgAllTypes.setRepeatedForeignMessageList(arrayVal); + msgPackedTypes.setPackedSfixed32List([1]); + arrayVal = msgPackedTypes.getPackedSfixed32List(); + arrayVal[0] = 1; + msgPackedTypes.setPackedSfixed32List(arrayVal); + msgAllTypes.setRepeatedSfixed32List([1]); + arrayVal = msgAllTypes.getRepeatedSfixed32List(); + arrayVal[0] = 1; + msgAllTypes.setRepeatedSfixed32List(arrayVal); + msgPackedTypes.setPackedSfixed64List([1]); + arrayVal = msgPackedTypes.getPackedSfixed64List(); + arrayVal[0] = 1; + msgPackedTypes.setPackedSfixed64List(arrayVal); + msgAllTypes.setRepeatedSfixed64List([1]); + arrayVal = msgAllTypes.getRepeatedSfixed64List(); + arrayVal[0] = 1; + msgAllTypes.setRepeatedSfixed64List(arrayVal); + msgPackedTypes.setPackedSint32List([1]); + arrayVal = msgPackedTypes.getPackedSint32List(); + arrayVal[0] = 1; + msgPackedTypes.setPackedSint32List(arrayVal); + msgAllTypes.setRepeatedSint32List([1]); + arrayVal = msgAllTypes.getRepeatedSint32List(); + arrayVal[0] = 1; + msgAllTypes.setRepeatedSint32List(arrayVal); + msgPackedTypes.setPackedSint64List([1]); + arrayVal = msgPackedTypes.getPackedSint64List(); + arrayVal[0] = 1; + msgPackedTypes.setPackedSint64List(arrayVal); + msgAllTypes.setRepeatedSint64List([1]); + arrayVal = msgAllTypes.getRepeatedSint64List(); + arrayVal[0] = 1; + msgAllTypes.setRepeatedSint64List(arrayVal); + msgPackedTypes.setPackedUint32List([1]); + arrayVal = msgPackedTypes.getPackedUint32List(); + arrayVal[0] = 1; + msgPackedTypes.setPackedUint32List(arrayVal); + msgAllTypes.setRepeatedUint32List([1]); + arrayVal = msgAllTypes.getRepeatedUint32List(); + arrayVal[0] = 1; + msgAllTypes.setRepeatedUint32List(arrayVal); + msgPackedTypes.setPackedUint64List([1]); + arrayVal = msgPackedTypes.getPackedUint64List(); + arrayVal[0] = 1; + msgPackedTypes.setPackedUint64List(arrayVal); + msgAllTypes.setRepeatedUint64List([1]); + arrayVal = msgAllTypes.getRepeatedUint64List(); + arrayVal[0] = 1; + msgAllTypes.setRepeatedUint64List(arrayVal); + + let s = ''; + s += msgAllTypes.getOptionalBool() || false; + s += msgAllTypes.getOptionalBytes_asB64() || ''; + // s += msgAllTypes.getOptionalBytes_asU8() || new Uint8Array([]); + s += msgAllTypes.getOptionalDouble() || 0.0; + s += msgAllTypes.getOptionalFixed32() || 0; + s += msgAllTypes.getOptionalFixed64() || 0; + s += msgAllTypes.getOptionalFloat() || 0.0; + s += msgAllTypes.getOptionalInt32() || 0; + s += msgAllTypes.getOptionalInt64() || 0; + // s += msgAllTypes.getOptionalForeignEnum() || ForeignEnum.FOREIGN_BAR; + s += msgAllTypes.getOptionalForeignMessage(); + s += msgAllTypes.getOptionalSfixed32() || 0; + s += msgAllTypes.getOptionalSfixed64() || 0; + s += msgAllTypes.getOptionalSint32() || 0; + s += msgAllTypes.getOptionalSint64() || 0; + s += msgAllTypes.getOptionalString() || ''; + s += msgAllTypes.getOptionalUint32() || 0; + s += msgAllTypes.getOptionalUint64() || 0; + s += msgAllTypes.getRepeatedBoolList(); + s += msgAllTypes.getRepeatedBoolList()[0]; + s += msgAllTypes.getRepeatedBoolList().length; + s += msgAllTypes.getRepeatedBytesList_asB64(); + s += msgAllTypes.getRepeatedBytesList_asB64()[0]; + s += msgAllTypes.getRepeatedBytesList_asB64().length; + s += msgAllTypes.getRepeatedBytesList_asU8(); + s += msgAllTypes.getRepeatedDoubleList(); + s += msgAllTypes.getRepeatedDoubleList()[0]; + s += msgAllTypes.getRepeatedDoubleList().length; + s += msgAllTypes.getRepeatedFixed32List(); + s += msgAllTypes.getRepeatedFixed32List()[0]; + s += msgAllTypes.getRepeatedFixed32List().length; + s += msgAllTypes.getRepeatedFixed64List(); + s += msgAllTypes.getRepeatedFixed64List()[0]; + s += msgAllTypes.getRepeatedFixed64List().length; + s += msgAllTypes.getRepeatedFloatList(); + s += msgAllTypes.getRepeatedFloatList()[0]; + s += msgAllTypes.getRepeatedFloatList().length; + s += msgAllTypes.getRepeatedInt32List(); + s += msgAllTypes.getRepeatedInt32List()[0]; + s += msgAllTypes.getRepeatedInt32List().length; + s += msgAllTypes.getRepeatedInt64List(); + s += msgAllTypes.getRepeatedInt64List()[0]; + s += msgAllTypes.getRepeatedInt64List().length; + // s += msgAllTypes.getRepeatedForeignEnumList(); + // s += msgAllTypes.getRepeatedForeignEnumList()[0]; + // s += msgAllTypes.getRepeatedForeignEnumList().length; + s += msgAllTypes.getRepeatedForeignMessageList(); + s += msgAllTypes.getRepeatedForeignMessageList()[0]; + s += msgAllTypes.getRepeatedForeignMessageList().length; + s += msgAllTypes.getRepeatedSfixed32List(); + s += msgAllTypes.getRepeatedSfixed32List()[0]; + s += msgAllTypes.getRepeatedSfixed32List().length; + s += msgAllTypes.getRepeatedSfixed64List(); + s += msgAllTypes.getRepeatedSfixed64List()[0]; + s += msgAllTypes.getRepeatedSfixed64List().length; + s += msgAllTypes.getRepeatedSint32List(); + s += msgAllTypes.getRepeatedSint32List()[0]; + s += msgAllTypes.getRepeatedSint32List().length; + s += msgAllTypes.getRepeatedSint64List(); + s += msgAllTypes.getRepeatedSint64List()[0]; + s += msgAllTypes.getRepeatedSint64List().length; + s += msgAllTypes.getRepeatedStringList(); + s += msgAllTypes.getRepeatedStringList()[0]; + s += msgAllTypes.getRepeatedStringList().length; + s += msgAllTypes.getRepeatedUint32List(); + s += msgAllTypes.getRepeatedUint32List()[0]; + s += msgAllTypes.getRepeatedUint32List().length; + s += msgAllTypes.getRepeatedUint64List(); + s += msgAllTypes.getRepeatedUint64List()[0]; + s += msgAllTypes.getRepeatedUint64List().length; + + s += msgAllTypes.serialize(); + s += msgPackedTypes.serialize(); + + return s; +} + +goog.global['__hiddenTest'] += accessAllTypes(); diff --git a/tools/env-vars-generator/protobuf/js/experimental/benchmarks/code_size/apps_jspb/popular_types_proto3.js b/tools/env-vars-generator/protobuf/js/experimental/benchmarks/code_size/apps_jspb/popular_types_proto3.js new file mode 100644 index 0000000..9b80428 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/experimental/benchmarks/code_size/apps_jspb/popular_types_proto3.js @@ -0,0 +1,53 @@ +/** + * @fileoverview The code size benchmark of apps JSPB for proto3 popular types. + */ +goog.module('protobuf.benchmark.code_size.apps_jspb.PopularTypesProto3'); + +// const ForeignEnum = goog.require('proto.proto3_unittest.ForeignEnum'); +const ForeignMessage = goog.require('proto.proto3_unittest.ForeignMessage'); +const TestAllTypes = goog.require('proto.proto3_unittest.TestAllTypes'); +const {ensureCommonBaseLine} = goog.require('protobuf.benchmark.codeSize.codeSizeBase'); + +ensureCommonBaseLine(); + +/** + * @return {string} + */ +function accessPopularTypes() { + const msgAllTypes = TestAllTypes.deserialize(''); + msgAllTypes.addRepeatedForeignMessage(ForeignMessage.deserialize(''), 1); + [ForeignMessage.deserialize('')].forEach( + (e) => msgAllTypes.addRepeatedForeignMessage(e)); + + msgAllTypes.setOptionalString(''); + msgAllTypes.setOptionalInt32(1); + msgAllTypes.setOptionalForeignMessage(ForeignMessage.deserialize('')); + msgAllTypes.setOptionalBool(true); + // msgAllTypes.setOptionalForeignEnum(ForeignEnum.FOREIGN_BAR); + msgAllTypes.setOptionalInt64(1); + msgAllTypes.setOptionalDouble(1.0); + msgAllTypes.setRepeatedForeignMessageList([ForeignMessage.deserialize('')]); + let arrayVal = msgAllTypes.getRepeatedForeignMessageList(); + arrayVal[0] = ForeignMessage.deserialize(''); + msgAllTypes.setRepeatedForeignMessageList(arrayVal); + msgAllTypes.setOptionalUint64(1); + + let s = ''; + s += msgAllTypes.getOptionalString(); + s += msgAllTypes.getOptionalInt32(); + s += msgAllTypes.getOptionalForeignMessage(); + s += msgAllTypes.getOptionalBool(); + // s += msgAllTypes.getOptionalForeignEnum(); + s += msgAllTypes.getOptionalInt64(); + s += msgAllTypes.getOptionalDouble(); + s += msgAllTypes.getRepeatedForeignMessageList(); + s += msgAllTypes.getRepeatedForeignMessageList()[0]; + s += msgAllTypes.getRepeatedForeignMessageList().length; + s += msgAllTypes.getOptionalUint64(); + + s += msgAllTypes.serialize(); + + return s; +} + +goog.global['__hiddenTest'] += accessPopularTypes(); diff --git a/tools/env-vars-generator/protobuf/js/experimental/benchmarks/code_size/code_size_base.js b/tools/env-vars-generator/protobuf/js/experimental/benchmarks/code_size/code_size_base.js new file mode 100644 index 0000000..04f6a47 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/experimental/benchmarks/code_size/code_size_base.js @@ -0,0 +1,57 @@ +/** + * @fileoverview Ensures types are live that would be live in a typical g3 + * JS program. + * + * Making certain constructs live ensures that we compare against the same + * baseline for all code size benchmarks. This increases the size + * of our benchmarks, but note that this size in a regular app would be + * attributes to other places. + */ +goog.module('protobuf.benchmark.codeSize.codeSizeBase'); + + +/** + * Ensures that the array iterator polyfill is live. + * @return {string} + */ +function useArrayIterator() { + let a = []; + let s = ''; + for (let value of a) { + s += value; + } + return s; +} + +/** + * Ensures that the symbol iterator polyfill is live. + * @return {string} + */ +function useSymbolIterator() { + /** + * @implements {Iterable} + */ + class Foo { + /** @return {!Iterator} */ + [Symbol.iterator]() {} + } + + let foo = new Foo(); + let s = ''; + for (let value of foo) { + s += value; + } + return s; +} + +/** + * Ensures certain base libs are live so we can have an apples to apples + * comparison for code size of different implementations + */ +function ensureCommonBaseLine() { + goog.global['__hiddenTest'] += useArrayIterator(); + goog.global['__hiddenTest'] += useSymbolIterator(); +} + + +exports = {ensureCommonBaseLine}; diff --git a/tools/env-vars-generator/protobuf/js/experimental/benchmarks/code_size/kernel/popular_types.js b/tools/env-vars-generator/protobuf/js/experimental/benchmarks/code_size/kernel/popular_types.js new file mode 100644 index 0000000..90e1792 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/experimental/benchmarks/code_size/kernel/popular_types.js @@ -0,0 +1,68 @@ +/** + * @fileoverview The code size benchmark of binary kernel for accessing all + * popular types setter and getter. + * + * The types are those whose usage are more than 1%: + * + * ('STRING__LABEL_OPTIONAL', '29.7214%') + * ('INT32__LABEL_OPTIONAL', '17.7277%') + * ('MESSAGE__LABEL_OPTIONAL', '15.6462%') + * ('BOOL__LABEL_OPTIONAL', '13.0038%') + * ('ENUM__LABEL_OPTIONAL', '11.4466%') + * ('INT64__LABEL_OPTIONAL', '3.2198%') + * ('DOUBLE__LABEL_OPTIONAL', '1.357%') + * ('MESSAGE__LABEL_REPEATED', '1.2775%') + * ('FIXED32__LABEL_REQUIRED', '1.2%') + * ('UINT64__LABEL_OPTIONAL', '1.1771%') + * ('STRING__LABEL_REQUIRED', '1.0785%') + * + */ +goog.module('protobuf.benchmark.KernelCodeSizeBenchmarkPopularTypes'); + +const Int64 = goog.require('protobuf.Int64'); +const Kernel = goog.require('protobuf.runtime.Kernel'); +const TestMessage = goog.require('protobuf.testing.binary.TestMessage'); +const {ensureCommonBaseLine} = goog.require('protobuf.benchmark.codeSize.codeSizeBase'); + +ensureCommonBaseLine(); + + +/** + * @return {string} + */ +function accessAllTypes() { + const message = new TestMessage(Kernel.createEmpty()); + + message.addRepeatedMessageElement(1, message, TestMessage.instanceCreator); + message.addRepeatedMessageIterable(1, [message], TestMessage.instanceCreator); + + message.setString(1, 'abc'); + message.setInt32(1, 1); + message.setMessage(1, message); + message.setBool(1, true); + message.setInt64(1, Int64.fromBits(0, 1)); + message.setDouble(1, 1.0); + message.setRepeatedMessageElement(1, message, TestMessage.instanceCreator, 0); + message.setRepeatedMessageIterable(1, [message]); + message.setUint64(1, Int64.fromBits(0, 1)); + + + let s = ''; + s += message.getStringWithDefault(1); + s += message.getInt32WithDefault(1); + s += message.getMessage(1, TestMessage.instanceCreator); + s += message.getMessageOrNull(1, TestMessage.instanceCreator); + s += message.getBoolWithDefault(1); + s += message.getInt64WithDefault(1); + s += message.getDoubleWithDefault(1); + s += message.getRepeatedMessageElement(1, TestMessage.instanceCreator, 0); + s += message.getRepeatedMessageIterable(1, TestMessage.instanceCreator); + s += message.getRepeatedMessageSize(1, TestMessage.instanceCreator); + s += message.getUint64WithDefault(1); + + s += message.serialize(); + + return s; +} + +goog.global['__hiddenTest'] += accessAllTypes(); diff --git a/tools/env-vars-generator/protobuf/js/experimental/runtime/bytestring.js b/tools/env-vars-generator/protobuf/js/experimental/runtime/bytestring.js new file mode 100644 index 0000000..d6af5f1 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/experimental/runtime/bytestring.js @@ -0,0 +1,183 @@ +/** + * @fileoverview Provides ByteString as a basic data type for protos. + */ +goog.module('protobuf.ByteString'); + +const base64 = goog.require('goog.crypt.base64'); +const {arrayBufferSlice, cloneArrayBufferView, hashUint8Array, uint8ArrayEqual} = goog.require('protobuf.binary.typedArrays'); + +/** + * Immutable sequence of bytes. + * + * Bytes can be obtained as an ArrayBuffer or a base64 encoded string. + * @final + */ +class ByteString { + /** + * @param {?Uint8Array} bytes + * @param {?string} base64 + * @private + */ + constructor(bytes, base64) { + /** @private {?Uint8Array}*/ + this.bytes_ = bytes; + /** @private {?string} */ + this.base64_ = base64; + /** @private {number} */ + this.hashCode_ = 0; + } + + /** + * Constructs a ByteString instance from a base64 string. + * @param {string} value + * @return {!ByteString} + */ + static fromBase64String(value) { + if (value == null) { + throw new Error('value must not be null'); + } + return new ByteString(/* bytes */ null, value); + } + + /** + * Constructs a ByteString from an array buffer. + * @param {!ArrayBuffer} bytes + * @param {number=} start + * @param {number=} end + * @return {!ByteString} + */ + static fromArrayBuffer(bytes, start = 0, end = undefined) { + return new ByteString( + new Uint8Array(arrayBufferSlice(bytes, start, end)), /* base64 */ null); + } + + /** + * Constructs a ByteString from any ArrayBufferView (e.g. DataView, + * TypedArray, Uint8Array, etc.). + * @param {!ArrayBufferView} bytes + * @return {!ByteString} + */ + static fromArrayBufferView(bytes) { + return new ByteString(cloneArrayBufferView(bytes), /* base64 */ null); + } + + /** + * Constructs a ByteString from an Uint8Array. DON'T MODIFY the underlying + * ArrayBuffer, since the ByteString directly uses it without making a copy. + * + * This method exists so that internal APIs can construct a ByteString without + * paying the penalty of copying an ArrayBuffer when that ArrayBuffer is not + * supposed to change. It is exposed to a limited number of internal classes + * through bytestring_internal.js. + * + * @param {!Uint8Array} bytes + * @return {!ByteString} + * @package + */ + static fromUint8ArrayUnsafe(bytes) { + return new ByteString(bytes, /* base64 */ null); + } + + /** + * Returns this ByteString as an ArrayBuffer. + * @return {!ArrayBuffer} + */ + toArrayBuffer() { + const bytes = this.ensureBytes_(); + return arrayBufferSlice( + bytes.buffer, bytes.byteOffset, bytes.byteOffset + bytes.byteLength); + } + + /** + * Returns this ByteString as an Uint8Array. DON'T MODIFY the returned array, + * since the ByteString holds the reference to the same array. + * + * This method exists so that internal APIs can get contents of a ByteString + * without paying the penalty of copying an ArrayBuffer. It is exposed to a + * limited number of internal classes through bytestring_internal.js. + * @return {!Uint8Array} + * @package + */ + toUint8ArrayUnsafe() { + return this.ensureBytes_(); + } + + /** + * Returns this ByteString as a base64 encoded string. + * @return {string} + */ + toBase64String() { + return this.ensureBase64String_(); + } + + /** + * Returns true for Bytestrings that contain identical values. + * @param {*} other + * @return {boolean} + */ + equals(other) { + if (this === other) { + return true; + } + + if (!(other instanceof ByteString)) { + return false; + } + + const otherByteString = /** @type {!ByteString} */ (other); + return uint8ArrayEqual(this.ensureBytes_(), otherByteString.ensureBytes_()); + } + + /** + * Returns a number (int32) that is suitable for using in hashed structures. + * @return {number} + */ + hashCode() { + if (this.hashCode_ == 0) { + this.hashCode_ = hashUint8Array(this.ensureBytes_()); + } + return this.hashCode_; + } + + /** + * Returns true if the bytestring is empty. + * @return {boolean} + */ + isEmpty() { + if (this.bytes_ != null && this.bytes_.byteLength == 0) { + return true; + } + if (this.base64_ != null && this.base64_.length == 0) { + return true; + } + return false; + } + + /** + * @return {!Uint8Array} + * @private + */ + ensureBytes_() { + if (this.bytes_) { + return this.bytes_; + } + return this.bytes_ = base64.decodeStringToUint8Array( + /** @type {string} */ (this.base64_)); + } + + /** + * @return {string} + * @private + */ + ensureBase64String_() { + if (this.base64_ == null) { + this.base64_ = base64.encodeByteArray(this.bytes_); + } + return this.base64_; + } +} + +/** @const {!ByteString} */ +ByteString.EMPTY = new ByteString(new Uint8Array(0), null); + +exports = ByteString; diff --git a/tools/env-vars-generator/protobuf/js/experimental/runtime/int64.js b/tools/env-vars-generator/protobuf/js/experimental/runtime/int64.js new file mode 100644 index 0000000..45585b7 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/experimental/runtime/int64.js @@ -0,0 +1,403 @@ +/** + * @fileoverview Protobufs Int64 representation. + */ +goog.module('protobuf.Int64'); + +const Long = goog.require('goog.math.Long'); +const {assert} = goog.require('goog.asserts'); + +/** + * A container for protobufs Int64/Uint64 data type. + * @final + */ +class Int64 { + /** @return {!Int64} */ + static getZero() { + return ZERO; + } + + /** @return {!Int64} */ + static getMinValue() { + return MIN_VALUE; + } + + /** @return {!Int64} */ + static getMaxValue() { + return MAX_VALUE; + } + + /** + * Constructs a Int64 given two 32 bit numbers + * @param {number} lowBits + * @param {number} highBits + * @return {!Int64} + */ + static fromBits(lowBits, highBits) { + return new Int64(lowBits, highBits); + } + + /** + * Constructs an Int64 from a signed 32 bit number. + * @param {number} value + * @return {!Int64} + */ + static fromInt(value) { + // TODO: Use our own checking system here. + assert(value === (value | 0), 'value should be a 32-bit integer'); + // Right shift 31 bits so all high bits are equal to the sign bit. + // Note: cannot use >> 32, because (1 >> 32) = 1 (!). + const signExtendedHighBits = value >> 31; + return new Int64(value, signExtendedHighBits); + } + + /** + * Constructs an Int64 from a number (over 32 bits). + * @param {number} value + * @return {!Int64} + */ + static fromNumber(value) { + if (value > 0) { + return new Int64(value, value / TWO_PWR_32_DBL); + } else if (value < 0) { + return negate(-value, -value / TWO_PWR_32_DBL); + } + return ZERO; + } + + /** + * Construct an Int64 from a signed decimal string. + * @param {string} value + * @return {!Int64} + */ + static fromDecimalString(value) { + // TODO: Use our own checking system here. + assert(value.length > 0); + // The basic Number conversion loses precision, but we can use it for + // a quick validation that the format is correct and it is an integer. + assert(Math.floor(Number(value)).toString().length == value.length); + return decimalStringToInt64(value); + } + + /** + * Construct an Int64 from a signed hexadecimal string. + * @param {string} value + * @return {!Int64} + */ + static fromHexString(value) { + // TODO: Use our own checking system here. + assert(value.length > 0); + assert(value.slice(0, 2) == '0x' || value.slice(0, 3) == '-0x'); + const minus = value[0] === '-'; + // Strip the 0x or -0x prefix. + value = value.slice(minus ? 3 : 2); + const lowBits = parseInt(value.slice(-8), 16); + const highBits = parseInt(value.slice(-16, -8) || '', 16); + return (minus ? negate : Int64.fromBits)(lowBits, highBits); + } + + // Note to the reader: + // goog.math.Long suffers from a code size issue. JsCompiler almost always + // considers toString methods to be alive in a program. So if you are + // constructing a Long instance the toString method is assumed to be live. + // Unfortunately Long's toString method makes a large chunk of code alive + // of the entire class adding 1.3kB (gzip) of extra code size. + // Callers that are sensitive to code size and are not using Long already + // should avoid calling this method. + /** + * Creates an Int64 instance from a Long value. + * @param {!Long} value + * @return {!Int64} + */ + static fromLong(value) { + return new Int64(value.getLowBits(), value.getHighBits()); + } + + /** + * @param {number} lowBits + * @param {number} highBits + * @private + */ + constructor(lowBits, highBits) { + /** @const @private {number} */ + this.lowBits_ = lowBits | 0; + /** @const @private {number} */ + this.highBits_ = highBits | 0; + } + + /** + * Returns the int64 value as a JavaScript number. This will lose precision + * if the number is outside of the safe range for JavaScript of 53 bits + * precision. + * @return {number} + */ + asNumber() { + const result = this.highBits_ * TWO_PWR_32_DBL + this.getLowBitsUnsigned(); + // TODO: Use our own checking system here. + assert( + Number.isSafeInteger(result), 'conversion to number loses precision.'); + return result; + } + + // Note to the reader: + // goog.math.Long suffers from a code size issue. JsCompiler almost always + // considers toString methods to be alive in a program. So if you are + // constructing a Long instance the toString method is assumed to be live. + // Unfortunately Long's toString method makes a large chunk of code alive + // of the entire class adding 1.3kB (gzip) of extra code size. + // Callers that are sensitive to code size and are not using Long already + // should avoid calling this method. + /** @return {!Long} */ + asLong() { + return Long.fromBits(this.lowBits_, this.highBits_); + } + + /** @return {number} Signed 32-bit integer value. */ + getLowBits() { + return this.lowBits_; + } + + /** @return {number} Signed 32-bit integer value. */ + getHighBits() { + return this.highBits_; + } + + /** @return {number} Unsigned 32-bit integer. */ + getLowBitsUnsigned() { + return this.lowBits_ >>> 0; + } + + /** @return {number} Unsigned 32-bit integer. */ + getHighBitsUnsigned() { + return this.highBits_ >>> 0; + } + + /** @return {string} */ + toSignedDecimalString() { + return joinSignedDecimalString(this); + } + + /** @return {string} */ + toUnsignedDecimalString() { + return joinUnsignedDecimalString(this); + } + + /** + * Returns an unsigned hexadecimal string representation of the Int64. + * @return {string} + */ + toHexString() { + let nibbles = new Array(16); + let lowBits = this.lowBits_; + let highBits = this.highBits_; + for (let highIndex = 7, lowIndex = 15; lowIndex > 7; + highIndex--, lowIndex--) { + nibbles[highIndex] = HEX_DIGITS[highBits & 0xF]; + nibbles[lowIndex] = HEX_DIGITS[lowBits & 0xF]; + highBits = highBits >>> 4; + lowBits = lowBits >>> 4; + } + // Always leave the least significant hex digit. + while (nibbles.length > 1 && nibbles[0] == '0') { + nibbles.shift(); + } + return `0x${nibbles.join('')}`; + } + + /** + * @param {*} other object to compare against. + * @return {boolean} Whether this Int64 equals the other. + */ + equals(other) { + if (this === other) { + return true; + } + if (!(other instanceof Int64)) { + return false; + } + // Compare low parts first as there is higher chance they are different. + const otherInt64 = /** @type{!Int64} */ (other); + return (this.lowBits_ === otherInt64.lowBits_) && + (this.highBits_ === otherInt64.highBits_); + } + + /** + * Returns a number (int32) that is suitable for using in hashed structures. + * @return {number} + */ + hashCode() { + return (31 * this.lowBits_ + 17 * this.highBits_) | 0; + } +} + +/** + * Losslessly converts a 64-bit unsigned integer in 32:32 split representation + * into a decimal string. + * @param {!Int64} int64 + * @return {string} The binary number represented as a string. + */ +const joinUnsignedDecimalString = (int64) => { + const lowBits = int64.getLowBitsUnsigned(); + const highBits = int64.getHighBitsUnsigned(); + // Skip the expensive conversion if the number is small enough to use the + // built-in conversions. + // Number.MAX_SAFE_INTEGER = 0x001FFFFF FFFFFFFF, thus any number with + // highBits <= 0x1FFFFF can be safely expressed with a double and retain + // integer precision. + // Proven by: Number.isSafeInteger(0x1FFFFF * 2**32 + 0xFFFFFFFF) == true. + if (highBits <= 0x1FFFFF) { + return String(TWO_PWR_32_DBL * highBits + lowBits); + } + + // What this code is doing is essentially converting the input number from + // base-2 to base-1e7, which allows us to represent the 64-bit range with + // only 3 (very large) digits. Those digits are then trivial to convert to + // a base-10 string. + + // The magic numbers used here are - + // 2^24 = 16777216 = (1,6777216) in base-1e7. + // 2^48 = 281474976710656 = (2,8147497,6710656) in base-1e7. + + // Split 32:32 representation into 16:24:24 representation so our + // intermediate digits don't overflow. + const low = lowBits & LOW_24_BITS; + const mid = ((lowBits >>> 24) | (highBits << 8)) & LOW_24_BITS; + const high = (highBits >> 16) & LOW_16_BITS; + + // Assemble our three base-1e7 digits, ignoring carries. The maximum + // value in a digit at this step is representable as a 48-bit integer, which + // can be stored in a 64-bit floating point number. + let digitA = low + (mid * 6777216) + (high * 6710656); + let digitB = mid + (high * 8147497); + let digitC = (high * 2); + + // Apply carries from A to B and from B to C. + const base = 10000000; + if (digitA >= base) { + digitB += Math.floor(digitA / base); + digitA %= base; + } + + if (digitB >= base) { + digitC += Math.floor(digitB / base); + digitB %= base; + } + + // If digitC is 0, then we should have returned in the trivial code path + // at the top for non-safe integers. Given this, we can assume both digitB + // and digitA need leading zeros. + // TODO: Use our own checking system here. + assert(digitC); + return digitC + decimalFrom1e7WithLeadingZeros(digitB) + + decimalFrom1e7WithLeadingZeros(digitA); +}; + +/** + * @param {number} digit1e7 Number < 1e7 + * @return {string} Decimal representation of digit1e7 with leading zeros. + */ +const decimalFrom1e7WithLeadingZeros = (digit1e7) => { + const partial = String(digit1e7); + return '0000000'.slice(partial.length) + partial; +}; + +/** + * Losslessly converts a 64-bit signed integer in 32:32 split representation + * into a decimal string. + * @param {!Int64} int64 + * @return {string} The binary number represented as a string. + */ +const joinSignedDecimalString = (int64) => { + // If we're treating the input as a signed value and the high bit is set, do + // a manual two's complement conversion before the decimal conversion. + const negative = (int64.getHighBits() & 0x80000000); + if (negative) { + int64 = negate(int64.getLowBits(), int64.getHighBits()); + } + + const result = joinUnsignedDecimalString(int64); + return negative ? '-' + result : result; +}; + +/** + * @param {string} dec + * @return {!Int64} + */ +const decimalStringToInt64 = (dec) => { + // Check for minus sign. + const minus = dec[0] === '-'; + if (minus) { + dec = dec.slice(1); + } + + // Work 6 decimal digits at a time, acting like we're converting base 1e6 + // digits to binary. This is safe to do with floating point math because + // Number.isSafeInteger(ALL_32_BITS * 1e6) == true. + const base = 1e6; + let lowBits = 0; + let highBits = 0; + function add1e6digit(begin, end = undefined) { + // Note: Number('') is 0. + const digit1e6 = Number(dec.slice(begin, end)); + highBits *= base; + lowBits = lowBits * base + digit1e6; + // Carry bits from lowBits to + if (lowBits >= TWO_PWR_32_DBL) { + highBits = highBits + ((lowBits / TWO_PWR_32_DBL) | 0); + lowBits = lowBits % TWO_PWR_32_DBL; + } + } + add1e6digit(-24, -18); + add1e6digit(-18, -12); + add1e6digit(-12, -6); + add1e6digit(-6); + + return (minus ? negate : Int64.fromBits)(lowBits, highBits); +}; + +/** + * @param {number} lowBits + * @param {number} highBits + * @return {!Int64} Two's compliment negation of input. + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Signed_32-bit_integers + */ +const negate = (lowBits, highBits) => { + highBits = ~highBits; + if (lowBits) { + lowBits = ~lowBits + 1; + } else { + // If lowBits is 0, then bitwise-not is 0xFFFFFFFF, + // adding 1 to that, results in 0x100000000, which leaves + // the low bits 0x0 and simply adds one to the high bits. + highBits += 1; + } + return Int64.fromBits(lowBits, highBits); +}; + +/** @const {!Int64} */ +const ZERO = new Int64(0, 0); + +/** @const @private {number} */ +const LOW_16_BITS = 0xFFFF; + +/** @const @private {number} */ +const LOW_24_BITS = 0xFFFFFF; + +/** @const @private {number} */ +const LOW_31_BITS = 0x7FFFFFFF; + +/** @const @private {number} */ +const ALL_32_BITS = 0xFFFFFFFF; + +/** @const {!Int64} */ +const MAX_VALUE = Int64.fromBits(ALL_32_BITS, LOW_31_BITS); + +/** @const {!Int64} */ +const MIN_VALUE = Int64.fromBits(0, 0x80000000); + +/** @const {number} */ +const TWO_PWR_32_DBL = 0x100000000; + +/** @const {string} */ +const HEX_DIGITS = '0123456789abcdef'; + +exports = Int64; diff --git a/tools/env-vars-generator/protobuf/js/experimental/runtime/internal/checks.js b/tools/env-vars-generator/protobuf/js/experimental/runtime/internal/checks.js new file mode 100644 index 0000000..3d1af54 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/experimental/runtime/internal/checks.js @@ -0,0 +1,708 @@ +/** + * @fileoverview Proto internal runtime checks. + * + * Checks are grouped into different severity, see: + * http://g3doc/third_party/protobuf/javascript/README.md#configurable-check-support-in-protocol-buffers + * + * Checks are also grouped into different sections: + * - CHECK_BOUNDS: + * Checks that ensure that indexed access is within bounds + * (e.g. an array being accessed past its size). + * - CHECK_STATE + * Checks related to the state of an object + * (e.g. a parser hitting an invalid case). + * - CHECK_TYPE: + * Checks that relate to type errors (e.g. code receives a number instead + * of a string). + */ +goog.module('protobuf.internal.checks'); + +const ByteString = goog.require('protobuf.ByteString'); +const Int64 = goog.require('protobuf.Int64'); +const WireType = goog.require('protobuf.binary.WireType'); + +// +// See +// http://g3doc/third_party/protobuf/javascript/README.md#configurable-check-support-in-protocol-buffers +// +/** @define{string} */ +const CHECK_LEVEL_DEFINE = goog.define('protobuf.defines.CHECK_LEVEL', ''); + +/** @define{boolean} */ +const POLYFILL_TEXT_ENCODING = + goog.define('protobuf.defines.POLYFILL_TEXT_ENCODING', true); + +/** + * @const {number} + */ +const MAX_FIELD_NUMBER = Math.pow(2, 29) - 1; + +/** + * The largest finite float32 value. + * @const {number} + */ +const FLOAT32_MAX = 3.4028234663852886e+38; + +/** @enum {number} */ +const CheckLevel = { + DEBUG: 0, + CRITICAL: 1, + OFF: 2 +}; + + +/** @return {!CheckLevel} */ +function calculateCheckLevel() { + const definedLevel = CHECK_LEVEL_DEFINE.toUpperCase(); + if (definedLevel === '') { + // user did not set a value, value now just depends on goog.DEBUG + return goog.DEBUG ? CheckLevel.DEBUG : CheckLevel.CRITICAL; + } + + if (definedLevel === 'CRITICAL') { + return CheckLevel.CRITICAL; + } + + if (definedLevel === 'OFF') { + return CheckLevel.OFF; + } + + if (definedLevel === 'DEBUG') { + return CheckLevel.DEBUG; + } + + throw new Error(`Unknown value for CHECK_LEVEL: ${CHECK_LEVEL_DEFINE}`); +} + +const /** !CheckLevel */ CHECK_LEVEL = calculateCheckLevel(); + +const /** boolean */ CHECK_STATE = CHECK_LEVEL === CheckLevel.DEBUG; + +const /** boolean */ CHECK_CRITICAL_STATE = + CHECK_LEVEL === CheckLevel.CRITICAL || CHECK_LEVEL === CheckLevel.DEBUG; + +const /** boolean */ CHECK_BOUNDS = CHECK_LEVEL === CheckLevel.DEBUG; + +const /** boolean */ CHECK_CRITICAL_BOUNDS = + CHECK_LEVEL === CheckLevel.CRITICAL || CHECK_LEVEL === CheckLevel.DEBUG; + +const /** boolean */ CHECK_TYPE = CHECK_LEVEL === CheckLevel.DEBUG; + +const /** boolean */ CHECK_CRITICAL_TYPE = + CHECK_LEVEL === CheckLevel.CRITICAL || CHECK_LEVEL === CheckLevel.DEBUG; + +/** + * Ensures the truth of an expression involving the state of the calling + * instance, but not involving any parameters to the calling method. + * + * For cases where failing fast is pretty important and not failing early could + * cause bugs that are much harder to debug. + * @param {boolean} state + * @param {string=} message + * @throws {!Error} If the state is false and the check state is critical. + */ +function checkCriticalState(state, message = '') { + if (!CHECK_CRITICAL_STATE) { + return; + } + if (!state) { + throw new Error(message); + } +} + +/** + * Ensures the truth of an expression involving the state of the calling + * instance, but not involving any parameters to the calling method. + * + * @param {boolean} state + * @param {string=} message + * @throws {!Error} If the state is false and the check state is debug. + */ +function checkState(state, message = '') { + if (!CHECK_STATE) { + return; + } + checkCriticalState(state, message); +} + +/** + * Ensures that `index` specifies a valid position in an indexable object of + * size `size`. A position index may range from zero to size, inclusive. + * @param {number} index + * @param {number} size + * @throws {!Error} If the index is out of range and the check state is debug. + */ +function checkPositionIndex(index, size) { + if (!CHECK_BOUNDS) { + return; + } + checkCriticalPositionIndex(index, size); +} + +/** + * Ensures that `index` specifies a valid position in an indexable object of + * size `size`. A position index may range from zero to size, inclusive. + * @param {number} index + * @param {number} size + * @throws {!Error} If the index is out of range and the check state is + * critical. + */ +function checkCriticalPositionIndex(index, size) { + if (!CHECK_CRITICAL_BOUNDS) { + return; + } + if (index < 0 || index > size) { + throw new Error(`Index out of bounds: index: ${index} size: ${size}`); + } +} + +/** + * Ensures that `index` specifies a valid element in an indexable object of + * size `size`. A element index may range from zero to size, exclusive. + * @param {number} index + * @param {number} size + * @throws {!Error} If the index is out of range and the check state is + * debug. + */ +function checkElementIndex(index, size) { + if (!CHECK_BOUNDS) { + return; + } + checkCriticalElementIndex(index, size); +} + +/** + * Ensures that `index` specifies a valid element in an indexable object of + * size `size`. A element index may range from zero to size, exclusive. + * @param {number} index + * @param {number} size + * @throws {!Error} If the index is out of range and the check state is + * critical. + */ +function checkCriticalElementIndex(index, size) { + if (!CHECK_CRITICAL_BOUNDS) { + return; + } + if (index < 0 || index >= size) { + throw new Error(`Index out of bounds: index: ${index} size: ${size}`); + } +} + +/** + * Ensures the range of [start, end) is with the range of [0, size). + * @param {number} start + * @param {number} end + * @param {number} size + * @throws {!Error} If start and end are out of range and the check state is + * debug. + */ +function checkRange(start, end, size) { + if (!CHECK_BOUNDS) { + return; + } + checkCriticalRange(start, end, size); +} + +/** + * Ensures the range of [start, end) is with the range of [0, size). + * @param {number} start + * @param {number} end + * @param {number} size + * @throws {!Error} If start and end are out of range and the check state is + * critical. + */ +function checkCriticalRange(start, end, size) { + if (!CHECK_CRITICAL_BOUNDS) { + return; + } + if (start < 0 || end < 0 || start > size || end > size) { + throw new Error(`Range error: start: ${start} end: ${end} size: ${size}`); + } + if (start > end) { + throw new Error(`Start > end: ${start} > ${end}`); + } +} + +/** + * Ensures that field number is an integer and within the range of + * [1, MAX_FIELD_NUMBER]. + * @param {number} fieldNumber + * @throws {!Error} If the field number is out of range and the check state is + * debug. + */ +function checkFieldNumber(fieldNumber) { + if (!CHECK_TYPE) { + return; + } + checkCriticalFieldNumber(fieldNumber); +} + +/** + * Ensures that the value is neither null nor undefined. + * + * @param {T} value + * @return {R} + * + * @template T + * @template R := + * mapunion(T, (V) => + * cond(eq(V, 'null'), + * none(), + * cond(eq(V, 'undefined'), + * none(), + * V))) + * =: + */ +function checkDefAndNotNull(value) { + if (CHECK_TYPE) { + // Note that undefined == null. + if (value == null) { + throw new Error(`Value can't be null`); + } + } + return value; +} + +/** + * Ensures that the value exists and is a function. + * + * @param {function(?): ?} func + */ +function checkFunctionExists(func) { + if (CHECK_TYPE) { + if (typeof func !== 'function') { + throw new Error(`${func} is not a function`); + } + } +} + +/** + * Ensures that field number is an integer and within the range of + * [1, MAX_FIELD_NUMBER]. + * @param {number} fieldNumber + * @throws {!Error} If the field number is out of range and the check state is + * critical. + */ +function checkCriticalFieldNumber(fieldNumber) { + if (!CHECK_CRITICAL_TYPE) { + return; + } + if (fieldNumber <= 0 || fieldNumber > MAX_FIELD_NUMBER) { + throw new Error(`Field number is out of range: ${fieldNumber}`); + } +} + +/** + * Ensures that wire type is valid. + * @param {!WireType} wireType + * @throws {!Error} If the wire type is invalid and the check state is debug. + */ +function checkWireType(wireType) { + if (!CHECK_TYPE) { + return; + } + checkCriticalWireType(wireType); +} + +/** + * Ensures that wire type is valid. + * @param {!WireType} wireType + * @throws {!Error} If the wire type is invalid and the check state is critical. + */ +function checkCriticalWireType(wireType) { + if (!CHECK_CRITICAL_TYPE) { + return; + } + if (wireType < WireType.VARINT || wireType > WireType.FIXED32) { + throw new Error(`Invalid wire type: ${wireType}`); + } +} + +/** + * Ensures the given value has the correct type. + * @param {boolean} expression + * @param {string} errorMsg + * @throws {!Error} If the value has the wrong type and the check state is + * critical. + */ +function checkCriticalType(expression, errorMsg) { + if (!CHECK_CRITICAL_TYPE) { + return; + } + if (!expression) { + throw new Error(errorMsg); + } +} + +/** + * Checks whether a given object is an array. + * @param {*} value + * @return {!Array<*>} + */ +function checkCriticalTypeArray(value) { + checkCriticalType( + Array.isArray(value), `Must be an array, but got: ${value}`); + return /** @type {!Array<*>} */ (value); +} + +/** + * Checks whether a given object is an iterable. + * @param {*} value + * @return {!Iterable<*>} + */ +function checkCriticalTypeIterable(value) { + checkCriticalType( + !!value[Symbol.iterator], `Must be an iterable, but got: ${value}`); + return /** @type {!Iterable<*>} */ (value); +} + +/** + * Checks whether a given object is a boolean. + * @param {*} value + */ +function checkCriticalTypeBool(value) { + checkCriticalType( + typeof value === 'boolean', `Must be a boolean, but got: ${value}`); +} + +/** + * Checks whether a given object is an array of boolean. + * @param {*} values + */ +function checkCriticalTypeBoolArray(values) { + // TODO(b/134765672) + if (!CHECK_CRITICAL_TYPE) { + return; + } + const array = checkCriticalTypeArray(values); + for (const value of array) { + checkCriticalTypeBool(value); + } +} + +/** + * Checks whether a given object is a ByteString. + * @param {*} value + */ +function checkCriticalTypeByteString(value) { + checkCriticalType( + value instanceof ByteString, `Must be a ByteString, but got: ${value}`); +} + +/** + * Checks whether a given object is an array of ByteString. + * @param {*} values + */ +function checkCriticalTypeByteStringArray(values) { + // TODO(b/134765672) + if (!CHECK_CRITICAL_TYPE) { + return; + } + const array = checkCriticalTypeArray(values); + for (const value of array) { + checkCriticalTypeByteString(value); + } +} + +/** + * Checks whether a given object is a number. + * @param {*} value + * @throws {!Error} If the value is not float and the check state is debug. + */ +function checkTypeDouble(value) { + if (!CHECK_TYPE) { + return; + } + checkCriticalTypeDouble(value); +} + +/** + * Checks whether a given object is a number. + * @param {*} value + * @throws {!Error} If the value is not float and the check state is critical. + */ +function checkCriticalTypeDouble(value) { + checkCriticalType( + typeof value === 'number', `Must be a number, but got: ${value}`); +} + +/** + * Checks whether a given object is an array of double. + * @param {*} values + */ +function checkCriticalTypeDoubleArray(values) { + // TODO(b/134765672) + if (!CHECK_CRITICAL_TYPE) { + return; + } + const array = checkCriticalTypeArray(values); + for (const value of array) { + checkCriticalTypeDouble(value); + } +} + +/** + * Checks whether a given object is a number. + * @param {*} value + * @throws {!Error} If the value is not signed int32 and the check state is + * debug. + */ +function checkTypeSignedInt32(value) { + if (!CHECK_TYPE) { + return; + } + checkCriticalTypeSignedInt32(value); +} + +/** + * Checks whether a given object is a number. + * @param {*} value + * @throws {!Error} If the value is not signed int32 and the check state is + * critical. + */ +function checkCriticalTypeSignedInt32(value) { + checkCriticalTypeDouble(value); + const valueAsNumber = /** @type {number} */ (value); + if (CHECK_CRITICAL_TYPE) { + if (valueAsNumber < -Math.pow(2, 31) || valueAsNumber > Math.pow(2, 31) || + !Number.isInteger(valueAsNumber)) { + throw new Error(`Must be int32, but got: ${valueAsNumber}`); + } + } +} + +/** + * Checks whether a given object is an array of numbers. + * @param {*} values + */ +function checkCriticalTypeSignedInt32Array(values) { + // TODO(b/134765672) + if (!CHECK_CRITICAL_TYPE) { + return; + } + const array = checkCriticalTypeArray(values); + for (const value of array) { + checkCriticalTypeSignedInt32(value); + } +} + +/** + * Ensures that value is a long instance. + * @param {*} value + * @throws {!Error} If the value is not a long instance and check state is + * debug. + */ +function checkTypeSignedInt64(value) { + if (!CHECK_TYPE) { + return; + } + checkCriticalTypeSignedInt64(value); +} + +/** + * Ensures that value is a long instance. + * @param {*} value + * @throws {!Error} If the value is not a long instance and check state is + * critical. + */ +function checkCriticalTypeSignedInt64(value) { + if (!CHECK_CRITICAL_TYPE) { + return; + } + if (!(value instanceof Int64)) { + throw new Error(`Must be Int64 instance, but got: ${value}`); + } +} + +/** + * Checks whether a given object is an array of long instances. + * @param {*} values + * @throws {!Error} If values is not an array of long instances. + */ +function checkCriticalTypeSignedInt64Array(values) { + // TODO(b/134765672) + if (!CHECK_CRITICAL_TYPE) { + return; + } + const array = checkCriticalTypeArray(values); + for (const value of array) { + checkCriticalTypeSignedInt64(value); + } +} + +/** + * Checks whether a given object is a number and within float32 precision. + * @param {*} value + * @throws {!Error} If the value is not float and the check state is debug. + */ +function checkTypeFloat(value) { + if (!CHECK_TYPE) { + return; + } + checkCriticalTypeFloat(value); +} + +/** + * Checks whether a given object is a number and within float32 precision. + * @param {*} value + * @throws {!Error} If the value is not float and the check state is critical. + */ +function checkCriticalTypeFloat(value) { + checkCriticalTypeDouble(value); + if (CHECK_CRITICAL_TYPE) { + const valueAsNumber = /** @type {number} */ (value); + if (Number.isFinite(valueAsNumber) && + (valueAsNumber > FLOAT32_MAX || valueAsNumber < -FLOAT32_MAX)) { + throw new Error( + `Given number does not fit into float precision: ${value}`); + } + } +} + +/** + * Checks whether a given object is an iterable of floats. + * @param {*} values + */ +function checkCriticalTypeFloatIterable(values) { + // TODO(b/134765672) + if (!CHECK_CRITICAL_TYPE) { + return; + } + const iterable = checkCriticalTypeIterable(values); + for (const value of iterable) { + checkCriticalTypeFloat(value); + } +} + +/** + * Checks whether a given object is a string. + * @param {*} value + */ +function checkCriticalTypeString(value) { + checkCriticalType( + typeof value === 'string', `Must be string, but got: ${value}`); +} + +/** + * Checks whether a given object is an array of string. + * @param {*} values + */ +function checkCriticalTypeStringArray(values) { + // TODO(b/134765672) + if (!CHECK_CRITICAL_TYPE) { + return; + } + const array = checkCriticalTypeArray(values); + for (const value of array) { + checkCriticalTypeString(value); + } +} + +/** + * Ensures that value is a valid unsigned int32. + * @param {*} value + * @throws {!Error} If the value is out of range and the check state is debug. + */ +function checkTypeUnsignedInt32(value) { + if (!CHECK_TYPE) { + return; + } + checkCriticalTypeUnsignedInt32(value); +} + +/** + * Ensures that value is a valid unsigned int32. + * @param {*} value + * @throws {!Error} If the value is out of range and the check state + * is critical. + */ +function checkCriticalTypeUnsignedInt32(value) { + if (!CHECK_CRITICAL_TYPE) { + return; + } + checkCriticalTypeDouble(value); + const valueAsNumber = /** @type {number} */ (value); + if (valueAsNumber < 0 || valueAsNumber > Math.pow(2, 32) - 1 || + !Number.isInteger(valueAsNumber)) { + throw new Error(`Must be uint32, but got: ${value}`); + } +} + +/** + * Checks whether a given object is an array of unsigned int32. + * @param {*} values + */ +function checkCriticalTypeUnsignedInt32Array(values) { + // TODO(b/134765672) + if (!CHECK_CRITICAL_TYPE) { + return; + } + const array = checkCriticalTypeArray(values); + for (const value of array) { + checkCriticalTypeUnsignedInt32(value); + } +} + +/** + * Checks whether a given object is an array of message. + * @param {*} values + */ +function checkCriticalTypeMessageArray(values) { + // TODO(b/134765672) + if (!CHECK_CRITICAL_TYPE) { + return; + } + const array = checkCriticalTypeArray(values); + for (const value of array) { + checkCriticalType( + value !== null, 'Given value is not a message instance: null'); + } +} + +exports = { + checkDefAndNotNull, + checkCriticalElementIndex, + checkCriticalFieldNumber, + checkCriticalPositionIndex, + checkCriticalRange, + checkCriticalState, + checkCriticalTypeBool, + checkCriticalTypeBoolArray, + checkCriticalTypeByteString, + checkCriticalTypeByteStringArray, + checkCriticalTypeDouble, + checkTypeDouble, + checkCriticalTypeDoubleArray, + checkTypeFloat, + checkCriticalTypeFloat, + checkCriticalTypeFloatIterable, + checkCriticalTypeMessageArray, + checkCriticalTypeSignedInt32, + checkCriticalTypeSignedInt32Array, + checkCriticalTypeSignedInt64, + checkTypeSignedInt64, + checkCriticalTypeSignedInt64Array, + checkCriticalTypeString, + checkCriticalTypeStringArray, + checkCriticalTypeUnsignedInt32, + checkCriticalTypeUnsignedInt32Array, + checkCriticalType, + checkCriticalWireType, + checkElementIndex, + checkFieldNumber, + checkFunctionExists, + checkPositionIndex, + checkRange, + checkState, + checkTypeUnsignedInt32, + checkTypeSignedInt32, + checkWireType, + CHECK_BOUNDS, + CHECK_CRITICAL_BOUNDS, + CHECK_STATE, + CHECK_CRITICAL_STATE, + CHECK_TYPE, + CHECK_CRITICAL_TYPE, + MAX_FIELD_NUMBER, + POLYFILL_TEXT_ENCODING, +}; diff --git a/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/bool_test_pairs.js b/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/bool_test_pairs.js new file mode 100644 index 0000000..4323f5b --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/bool_test_pairs.js @@ -0,0 +1,79 @@ +/** + * @fileoverview Test data for bool encoding and decoding. + */ +goog.module('protobuf.binary.boolTestPairs'); + +const BufferDecoder = goog.require('protobuf.binary.BufferDecoder'); +const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper'); + +/** + * An array of Pairs of boolean values and their bit representation. + * This is used to test encoding and decoding from/to the protobuf wire format. + * @return {!Array<{name: string, boolValue: boolean, bufferDecoder: + * !BufferDecoder, error: ?boolean, skip_writer: ?boolean}>} + */ +function getBoolPairs() { + const boolPairs = [ + { + name: 'true', + boolValue: true, + bufferDecoder: createBufferDecoder(0x01), + }, + { + name: 'false', + boolValue: false, + bufferDecoder: createBufferDecoder(0x00), + }, + { + name: 'two-byte true', + boolValue: true, + bufferDecoder: createBufferDecoder(0x80, 0x01), + skip_writer: true, + }, + { + name: 'two-byte false', + boolValue: false, + bufferDecoder: createBufferDecoder(0x80, 0x00), + skip_writer: true, + }, + { + name: 'minus one', + boolValue: true, + bufferDecoder: createBufferDecoder( + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01), + skip_writer: true, + }, + { + name: 'max signed int 2^63 - 1', + boolValue: true, + bufferDecoder: createBufferDecoder( + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F), + skip_writer: true, + }, + { + name: 'min signed int -2^63', + boolValue: true, + bufferDecoder: createBufferDecoder( + 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01), + skip_writer: true, + }, + { + name: 'overflowed but valid varint', + boolValue: false, + bufferDecoder: createBufferDecoder( + 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x02), + skip_writer: true, + }, + { + name: 'errors out for 11 bytes', + boolValue: true, + bufferDecoder: createBufferDecoder( + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF), + error: true, + skip_writer: true, + }, + ]; + return [...boolPairs]; +} + +exports = {getBoolPairs}; diff --git a/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/conformance/test_all_types_proto2.js b/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/conformance/test_all_types_proto2.js new file mode 100644 index 0000000..3be1bee --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/conformance/test_all_types_proto2.js @@ -0,0 +1,309 @@ +/** + * @fileoverview Handwritten code of TestAllTypesProto2. + */ +goog.module('proto.conformance.TestAllTypesProto2'); + +const InternalMessage = goog.require('protobuf.binary.InternalMessage'); +const Kernel = goog.require('protobuf.runtime.Kernel'); + +/** + * Handwritten code of conformance.TestAllTypesProto2. + * Check google/protobuf/test_messages_proto3.proto for more details. + * @implements {InternalMessage} + * @final + */ +class TestAllTypesProto2 { + /** + * @param {!Kernel=} accessor + * @private + */ + constructor(accessor = Kernel.createEmpty()) { + /** @private @const {!Kernel} */ + this.accessor_ = accessor; + } + + /** + * @override + * @package + * @return {!Kernel} + */ + internalGetKernel() { + return this.accessor_; + } + + /** + * Create a request instance with the given bytes data. + * If we directly use the accessor created by the binary decoding, the + * Kernel instance will only copy the same data over for encoding. By + * explicitly fetching data from the previous accessor and setting all fields + * into a new accessor, we will actually test encoding/decoding for the binary + * format. + * @param {!ArrayBuffer} bytes + * @return {!TestAllTypesProto2} + */ + static deserialize(bytes) { + const msg = new TestAllTypesProto2(); + const requestAccessor = Kernel.fromArrayBuffer(bytes); + + if (requestAccessor.hasFieldNumber(1)) { + const value = requestAccessor.getInt32WithDefault(1); + msg.accessor_.setInt32(1, value); + } + + if (requestAccessor.hasFieldNumber(2)) { + const value = requestAccessor.getInt64WithDefault(2); + msg.accessor_.setInt64(2, value); + } + + if (requestAccessor.hasFieldNumber(3)) { + const value = requestAccessor.getUint32WithDefault(3); + msg.accessor_.setUint32(3, value); + } + + if (requestAccessor.hasFieldNumber(4)) { + const value = requestAccessor.getUint64WithDefault(4); + msg.accessor_.setUint64(4, value); + } + + if (requestAccessor.hasFieldNumber(5)) { + const value = requestAccessor.getSint32WithDefault(5); + msg.accessor_.setSint32(5, value); + } + + if (requestAccessor.hasFieldNumber(6)) { + const value = requestAccessor.getSint64WithDefault(6); + msg.accessor_.setSint64(6, value); + } + + if (requestAccessor.hasFieldNumber(7)) { + const value = requestAccessor.getFixed32WithDefault(7); + msg.accessor_.setFixed32(7, value); + } + + if (requestAccessor.hasFieldNumber(8)) { + const value = requestAccessor.getFixed64WithDefault(8); + msg.accessor_.setFixed64(8, value); + } + + if (requestAccessor.hasFieldNumber(9)) { + const value = requestAccessor.getSfixed32WithDefault(9); + msg.accessor_.setSfixed32(9, value); + } + + if (requestAccessor.hasFieldNumber(10)) { + const value = requestAccessor.getSfixed64WithDefault(10); + msg.accessor_.setSfixed64(10, value); + } + + if (requestAccessor.hasFieldNumber(11)) { + const value = requestAccessor.getFloatWithDefault(11); + msg.accessor_.setFloat(11, value); + } + + if (requestAccessor.hasFieldNumber(12)) { + const value = requestAccessor.getDoubleWithDefault(12); + msg.accessor_.setDouble(12, value); + } + + if (requestAccessor.hasFieldNumber(13)) { + const value = requestAccessor.getBoolWithDefault(13); + msg.accessor_.setBool(13, value); + } + + if (requestAccessor.hasFieldNumber(14)) { + const value = requestAccessor.getStringWithDefault(14); + msg.accessor_.setString(14, value); + } + + if (requestAccessor.hasFieldNumber(15)) { + const value = requestAccessor.getBytesWithDefault(15); + msg.accessor_.setBytes(15, value); + } + + if (requestAccessor.hasFieldNumber(18)) { + const value = requestAccessor.getMessage( + 18, (accessor) => new TestAllTypesProto2(accessor)); + msg.accessor_.setMessage(18, value); + } + + if (requestAccessor.hasFieldNumber(21)) { + // Unknown enum is not checked here, because even if an enum is unknown, + // it should be kept during encoding. For the purpose of wire format test, + // we can simplify the implementation by treating it as an int32 field, + // which has the same semantic except for the unknown value checking. + const value = requestAccessor.getInt32WithDefault(21); + msg.accessor_.setInt32(21, value); + } + + if (requestAccessor.hasFieldNumber(31)) { + const value = requestAccessor.getRepeatedInt32Iterable(31); + msg.accessor_.setUnpackedInt32Iterable(31, value); + } + + if (requestAccessor.hasFieldNumber(32)) { + const value = requestAccessor.getRepeatedInt64Iterable(32); + msg.accessor_.setUnpackedInt64Iterable(32, value); + } + + if (requestAccessor.hasFieldNumber(33)) { + const value = requestAccessor.getRepeatedUint32Iterable(33); + msg.accessor_.setUnpackedUint32Iterable(33, value); + } + + if (requestAccessor.hasFieldNumber(34)) { + const value = requestAccessor.getRepeatedUint64Iterable(34); + msg.accessor_.setUnpackedUint64Iterable(34, value); + } + + if (requestAccessor.hasFieldNumber(35)) { + const value = requestAccessor.getRepeatedSint32Iterable(35); + msg.accessor_.setUnpackedSint32Iterable(35, value); + } + + if (requestAccessor.hasFieldNumber(36)) { + const value = requestAccessor.getRepeatedSint64Iterable(36); + msg.accessor_.setUnpackedSint64Iterable(36, value); + } + + if (requestAccessor.hasFieldNumber(37)) { + const value = requestAccessor.getRepeatedFixed32Iterable(37); + msg.accessor_.setUnpackedFixed32Iterable(37, value); + } + + if (requestAccessor.hasFieldNumber(38)) { + const value = requestAccessor.getRepeatedFixed64Iterable(38); + msg.accessor_.setUnpackedFixed64Iterable(38, value); + } + + if (requestAccessor.hasFieldNumber(39)) { + const value = requestAccessor.getRepeatedSfixed32Iterable(39); + msg.accessor_.setUnpackedSfixed32Iterable(39, value); + } + + if (requestAccessor.hasFieldNumber(40)) { + const value = requestAccessor.getRepeatedSfixed64Iterable(40); + msg.accessor_.setUnpackedSfixed64Iterable(40, value); + } + + if (requestAccessor.hasFieldNumber(41)) { + const value = requestAccessor.getRepeatedFloatIterable(41); + msg.accessor_.setUnpackedFloatIterable(41, value); + } + + if (requestAccessor.hasFieldNumber(42)) { + const value = requestAccessor.getRepeatedDoubleIterable(42); + msg.accessor_.setUnpackedDoubleIterable(42, value); + } + + if (requestAccessor.hasFieldNumber(43)) { + const value = requestAccessor.getRepeatedBoolIterable(43); + msg.accessor_.setUnpackedBoolIterable(43, value); + } + + if (requestAccessor.hasFieldNumber(44)) { + const value = requestAccessor.getRepeatedStringIterable(44); + msg.accessor_.setRepeatedStringIterable(44, value); + } + + if (requestAccessor.hasFieldNumber(45)) { + const value = requestAccessor.getRepeatedBytesIterable(45); + msg.accessor_.setRepeatedBytesIterable(45, value); + } + + if (requestAccessor.hasFieldNumber(48)) { + const value = requestAccessor.getRepeatedMessageIterable( + 48, (accessor) => new TestAllTypesProto2(accessor)); + msg.accessor_.setRepeatedMessageIterable(48, value); + } + + if (requestAccessor.hasFieldNumber(51)) { + // Unknown enum is not checked here, because even if an enum is unknown, + // it should be kept during encoding. For the purpose of wire format test, + // we can simplify the implementation by treating it as an int32 field, + // which has the same semantic except for the unknown value checking. + const value = requestAccessor.getRepeatedInt32Iterable(51); + msg.accessor_.setUnpackedInt32Iterable(51, value); + } + + if (requestAccessor.hasFieldNumber(75)) { + const value = requestAccessor.getRepeatedInt32Iterable(75); + msg.accessor_.setPackedInt32Iterable(75, value); + } + + if (requestAccessor.hasFieldNumber(76)) { + const value = requestAccessor.getRepeatedInt64Iterable(76); + msg.accessor_.setPackedInt64Iterable(76, value); + } + + if (requestAccessor.hasFieldNumber(77)) { + const value = requestAccessor.getRepeatedUint32Iterable(77); + msg.accessor_.setPackedUint32Iterable(77, value); + } + + if (requestAccessor.hasFieldNumber(78)) { + const value = requestAccessor.getRepeatedUint64Iterable(78); + msg.accessor_.setPackedUint64Iterable(78, value); + } + + if (requestAccessor.hasFieldNumber(79)) { + const value = requestAccessor.getRepeatedSint32Iterable(79); + msg.accessor_.setPackedSint32Iterable(79, value); + } + + if (requestAccessor.hasFieldNumber(80)) { + const value = requestAccessor.getRepeatedSint64Iterable(80); + msg.accessor_.setPackedSint64Iterable(80, value); + } + + if (requestAccessor.hasFieldNumber(81)) { + const value = requestAccessor.getRepeatedFixed32Iterable(81); + msg.accessor_.setPackedFixed32Iterable(81, value); + } + + if (requestAccessor.hasFieldNumber(82)) { + const value = requestAccessor.getRepeatedFixed64Iterable(82); + msg.accessor_.setPackedFixed64Iterable(82, value); + } + + if (requestAccessor.hasFieldNumber(83)) { + const value = requestAccessor.getRepeatedSfixed32Iterable(83); + msg.accessor_.setPackedSfixed32Iterable(83, value); + } + + if (requestAccessor.hasFieldNumber(84)) { + const value = requestAccessor.getRepeatedSfixed64Iterable(84); + msg.accessor_.setPackedSfixed64Iterable(84, value); + } + + if (requestAccessor.hasFieldNumber(85)) { + const value = requestAccessor.getRepeatedFloatIterable(85); + msg.accessor_.setPackedFloatIterable(85, value); + } + + if (requestAccessor.hasFieldNumber(86)) { + const value = requestAccessor.getRepeatedDoubleIterable(86); + msg.accessor_.setPackedDoubleIterable(86, value); + } + + if (requestAccessor.hasFieldNumber(87)) { + const value = requestAccessor.getRepeatedBoolIterable(87); + msg.accessor_.setPackedBoolIterable(87, value); + } + + if (requestAccessor.hasFieldNumber(88)) { + const value = requestAccessor.getRepeatedInt32Iterable(88); + msg.accessor_.setPackedInt32Iterable(88, value); + } + return msg; + } + + /** + * Serializes into binary data. + * @return {!ArrayBuffer} + */ + serialize() { + return this.accessor_.serialize(); + } +} + +exports = TestAllTypesProto2; diff --git a/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/indexer_test.js b/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/indexer_test.js new file mode 100644 index 0000000..ffb8807 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/indexer_test.js @@ -0,0 +1,334 @@ +/** + * @fileoverview Tests for indexer.js. + */ +goog.module('protobuf.binary.IndexerTest'); + +goog.setTestOnly(); + +// Note to the reader: +// Since the index behavior changes with the checking level some of the tests +// in this file have to know which checking level is enabled to make correct +// assertions. +// Test are run in all checking levels. +const BinaryStorage = goog.require('protobuf.runtime.BinaryStorage'); +const BufferDecoder = goog.require('protobuf.binary.BufferDecoder'); +const WireType = goog.require('protobuf.binary.WireType'); +const {CHECK_CRITICAL_STATE} = goog.require('protobuf.internal.checks'); +const {Field, IndexEntry} = goog.require('protobuf.binary.field'); +const {buildIndex} = goog.require('protobuf.binary.indexer'); +const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper'); + +/** + * Returns the number of fields stored. + * + * @param {!BinaryStorage} storage + * @return {number} + */ +function getStorageSize(storage) { + let size = 0; + storage.forEach(() => void size++); + return size; +} + +/** + * @type {number} + */ +const PIVOT = 1; + +/** + * Asserts a single IndexEntry at a given field number. + * @param {!BinaryStorage} storage + * @param {number} fieldNumber + * @param {...!IndexEntry} expectedEntries + */ +function assertStorageEntries(storage, fieldNumber, ...expectedEntries) { + expect(getStorageSize(storage)).toBe(1); + + const entryArray = storage.get(fieldNumber).getIndexArray(); + expect(entryArray).not.toBeUndefined(); + expect(entryArray.length).toBe(expectedEntries.length); + + for (let i = 0; i < entryArray.length; i++) { + const storageEntry = entryArray[i]; + const expectedEntry = expectedEntries[i]; + + expect(storageEntry).toBe(expectedEntry); + } +} + +describe('Indexer does', () => { + it('return empty storage for empty array', () => { + const storage = buildIndex(createBufferDecoder(), PIVOT); + expect(storage).not.toBeNull(); + expect(getStorageSize(storage)).toBe(0); + }); + + it('throw for null array', () => { + expect( + () => buildIndex( + /** @type {!BufferDecoder} */ (/** @type {*} */ (null)), PIVOT)) + .toThrow(); + }); + + it('fail for invalid wire type (6)', () => { + expect(() => buildIndex(createBufferDecoder(0x0E, 0x01), PIVOT)) + .toThrowError('Unexpected wire type: 6'); + }); + + it('fail for invalid wire type (7)', () => { + expect(() => buildIndex(createBufferDecoder(0x0F, 0x01), PIVOT)) + .toThrowError('Unexpected wire type: 7'); + }); + + it('index varint', () => { + const data = createBufferDecoder(0x08, 0x01, 0x08, 0x01); + const storage = buildIndex(data, PIVOT); + assertStorageEntries( + storage, /* fieldNumber= */ 1, + Field.encodeIndexEntry(WireType.VARINT, /* startIndex= */ 1), + Field.encodeIndexEntry(WireType.VARINT, /* startIndex= */ 3)); + }); + + it('index varint with two bytes field number', () => { + const data = createBufferDecoder(0xF8, 0x01, 0x01); + const storage = buildIndex(data, PIVOT); + assertStorageEntries( + storage, /* fieldNumber= */ 31, + Field.encodeIndexEntry(WireType.VARINT, /* startIndex= */ 2)); + }); + + it('fail for varints that are longer than 10 bytes', () => { + const data = createBufferDecoder( + 0x08, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00); + if (CHECK_CRITICAL_STATE) { + expect(() => buildIndex(data, PIVOT)) + .toThrowError('Index out of bounds: index: 12 size: 11'); + } else { + // Note in unchecked mode we produce invalid output for invalid inputs. + // This test just documents our behavior in those cases. + // These values might change at any point and are not considered + // what the implementation should be doing here. + const storage = buildIndex(data, PIVOT); + assertStorageEntries( + storage, /* fieldNumber= */ 1, + Field.encodeIndexEntry(WireType.VARINT, /* startIndex= */ 1)); + } + }); + + it('fail for varints with no data', () => { + const data = createBufferDecoder(0x08); + expect(() => buildIndex(data, PIVOT)).toThrow(); + }); + + it('index fixed64', () => { + const data = createBufferDecoder( + /* first= */ 0x09, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + /* second= */ 0x09, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08); + const storage = buildIndex(data, PIVOT); + assertStorageEntries( + storage, /* fieldNumber= */ 1, + Field.encodeIndexEntry(WireType.FIXED64, /* startIndex= */ 1), + Field.encodeIndexEntry(WireType.FIXED64, /* startIndex= */ 10)); + }); + + it('fail for fixed64 data missing in input', () => { + const data = + createBufferDecoder(0x09, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07); + if (CHECK_CRITICAL_STATE) { + expect(() => buildIndex(data, PIVOT)) + .toThrowError('Index out of bounds: index: 9 size: 8'); + } else { + // Note in unchecked mode we produce invalid output for invalid inputs. + // This test just documents our behavior in those cases. + // These values might change at any point and are not considered + // what the implementation should be doing here. + const storage = buildIndex(data, PIVOT); + assertStorageEntries( + storage, /* fieldNumber= */ 1, + Field.encodeIndexEntry(WireType.FIXED64, /* startIndex= */ 1)); + } + }); + + it('fail for fixed64 tag that has no data after it', () => { + if (CHECK_CRITICAL_STATE) { + const data = createBufferDecoder(0x09); + expect(() => buildIndex(data, PIVOT)) + .toThrowError('Index out of bounds: index: 9 size: 1'); + } else { + // Note in unchecked mode we produce invalid output for invalid inputs. + // This test just documents our behavior in those cases. + // These values might change at any point and are not considered + // what the implementation should be doing here. + const data = createBufferDecoder(0x09); + const storage = buildIndex(data, PIVOT); + assertStorageEntries( + storage, /* fieldNumber= */ 1, + Field.encodeIndexEntry(WireType.FIXED64, /* startIndex= */ 1)); + } + }); + + it('index delimited', () => { + const data = createBufferDecoder( + /* first= */ 0x0A, 0x02, 0x00, 0x01, /* second= */ 0x0A, 0x02, 0x00, + 0x01); + const storage = buildIndex(data, PIVOT); + assertStorageEntries( + storage, /* fieldNumber= */ 1, + Field.encodeIndexEntry(WireType.DELIMITED, /* startIndex= */ 1), + Field.encodeIndexEntry(WireType.DELIMITED, /* startIndex= */ 5)); + }); + + it('fail for length deliimted field data missing in input', () => { + const data = createBufferDecoder(0x0A, 0x04, 0x00, 0x01); + if (CHECK_CRITICAL_STATE) { + expect(() => buildIndex(data, PIVOT)) + .toThrowError('Index out of bounds: index: 6 size: 4'); + } else { + // Note in unchecked mode we produce invalid output for invalid inputs. + // This test just documents our behavior in those cases. + // These values might change at any point and are not considered + // what the implementation should be doing here. + const storage = buildIndex(data, PIVOT); + assertStorageEntries( + storage, /* fieldNumber= */ 1, + Field.encodeIndexEntry(WireType.DELIMITED, /* startIndex= */ 1)); + } + }); + + it('fail for delimited tag that has no data after it', () => { + const data = createBufferDecoder(0x0A); + expect(() => buildIndex(data, PIVOT)).toThrow(); + }); + + it('index fixed32', () => { + const data = createBufferDecoder( + /* first= */ 0x0D, 0x01, 0x02, 0x03, 0x04, /* second= */ 0x0D, 0x01, + 0x02, 0x03, 0x04); + const storage = buildIndex(data, PIVOT); + assertStorageEntries( + storage, /* fieldNumber= */ 1, + Field.encodeIndexEntry(WireType.FIXED32, /* startIndex= */ 1), + Field.encodeIndexEntry(WireType.FIXED32, /* startIndex= */ 6)); + }); + + it('fail for fixed32 data missing in input', () => { + const data = createBufferDecoder(0x0D, 0x01, 0x02, 0x03); + + if (CHECK_CRITICAL_STATE) { + expect(() => buildIndex(data, PIVOT)) + .toThrowError('Index out of bounds: index: 5 size: 4'); + } else { + // Note in unchecked mode we produce invalid output for invalid inputs. + // This test just documents our behavior in those cases. + // These values might change at any point and are not considered + // what the implementation should be doing here. + const storage = buildIndex(data, PIVOT); + assertStorageEntries( + storage, /* fieldNumber= */ 1, + Field.encodeIndexEntry(WireType.FIXED32, /* startIndex= */ 1)); + } + }); + + it('fail for fixed32 tag that has no data after it', () => { + if (CHECK_CRITICAL_STATE) { + const data = createBufferDecoder(0x0D); + expect(() => buildIndex(data, PIVOT)) + .toThrowError('Index out of bounds: index: 5 size: 1'); + } else { + // Note in unchecked mode we produce invalid output for invalid inputs. + // This test just documents our behavior in those cases. + // These values might change at any point and are not considered + // what the implementation should be doing here. + const data = createBufferDecoder(0x0D); + const storage = buildIndex(data, PIVOT); + assertStorageEntries( + storage, /* fieldNumber= */ 1, + Field.encodeIndexEntry(WireType.FIXED32, /* startIndex= */ 1)); + } + }); + + it('index group', () => { + const data = createBufferDecoder( + /* first= */ 0x0B, 0x08, 0x01, 0x0C, /* second= */ 0x0B, 0x08, 0x01, + 0x0C); + const storage = buildIndex(data, PIVOT); + assertStorageEntries( + storage, /* fieldNumber= */ 1, + Field.encodeIndexEntry(WireType.START_GROUP, /* startIndex= */ 1), + Field.encodeIndexEntry(WireType.START_GROUP, /* startIndex= */ 5)); + }); + + it('index group and skips inner group', () => { + const data = + createBufferDecoder(0x0B, 0x0B, 0x08, 0x01, 0x0C, 0x08, 0x01, 0x0C); + const storage = buildIndex(data, PIVOT); + assertStorageEntries( + storage, /* fieldNumber= */ 1, + Field.encodeIndexEntry(WireType.START_GROUP, /* startIndex= */ 1)); + }); + + it('fail on unmatched stop group', () => { + const data = createBufferDecoder(0x0C, 0x01); + expect(() => buildIndex(data, PIVOT)) + .toThrowError('Unexpected wire type: 4'); + }); + + it('fail for groups without matching stop group', () => { + const data = createBufferDecoder(0x0B, 0x08, 0x01, 0x1C); + if (CHECK_CRITICAL_STATE) { + expect(() => buildIndex(data, PIVOT)) + .toThrowError('Expected stop group for fieldnumber 1 not found.'); + } else { + // Note in unchecked mode we produce invalid output for invalid inputs. + // This test just documents our behavior in those cases. + // These values might change at any point and are not considered + // what the implementation should be doing here. + const storage = buildIndex(data, PIVOT); + assertStorageEntries( + storage, /* fieldNumber= */ 1, + Field.encodeIndexEntry(WireType.START_GROUP, /* startIndex= */ 1)); + } + }); + + it('fail for groups without stop group', () => { + const data = createBufferDecoder(0x0B, 0x08, 0x01); + if (CHECK_CRITICAL_STATE) { + expect(() => buildIndex(data, PIVOT)).toThrowError('No end group found.'); + } else { + // Note in unchecked mode we produce invalid output for invalid inputs. + // This test just documents our behavior in those cases. + // These values might change at any point and are not considered + // what the implementation should be doing here. + const storage = buildIndex(data, PIVOT); + assertStorageEntries( + storage, /* fieldNumber= */ 1, + Field.encodeIndexEntry(WireType.START_GROUP, /* startIndex= */ 1)); + } + }); + + it('fail for group tag that has no data after it', () => { + const data = createBufferDecoder(0x0B); + if (CHECK_CRITICAL_STATE) { + expect(() => buildIndex(data, PIVOT)).toThrowError('No end group found.'); + } else { + // Note in unchecked mode we produce invalid output for invalid inputs. + // This test just documents our behavior in those cases. + // These values might change at any point and are not considered + // what the implementation should be doing here. + const storage = buildIndex(data, PIVOT); + assertStorageEntries( + storage, /* fieldNumber= */ 1, + Field.encodeIndexEntry(WireType.START_GROUP, /* startIndex= */ 1)); + } + }); + + it('index too large tag', () => { + const data = createBufferDecoder(0xF8, 0xFF, 0xFF, 0xFF, 0xFF); + expect(() => buildIndex(data, PIVOT)).toThrow(); + }); + + it('fail for varint tag that has no data after it', () => { + const data = createBufferDecoder(0x08); + expect(() => buildIndex(data, PIVOT)).toThrow(); + }); +}); diff --git a/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/internal_message.js b/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/internal_message.js new file mode 100644 index 0000000..1ba9ed9 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/internal_message.js @@ -0,0 +1,24 @@ +/** + * @fileoverview Internal interface for messages implemented with the binary + * kernel. + */ +goog.module('protobuf.binary.InternalMessage'); + +const Kernel = goog.requireType('protobuf.runtime.Kernel'); + +/** + * Interface that needs to be implemented by messages implemented with the + * binary kernel. This is an internal only interface and should be used only by + * the classes in binary kernel. + * + * @interface + */ +class InternalMessage { + /** + * @package + * @return {!Kernel} + */ + internalGetKernel() {} +} + +exports = InternalMessage; \ No newline at end of file diff --git a/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/message_set_test.js b/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/message_set_test.js new file mode 100644 index 0000000..35e5935 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/message_set_test.js @@ -0,0 +1,262 @@ +/** + * @fileoverview Tests for message_set.js. + */ +goog.module('protobuf.runtime.MessageSetTest'); + +goog.setTestOnly(); + +const Kernel = goog.require('protobuf.runtime.Kernel'); +const MessageSet = goog.require('protobuf.runtime.MessageSet'); +const TestMessage = goog.require('protobuf.testing.binary.TestMessage'); + +/** + * @param {...number} bytes + * @return {!ArrayBuffer} + */ +function createArrayBuffer(...bytes) { + return new Uint8Array(bytes).buffer; +} + +describe('MessageSet does', () => { + it('returns no messages for empty set', () => { + const messageSet = MessageSet.createEmpty(); + expect(messageSet.getMessageOrNull(12345, TestMessage.instanceCreator)) + .toBeNull(); + }); + + it('returns no kernel for empty set', () => { + const messageSet = MessageSet.createEmpty(); + expect(messageSet.getMessageAccessorOrNull(12345)).toBeNull(); + }); + + it('returns message that has been set', () => { + const messageSet = MessageSet.createEmpty(); + const message = TestMessage.createEmpty(); + messageSet.setMessage(12345, message); + expect(messageSet.getMessageOrNull(12345, TestMessage.instanceCreator)) + .toBe(message); + }); + + it('returns null for cleared message', () => { + const messageSet = MessageSet.createEmpty(); + const message = TestMessage.createEmpty(); + messageSet.setMessage(12345, message); + messageSet.clearMessage(12345); + expect(messageSet.getMessageAccessorOrNull(12345)).toBeNull(); + }); + + it('returns false for not present message', () => { + const messageSet = MessageSet.createEmpty(); + expect(messageSet.hasMessage(12345)).toBe(false); + }); + + it('returns true for present message', () => { + const messageSet = MessageSet.createEmpty(); + const message = TestMessage.createEmpty(); + messageSet.setMessage(12345, message); + expect(messageSet.hasMessage(12345)).toBe(true); + }); + + it('returns false for cleared message', () => { + const messageSet = MessageSet.createEmpty(); + const message = TestMessage.createEmpty(); + messageSet.setMessage(12345, message); + messageSet.clearMessage(12345); + expect(messageSet.hasMessage(12345)).toBe(false); + }); + + it('returns false for cleared message without it being present', () => { + const messageSet = MessageSet.createEmpty(); + messageSet.clearMessage(12345); + expect(messageSet.hasMessage(12345)).toBe(false); + }); + + const createMessageSet = () => { + const messageSet = MessageSet.createEmpty(); + const message = TestMessage.createEmpty(); + message.setInt32(1, 2); + messageSet.setMessage(12345, message); + + + const parsedKernel = + Kernel.fromArrayBuffer(messageSet.internalGetKernel().serialize()); + return MessageSet.fromKernel(parsedKernel); + }; + + it('pass through pivot for getMessageOrNull', () => { + const messageSet = createMessageSet(); + const message = + messageSet.getMessageOrNull(12345, TestMessage.instanceCreator, 2); + expect(message.internalGetKernel().getPivot()).toBe(2); + }); + + it('pass through pivot for getMessageAttach', () => { + const messageSet = createMessageSet(); + const message = + messageSet.getMessageAttach(12345, TestMessage.instanceCreator, 2); + expect(message.internalGetKernel().getPivot()).toBe(2); + }); + + it('pass through pivot for getMessageAccessorOrNull', () => { + const messageSet = createMessageSet(); + const kernel = messageSet.getMessageAccessorOrNull(12345, 2); + expect(kernel.getPivot()).toBe(2); + }); + + it('pick the last value in the stream', () => { + const arrayBuffer = createArrayBuffer( + 0x52, // Tag (field:10, length delimited) + 0x14, // Length of 20 bytes + 0x0B, // Start group fieldnumber 1 + 0x10, // Tag (field 2, varint) + 0xB9, // 12345 + 0x60, // 12345 + 0x1A, // Tag (field 3, length delimited) + 0x03, // length 3 + 0xA0, // Tag (fieldnumber 20, varint) + 0x01, // Tag (fieldnumber 20, varint) + 0x1E, // 30 + 0x0C, // Stop Group field number 1 + // second group + 0x0B, // Start group fieldnumber 1 + 0x10, // Tag (field 2, varint) + 0xB9, // 12345 + 0x60, // 12345 + 0x1A, // Tag (field 3, length delimited) + 0x03, // length 3 + 0xA0, // Tag (fieldnumber 20, varint) + 0x01, // Tag (fieldnumber 20, varint) + 0x01, // 1 + 0x0C // Stop Group field number 1 + ); + + const outerMessage = Kernel.fromArrayBuffer(arrayBuffer); + + const messageSet = outerMessage.getMessage(10, MessageSet.fromKernel); + + const message = + messageSet.getMessageOrNull(12345, TestMessage.instanceCreator); + expect(message.getInt32WithDefault(20)).toBe(1); + }); + + it('removes duplicates when read', () => { + const arrayBuffer = createArrayBuffer( + 0x52, // Tag (field:10, length delimited) + 0x14, // Length of 20 bytes + 0x0B, // Start group fieldnumber 1 + 0x10, // Tag (field 2, varint) + 0xB9, // 12345 + 0x60, // 12345 + 0x1A, // Tag (field 3, length delimited) + 0x03, // length 3 + 0xA0, // Tag (fieldnumber 20, varint) + 0x01, // Tag (fieldnumber 20, varint) + 0x1E, // 30 + 0x0C, // Stop Group field number 1 + // second group + 0x0B, // Start group fieldnumber 1 + 0x10, // Tag (field 2, varint) + 0xB9, // 12345 + 0x60, // 12345 + 0x1A, // Tag (field 3, length delimited) + 0x03, // length 3 + 0xA0, // Tag (fieldnumber 20, varint) + 0x01, // Tag (fieldnumber 20, varint) + 0x01, // 1 + 0x0C // Stop Group field number 1 + ); + + + const outerMessage = Kernel.fromArrayBuffer(arrayBuffer); + outerMessage.getMessageAttach(10, MessageSet.fromKernel); + + expect(outerMessage.serialize()) + .toEqual(createArrayBuffer( + 0x52, // Tag (field:10, length delimited) + 0x0A, // Length of 10 bytes + 0x0B, // Start group fieldnumber 1 + 0x10, // Tag (field 2, varint) + 0xB9, // 12345 + 0x60, // 12345 + 0x1A, // Tag (field 3, length delimited) + 0x03, // length 3 + 0xA0, // Tag (fieldnumber 20, varint) + 0x01, // Tag (fieldnumber 20, varint) + 0x01, // 1 + 0x0C // Stop Group field number 1 + )); + }); + + it('allow for large typeIds', () => { + const messageSet = MessageSet.createEmpty(); + const message = TestMessage.createEmpty(); + messageSet.setMessage(0xFFFFFFFE >>> 0, message); + expect(messageSet.hasMessage(0xFFFFFFFE >>> 0)).toBe(true); + }); +}); + +describe('Optional MessageSet does', () => { + // message Bar { + // optional MessageSet mset = 10; + //} + // + // message Foo { + // extend proto2.bridge.MessageSet { + // optional Foo message_set_extension = 12345; + // } + // optional int32 f20 = 20; + //} + + it('encode as a field', () => { + const fooMessage = Kernel.createEmpty(); + fooMessage.setInt32(20, 30); + + const messageSet = MessageSet.createEmpty(); + messageSet.setMessage(12345, TestMessage.instanceCreator(fooMessage)); + + const barMessage = Kernel.createEmpty(); + barMessage.setMessage(10, messageSet); + + expect(barMessage.serialize()) + .toEqual(createArrayBuffer( + 0x52, // Tag (field:10, length delimited) + 0x0A, // Length of 10 bytes + 0x0B, // Start group fieldnumber 1 + 0x10, // Tag (field 2, varint) + 0xB9, // 12345 + 0x60, // 12345 + 0x1A, // Tag (field 3, length delimited) + 0x03, // length 3 + 0xA0, // Tag (fieldnumber 20, varint) + 0x01, // Tag (fieldnumber 20, varint) + 0x1E, // 30 + 0x0C // Stop Group field number 1 + )); + }); + + it('deserializes', () => { + const fooMessage = Kernel.createEmpty(); + fooMessage.setInt32(20, 30); + + const messageSet = MessageSet.createEmpty(); + messageSet.setMessage(12345, TestMessage.instanceCreator(fooMessage)); + + + const barMessage = Kernel.createEmpty(); + barMessage.setMessage(10, messageSet); + + const arrayBuffer = barMessage.serialize(); + + const barMessageParsed = Kernel.fromArrayBuffer(arrayBuffer); + expect(barMessageParsed.hasFieldNumber(10)).toBe(true); + + const messageSetParsed = + barMessageParsed.getMessage(10, MessageSet.fromKernel); + + const fooMessageParsed = + messageSetParsed.getMessageOrNull(12345, TestMessage.instanceCreator) + .internalGetKernel(); + + expect(fooMessageParsed.getInt32WithDefault(20)).toBe(30); + }); +}); diff --git a/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/packed_sint32_test_pairs.js b/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/packed_sint32_test_pairs.js new file mode 100644 index 0000000..314ac11 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/packed_sint32_test_pairs.js @@ -0,0 +1,33 @@ +goog.module('protobuf.binary.packedSint32TestPairs'); + +const BufferDecoder = goog.require('protobuf.binary.BufferDecoder'); +const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper'); + +/** + * An array of Pairs of packed sint32 values and their bit representation. + * This is used to test encoding and decoding from/to the protobuf wire format. + * @return {!Array<{name: string, sint32Values: !Array, + * bufferDecoder: !BufferDecoder, skip_writer: ?boolean}>} + */ +function getPackedSint32Pairs() { + return [ + { + name: 'empty value', + sint32Values: [], + bufferDecoder: createBufferDecoder(0x00), + skip_writer: true, + }, + { + name: 'single value', + sint32Values: [-1], + bufferDecoder: createBufferDecoder(0x01, 0x01), + }, + { + name: 'multiple values', + sint32Values: [-1, 0], + bufferDecoder: createBufferDecoder(0x02, 0x01, 0x00), + }, + ]; +} + +exports = {getPackedSint32Pairs}; diff --git a/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/storage.js b/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/storage.js new file mode 100644 index 0000000..a3e1e4f --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/storage.js @@ -0,0 +1,67 @@ +goog.module('protobuf.runtime.Storage'); + +/** + * Interface for getting and storing fields of a protobuf message. + * + * @interface + * @package + * @template FieldType + */ +class Storage { + /** + * Returns the pivot value. + * + * @return {number} + */ + getPivot() {} + + /** + * Sets a field in the specified field number. + * + * @param {number} fieldNumber + * @param {!FieldType} field + */ + set(fieldNumber, field) {} + + /** + * Returns a field at the specified field number. + * + * @param {number} fieldNumber + * @return {!FieldType|undefined} + */ + get(fieldNumber) {} + + /** + * Deletes a field from the specified field number. + * + * @param {number} fieldNumber + */ + delete(fieldNumber) {} + + /** + * Executes the provided function once for each field. + * + * @param {function(!FieldType, number): void} callback + */ + forEach(callback) {} + + /** + * Creates a shallow copy of the storage. + * + * @return {!Storage} + */ + shallowCopy() {} +} + +/** + * 85% of the proto fields have a field number <= 24: + * https://plx.corp.google.com/scripts2/script_5d._f02af6_0000_23b1_a15f_001a1139dd02 + * + * @type {number} + */ +// LINT.IfChange +Storage.DEFAULT_PIVOT = 24; +// LINT.ThenChange(//depot/google3/third_party/protobuf/javascript/runtime/kernel/binary_storage_test.js, +// //depot/google3/net/proto2/contrib/js_proto/internal/kernel_message_generator.cc) + +exports = Storage; diff --git a/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/textencoding.js b/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/textencoding.js new file mode 100644 index 0000000..fe8fd25 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/textencoding.js @@ -0,0 +1,116 @@ +/** + * @fileoverview A UTF8 decoder. + */ +goog.module('protobuf.binary.textencoding'); + +const {checkElementIndex} = goog.require('protobuf.internal.checks'); + +/** + * Combines an array of codePoints into a string. + * @param {!Array} codePoints + * @return {string} + */ +function codePointsToString(codePoints) { + // Performance: http://jsperf.com/string-fromcharcode-test/13 + let s = '', i = 0; + const length = codePoints.length; + const BATCH_SIZE = 10000; + while (i < length) { + const end = Math.min(i + BATCH_SIZE, length); + s += String.fromCharCode.apply(null, codePoints.slice(i, end)); + i = end; + } + return s; +} + +/** + * Decodes raw bytes into a string. + * Supports codepoints from U+0000 up to U+10FFFF. + * (http://en.wikipedia.org/wiki/UTF-8). + * @param {!DataView} bytes + * @return {string} + */ +function decode(bytes) { + let cursor = 0; + const codePoints = []; + + while (cursor < bytes.byteLength) { + const c = bytes.getUint8(cursor++); + if (c < 0x80) { // Regular 7-bit ASCII. + codePoints.push(c); + } else if (c < 0xC0) { + // UTF-8 continuation mark. We are out of sync. This + // might happen if we attempted to read a character + // with more than four bytes. + continue; + } else if (c < 0xE0) { // UTF-8 with two bytes. + checkElementIndex(cursor, bytes.byteLength); + const c2 = bytes.getUint8(cursor++); + codePoints.push(((c & 0x1F) << 6) | (c2 & 0x3F)); + } else if (c < 0xF0) { // UTF-8 with three bytes. + checkElementIndex(cursor + 1, bytes.byteLength); + const c2 = bytes.getUint8(cursor++); + const c3 = bytes.getUint8(cursor++); + codePoints.push(((c & 0xF) << 12) | ((c2 & 0x3F) << 6) | (c3 & 0x3F)); + } else if (c < 0xF8) { // UTF-8 with 4 bytes. + checkElementIndex(cursor + 2, bytes.byteLength); + const c2 = bytes.getUint8(cursor++); + const c3 = bytes.getUint8(cursor++); + const c4 = bytes.getUint8(cursor++); + // Characters written on 4 bytes have 21 bits for a codepoint. + // We can't fit that on 16bit characters, so we use surrogates. + let codepoint = ((c & 0x07) << 18) | ((c2 & 0x3F) << 12) | + ((c3 & 0x3F) << 6) | (c4 & 0x3F); + // Surrogates formula from wikipedia. + // 1. Subtract 0x10000 from codepoint + codepoint -= 0x10000; + // 2. Split this into the high 10-bit value and the low 10-bit value + // 3. Add 0xD800 to the high value to form the high surrogate + // 4. Add 0xDC00 to the low value to form the low surrogate: + const low = (codepoint & 0x3FF) + 0xDC00; + const high = ((codepoint >> 10) & 0x3FF) + 0xD800; + codePoints.push(high, low); + } + } + return codePointsToString(codePoints); +} + +/** + * Writes a UTF16 JavaScript string to the buffer encoded as UTF8. + * @param {string} value The string to write. + * @return {!Uint8Array} An array containing the encoded bytes. + */ +function encode(value) { + const buffer = []; + + for (let i = 0; i < value.length; i++) { + const c1 = value.charCodeAt(i); + + if (c1 < 0x80) { + buffer.push(c1); + } else if (c1 < 0x800) { + buffer.push((c1 >> 6) | 0xC0); + buffer.push((c1 & 0x3F) | 0x80); + } else if (c1 < 0xD800 || c1 >= 0xE000) { + buffer.push((c1 >> 12) | 0xE0); + buffer.push(((c1 >> 6) & 0x3F) | 0x80); + buffer.push((c1 & 0x3F) | 0x80); + } else { + // surrogate pair + i++; + checkElementIndex(i, value.length); + const c2 = value.charCodeAt(i); + const paired = 0x10000 + (((c1 & 0x3FF) << 10) | (c2 & 0x3FF)); + buffer.push((paired >> 18) | 0xF0); + buffer.push(((paired >> 12) & 0x3F) | 0x80); + buffer.push(((paired >> 6) & 0x3F) | 0x80); + buffer.push((paired & 0x3F) | 0x80); + } + } + return new Uint8Array(buffer); +} + +exports = { + decode, + encode, +}; diff --git a/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/textencoding_test.js b/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/textencoding_test.js new file mode 100644 index 0000000..c7ecd18 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/textencoding_test.js @@ -0,0 +1,113 @@ +/** + * @fileoverview Tests for textdecoder.js. + */ +goog.module('protobuf.binary.TextDecoderTest'); + +goog.setTestOnly(); + +const {decode, encode} = goog.require('protobuf.binary.textencoding'); + +describe('Decode does', () => { + it('return empty string for empty array', () => { + expect(decode(new DataView(new ArrayBuffer(0)))).toEqual(''); + }); + + it('throw on null being passed', () => { + expect(() => decode(/** @type {!DataView} */ (/** @type {*} */ (null)))) + .toThrow(); + }); +}); + +describe('Encode does', () => { + it('return empty array for empty string', () => { + expect(encode('')).toEqual(new Uint8Array(0)); + }); + + it('throw on null being passed', () => { + expect(() => encode(/** @type {string} */ (/** @type {*} */ (null)))) + .toThrow(); + }); +}); + +/** @const {!TextEncoder} */ +const textEncoder = new TextEncoder('utf-8'); + +/** + * A Pair of string and Uint8Array representing the same data. + * Each pair has the string value and its utf-8 bytes. + */ +class Pair { + /** + * Constructs a pair from a given string. + * @param {string} s + * @return {!Pair} + */ + static fromString(s) { + return new Pair(s, textEncoder.encode(s).buffer); + } + /** + * Constructs a pair from a given charCode. + * @param {number} charCode + * @return {!Pair} + */ + static fromCharCode(charCode) { + return Pair.fromString(String.fromCharCode(charCode)); + } + + /** + * @param {string} stringValue + * @param {!ArrayBuffer} bytes + * @private + */ + constructor(stringValue, bytes) { + /** @const @private {string} */ + this.stringValue_ = stringValue; + /** @const @private {!ArrayBuffer} */ + this.bytes_ = bytes; + } + + /** Ensures that a given pair encodes and decodes round trip*/ + expectPairToMatch() { + expect(decode(new DataView(this.bytes_))).toEqual(this.stringValue_); + expect(encode(this.stringValue_)).toEqual(new Uint8Array(this.bytes_)); + } +} + +describe('textencoding does', () => { + it('works for empty string', () => { + Pair.fromString('').expectPairToMatch(); + }); + + it('decode and encode random strings', () => { + // 1 byte strings + Pair.fromString('hello').expectPairToMatch(); + Pair.fromString('HELLO1!'); + + // 2 byte String + Pair.fromString('©').expectPairToMatch(); + + // 3 byte string + Pair.fromString('â„').expectPairToMatch(); + + // 4 byte string + Pair.fromString('ðŸ˜').expectPairToMatch(); + }); + + it('decode and encode 1 byte strings', () => { + for (let i = 0; i < 0x80; i++) { + Pair.fromCharCode(i).expectPairToMatch(); + } + }); + + it('decode and encode 2 byte strings', () => { + for (let i = 0xC0; i < 0x7FF; i++) { + Pair.fromCharCode(i).expectPairToMatch(); + } + }); + + it('decode and encode 3 byte strings', () => { + for (let i = 0x7FF; i < 0x8FFF; i++) { + Pair.fromCharCode(i).expectPairToMatch(); + } + }); +}); diff --git a/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/typed_arrays_test.js b/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/typed_arrays_test.js new file mode 100644 index 0000000..be9ba65 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/typed_arrays_test.js @@ -0,0 +1,191 @@ +/** + * @fileoverview Tests for typed_arrays.js. + */ +goog.module('protobuf.binary.typedArraysTest'); + +const {arrayBufferEqual, arrayBufferSlice, cloneArrayBufferView, hashUint8Array, uint8ArrayEqual} = goog.require('protobuf.binary.typedArrays'); + +describe('arrayBufferEqual', () => { + it('returns true for empty buffers', () => { + const buffer1 = new ArrayBuffer(0); + const buffer2 = new ArrayBuffer(0); + expect(arrayBufferEqual(buffer1, buffer2)).toBe(true); + }); + + it('throws for first null buffers', () => { + const buffer = new ArrayBuffer(0); + expect( + () => arrayBufferEqual( + /** @type {!ArrayBuffer} */ (/** @type {*} */ (null)), buffer)) + .toThrow(); + }); + + it('throws for second null buffers', () => { + const buffer = new ArrayBuffer(0); + expect( + () => arrayBufferEqual( + buffer, /** @type {!ArrayBuffer} */ (/** @type {*} */ (null)))) + .toThrow(); + }); + + it('returns true for arrays with same values', () => { + const array1 = new Uint8Array(4); + array1[0] = 1; + const array2 = new Uint8Array(4); + array2[0] = 1; + expect(arrayBufferEqual(array1.buffer, array2.buffer)).toBe(true); + }); + + it('returns false for arrays with different values', () => { + const array1 = new Uint8Array(4); + array1[0] = 1; + const array2 = new Uint8Array(4); + array2[0] = 2; + expect(arrayBufferEqual(array1.buffer, array2.buffer)).toBe(false); + }); + + it('returns true same instance', () => { + const array1 = new Uint8Array(4); + array1[0] = 1; + expect(arrayBufferEqual(array1.buffer, array1.buffer)).toBe(true); + }); +}); + +describe('uint8ArrayEqual', () => { + it('returns true for empty arrays', () => { + const array1 = new Uint8Array(0); + const array2 = new Uint8Array(0); + expect(uint8ArrayEqual(array1, array2)).toBe(true); + }); + + it('throws for first Uint8Array array', () => { + const array = new Uint8Array(0); + expect( + () => uint8ArrayEqual( + /** @type {!Uint8Array} */ (/** @type {*} */ (null)), array)) + .toThrow(); + }); + + it('throws for second null array', () => { + const array = new Uint8Array(0); + expect( + () => uint8ArrayEqual( + array, /** @type {!Uint8Array} */ (/** @type {*} */ (null)))) + .toThrow(); + }); + + it('returns true for arrays with same values', () => { + const buffer1 = new Uint8Array([0, 1, 2, 3]).buffer; + const buffer2 = new Uint8Array([1, 2, 3, 4]).buffer; + const array1 = new Uint8Array(buffer1, 1, 3); + const array2 = new Uint8Array(buffer2, 0, 3); + expect(uint8ArrayEqual(array1, array2)).toBe(true); + }); + + it('returns false for arrays with different values', () => { + const array1 = new Uint8Array(4); + array1[0] = 1; + const array2 = new Uint8Array(4); + array2[0] = 2; + expect(uint8ArrayEqual(array1, array2)).toBe(false); + }); + + it('returns true same instance', () => { + const array1 = new Uint8Array(4); + array1[0] = 1; + expect(uint8ArrayEqual(array1, array1)).toBe(true); + }); +}); + +describe('arrayBufferSlice', () => { + it('Returns a new instance.', () => { + const buffer1 = new ArrayBuffer(0); + const buffer2 = arrayBufferSlice(buffer1, 0); + expect(buffer2).not.toBe(buffer1); + expect(arrayBufferEqual(buffer1, buffer2)).toBe(true); + }); + + it('Copies data with positive start/end.', () => { + const buffer1 = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).buffer; + expect(buffer1.byteLength).toEqual(10); + + const buffer2 = arrayBufferSlice(buffer1, 2, 6); + expect(buffer2.byteLength).toEqual(4); + expect(buffer2).not.toBe(buffer1); + const expected = new Uint8Array([2, 3, 4, 5]).buffer; + expect(arrayBufferEqual(expected, buffer2)).toBe(true); + }); + + it('Copies all data without end.', () => { + const buffer1 = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).buffer; + expect(buffer1.byteLength).toEqual(10); + + const buffer2 = arrayBufferSlice(buffer1, 0); + expect(buffer2.byteLength).toEqual(10); + expect(arrayBufferEqual(buffer1, buffer2)).toBe(true); + }); + + if (goog.DEBUG) { + it('Fails with negative end.', () => { + const buffer1 = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).buffer; + expect(() => void arrayBufferSlice(buffer1, 2, -1)).toThrow(); + }); + + it('Fails with negative start.', () => { + const buffer1 = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).buffer; + expect(() => void arrayBufferSlice(buffer1, 2, -1)).toThrow(); + }); + + it('Fails when start > end.', () => { + const buffer1 = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).buffer; + expect(() => void arrayBufferSlice(buffer1, 2, 1)).toThrow(); + }); + } +}); + +describe('cloneArrayBufferView', () => { + it('Returns a new instance.', () => { + const array1 = new Uint8Array(0); + const array2 = cloneArrayBufferView(new Uint8Array(array1)); + expect(array2).not.toBe(array1); + expect(uint8ArrayEqual(array1, array2)).toBe(true); + }); + + it('Returns an array of the exact size.', () => { + const array1 = + new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).subarray(2, 5); + expect(array1.length).toEqual(3); + expect(array1.buffer.byteLength).toEqual(10); + const array2 = cloneArrayBufferView(array1); + expect(array2.byteLength).toEqual(3); + expect(array2).toEqual(new Uint8Array([2, 3, 4])); + }); +}); + +describe('hashUint8Array', () => { + it('returns same hashcode for empty Uint8Arrays', () => { + const array1 = new Uint8Array(0); + const array2 = new Uint8Array(0); + expect(hashUint8Array(array1)).toBe(hashUint8Array(array2)); + }); + + it('returns same hashcode for Uint8Arrays with same values', () => { + const array1 = new Uint8Array(4); + array1[0] = 1; + const array2 = new Uint8Array(4); + array2[0] = 1; + expect(hashUint8Array(array1)).toBe(hashUint8Array(array2)); + }); + + it('returns different hashcode for Uint8Arrays with different values', () => { + // This test might fail in the future if the hashing algorithm is updated + // and we end up with a collision here. + // We still need this test to make sure that we are not just returning + // the same number for all buffers. + const array1 = new Uint8Array(4); + array1[0] = 1; + const array2 = new Uint8Array(4); + array2[0] = 2; + expect(hashUint8Array(array1)).not.toBe(hashUint8Array(array2)); + }); +}); diff --git a/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/uint8arrays.js b/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/uint8arrays.js new file mode 100644 index 0000000..c6bed16 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/experimental/runtime/kernel/uint8arrays.js @@ -0,0 +1,28 @@ +/** + * @fileoverview Helper methods for Uint8Arrays. + */ +goog.module('protobuf.binary.uint8arrays'); + +/** + * Combines multiple bytes arrays (either Uint8Array or number array whose + * values are bytes) into a single Uint8Array. + * @param {!Array|!Array>} arrays + * @return {!Uint8Array} + */ +function concatenateByteArrays(arrays) { + let totalLength = 0; + for (const array of arrays) { + totalLength += array.length; + } + const result = new Uint8Array(totalLength); + let offset = 0; + for (const array of arrays) { + result.set(array, offset); + offset += array.length; + } + return result; +} + +exports = { + concatenateByteArrays, +}; diff --git a/tools/env-vars-generator/protobuf/js/gulpfile.js b/tools/env-vars-generator/protobuf/js/gulpfile.js new file mode 100644 index 0000000..00a6d64 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/gulpfile.js @@ -0,0 +1,273 @@ +var gulp = require('gulp'); +var execFile = require('child_process').execFile; +var glob = require('glob'); + +function exec(command, cb) { + execFile('sh', ['-c', command], cb); +} + +var protoc = process.env.PROTOC || '../src/protoc'; + +var wellKnownTypes = [ + '../src/google/protobuf/any.proto', + '../src/google/protobuf/api.proto', + '../src/google/protobuf/compiler/plugin.proto', + '../src/google/protobuf/descriptor.proto', + '../src/google/protobuf/duration.proto', + '../src/google/protobuf/empty.proto', + '../src/google/protobuf/field_mask.proto', + '../src/google/protobuf/source_context.proto', + '../src/google/protobuf/struct.proto', + '../src/google/protobuf/timestamp.proto', + '../src/google/protobuf/type.proto', + '../src/google/protobuf/wrappers.proto', +]; + +var group1Protos = [ + 'data.proto', + 'test3.proto', + 'test5.proto', + 'commonjs/test6/test6.proto', + 'test8.proto', + 'test11.proto', + 'test12.proto', + 'test13.proto', + 'test14.proto', + 'test15.proto', + 'testbinary.proto', + 'testempty.proto', + 'test.proto', + 'testlargenumbers.proto', +]; + +var group2Protos = [ + 'proto3_test.proto', + 'test2.proto', + 'test4.proto', + 'commonjs/test7/test7.proto', +]; + +var group3Protos = [ + 'test9.proto', + 'test10.proto' +]; + + +gulp.task('genproto_well_known_types_closure', function (cb) { + exec(protoc + ' --js_out=one_output_file_per_input_file,binary:. -I ../src -I . ' + wellKnownTypes.join(' '), + function (err, stdout, stderr) { + console.log(stdout); + console.log(stderr); + cb(err); + }); +}); + +gulp.task('genproto_group1_closure', function (cb) { + exec(protoc + ' --js_out=library=testproto_libs1,binary:. -I ../src -I . ' + group1Protos.join(' '), + function (err, stdout, stderr) { + console.log(stdout); + console.log(stderr); + cb(err); + }); +}); + +gulp.task('genproto_group2_closure', function(cb) { + exec( + protoc + + ' --experimental_allow_proto3_optional --js_out=library=testproto_libs2,binary:. -I ../src -I . -I commonjs ' + + group2Protos.join(' '), + function(err, stdout, stderr) { + console.log(stdout); + console.log(stderr); + cb(err); + }); +}); + +gulp.task('genproto_well_known_types_commonjs', function (cb) { + exec('mkdir -p commonjs_out && ' + protoc + ' --js_out=import_style=commonjs,binary:commonjs_out -I ../src ' + wellKnownTypes.join(' '), + function (err, stdout, stderr) { + console.log(stdout); + console.log(stderr); + cb(err); + }); +}); + +gulp.task('genproto_group1_commonjs', function (cb) { + exec('mkdir -p commonjs_out && ' + protoc + ' --js_out=import_style=commonjs,binary:commonjs_out -I ../src -I commonjs -I . ' + group1Protos.join(' '), + function (err, stdout, stderr) { + console.log(stdout); + console.log(stderr); + cb(err); + }); +}); + +gulp.task('genproto_group2_commonjs', function(cb) { + exec( + 'mkdir -p commonjs_out && ' + protoc + + ' --experimental_allow_proto3_optional --js_out=import_style=commonjs,binary:commonjs_out -I ../src -I commonjs -I . ' + + group2Protos.join(' '), + function(err, stdout, stderr) { + console.log(stdout); + console.log(stderr); + cb(err); + }); +}); + +gulp.task('genproto_commonjs_wellknowntypes', function (cb) { + exec('mkdir -p commonjs_out/node_modules/google-protobuf && ' + protoc + ' --js_out=import_style=commonjs,binary:commonjs_out/node_modules/google-protobuf -I ../src ' + wellKnownTypes.join(' '), + function (err, stdout, stderr) { + console.log(stdout); + console.log(stderr); + cb(err); + }); +}); + +gulp.task('genproto_wellknowntypes', function (cb) { + exec(protoc + ' --js_out=import_style=commonjs,binary:. -I ../src ' + wellKnownTypes.join(' '), + function (err, stdout, stderr) { + console.log(stdout); + console.log(stderr); + cb(err); + }); +}); +gulp.task('genproto_group3_commonjs_strict', function (cb) { + exec('mkdir -p commonjs_out && ' + protoc + ' --js_out=import_style=commonjs_strict,binary:commonjs_out -I ../src -I commonjs -I . ' + group3Protos.join(' '), + function (err, stdout, stderr) { + console.log(stdout); + console.log(stderr); + cb(err); + }); +}); + + +function getClosureCompilerCommand(exportsFile, outputFile) { + const closureLib = 'node_modules/google-closure-library'; + return [ + 'node_modules/.bin/google-closure-compiler', + `--js=${closureLib}/closure/goog/**.js`, + `--js=${closureLib}/third_party/closure/goog/**.js`, '--js=map.js', + '--js=message.js', '--js=binary/arith.js', '--js=binary/constants.js', + '--js=binary/decoder.js', '--js=binary/encoder.js', '--js=binary/reader.js', + '--js=binary/utils.js', '--js=binary/writer.js', `--js=${exportsFile}`, + `--entry_point=${exportsFile}`, `> ${outputFile}` + ].join(' '); +} + +gulp.task('dist', gulp.series(['genproto_wellknowntypes'], function(cb) { + // TODO(haberman): minify this more aggressively. + // Will require proper externs/exports. + exec( + getClosureCompilerCommand('commonjs/export.js', 'google-protobuf.js'), + function(err, stdout, stderr) { + console.log(stdout); + console.log(stderr); + cb(err); + }); +})); + +gulp.task('commonjs_asserts', function(cb) { + exec( + 'mkdir -p commonjs_out/test_node_modules && ' + + getClosureCompilerCommand( + 'commonjs/export_asserts.js', + 'commonjs_out/test_node_modules/closure_asserts_commonjs.js'), + function(err, stdout, stderr) { + console.log(stdout); + console.log(stderr); + cb(err); + }); +}); + +gulp.task('commonjs_testdeps', function(cb) { + exec( + 'mkdir -p commonjs_out/test_node_modules && ' + + getClosureCompilerCommand( + 'commonjs/export_testdeps.js', + 'commonjs_out/test_node_modules/testdeps_commonjs.js'), + function(err, stdout, stderr) { + console.log(stdout); + console.log(stderr); + cb(err); + }); +}); + +gulp.task( + 'make_commonjs_out', + gulp.series( + [ + 'dist', 'genproto_well_known_types_commonjs', + 'genproto_group1_commonjs', 'genproto_group2_commonjs', + 'genproto_commonjs_wellknowntypes', 'commonjs_asserts', + 'commonjs_testdeps', 'genproto_group3_commonjs_strict' + ], + function(cb) { + // TODO(haberman): minify this more aggressively. + // Will require proper externs/exports. + var cmd = + 'mkdir -p commonjs_out/binary && mkdir -p commonjs_out/test_node_modules && '; + function addTestFile(file) { + cmd += 'node commonjs/rewrite_tests_for_commonjs.js < ' + file + + ' > commonjs_out/' + file + '&& '; + } + + glob.sync('*_test.js').forEach(addTestFile); + glob.sync('binary/*_test.js').forEach(addTestFile); + + exec( + cmd + 'cp commonjs/jasmine.json commonjs_out/jasmine.json && ' + + 'cp google-protobuf.js commonjs_out/test_node_modules && ' + + 'cp commonjs/strict_test.js commonjs_out/strict_test.js &&' + + 'cp commonjs/import_test.js commonjs_out/import_test.js', + function(err, stdout, stderr) { + console.log(stdout); + console.log(stderr); + cb(err); + }); + })); + +gulp.task( + 'deps', + gulp.series( + [ + 'genproto_well_known_types_closure', 'genproto_group1_closure', + 'genproto_group2_closure' + ], + function(cb) { + exec( + './node_modules/.bin/closure-make-deps --closure-path=. --file=node_modules/google-closure-library/closure/goog/deps.js binary/arith.js binary/constants.js binary/decoder.js binary/encoder.js binary/reader.js binary/utils.js binary/writer.js debug.js map.js message.js node_loader.js test_bootstrap.js > deps.js', + function(err, stdout, stderr) { + console.log(stdout); + console.log(stderr); + cb(err); + }); + })); + +gulp.task( + 'test_closure', + gulp.series( + [ + 'genproto_well_known_types_closure', 'genproto_group1_closure', + 'genproto_group2_closure', 'deps' + ], + function(cb) { + exec( + 'JASMINE_CONFIG_PATH=jasmine.json ./node_modules/.bin/jasmine', + function(err, stdout, stderr) { + console.log(stdout); + console.log(stderr); + cb(err); + }); + })); + +gulp.task('test_commonjs', gulp.series(['make_commonjs_out'], function(cb) { + exec('cd commonjs_out && JASMINE_CONFIG_PATH=jasmine.json NODE_PATH=test_node_modules ../node_modules/.bin/jasmine', + function (err, stdout, stderr) { + console.log(stdout); + console.log(stderr); + cb(err); + }); +})); + +gulp.task('test', gulp.series(['test_closure', 'test_commonjs'], function(cb) { + cb(); +})); diff --git a/tools/env-vars-generator/protobuf/js/maps_test.js b/tools/env-vars-generator/protobuf/js/maps_test.js new file mode 100644 index 0000000..68ed683 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/maps_test.js @@ -0,0 +1,439 @@ +// 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. + +goog.require('goog.testing.asserts'); +goog.require('goog.userAgent'); + +// CommonJS-LoadFromFile: testbinary_pb proto.jspb.test +goog.require('proto.jspb.test.MapValueEnum'); +goog.require('proto.jspb.test.MapValueMessage'); +goog.require('proto.jspb.test.TestMapFields'); +goog.require('proto.jspb.test.TestMapFieldsOptionalKeys'); +goog.require('proto.jspb.test.TestMapFieldsOptionalValues'); +goog.require('proto.jspb.test.MapEntryOptionalKeysStringKey'); +goog.require('proto.jspb.test.MapEntryOptionalKeysInt32Key'); +goog.require('proto.jspb.test.MapEntryOptionalKeysInt64Key'); +goog.require('proto.jspb.test.MapEntryOptionalKeysBoolKey'); +goog.require('proto.jspb.test.MapEntryOptionalValuesStringValue'); +goog.require('proto.jspb.test.MapEntryOptionalValuesInt32Value'); +goog.require('proto.jspb.test.MapEntryOptionalValuesInt64Value'); +goog.require('proto.jspb.test.MapEntryOptionalValuesBoolValue'); +goog.require('proto.jspb.test.MapEntryOptionalValuesDoubleValue'); +goog.require('proto.jspb.test.MapEntryOptionalValuesEnumValue'); +goog.require('proto.jspb.test.MapEntryOptionalValuesMessageValue'); + +// CommonJS-LoadFromFile: test_pb proto.jspb.test +goog.require('proto.jspb.test.MapValueMessageNoBinary'); +goog.require('proto.jspb.test.TestMapFieldsNoBinary'); + +goog.requireType('jspb.Map'); + +/** + * Helper: check that the given map has exactly this set of (sorted) entries. + * @param {!jspb.Map} map + * @param {!Array>} entries + */ +function checkMapEquals(map, entries) { + var arr = map.toArray(); + assertEquals(arr.length, entries.length); + for (var i = 0; i < arr.length; i++) { + if (Array.isArray(arr[i])) { + assertTrue(Array.isArray(entries[i])); + assertArrayEquals(arr[i], entries[i]); + } else { + assertElementsEquals(arr[i], entries[i]); + } + } +} + +/** + * Converts an ES6 iterator to an array. + * @template T + * @param {!Iterator} iter an iterator + * @return {!Array} + */ +function toArray(iter) { + var arr = []; + while (true) { + var val = iter.next(); + if (val.done) { + break; + } + arr.push(val.value); + } + return arr; +} + + +/** + * Helper: generate test methods for this TestMapFields class. + * @param {?} msgInfo + * @param {?} submessageCtor + * @param {string} suffix + */ +function makeTests(msgInfo, submessageCtor, suffix) { + /** + * Helper: fill all maps on a TestMapFields. + * @param {?} msg + */ + var fillMapFields = function(msg) { + msg.getMapStringStringMap().set('asdf', 'jkl;').set('key 2', 'hello world'); + msg.getMapStringInt32Map().set('a', 1).set('b', -2); + msg.getMapStringInt64Map().set('c', 0x100000000).set('d', 0x200000000); + msg.getMapStringBoolMap().set('e', true).set('f', false); + msg.getMapStringDoubleMap().set('g', 3.14159).set('h', 2.71828); + msg.getMapStringEnumMap() + .set('i', proto.jspb.test.MapValueEnum.MAP_VALUE_BAR) + .set('j', proto.jspb.test.MapValueEnum.MAP_VALUE_BAZ); + msg.getMapStringMsgMap() + .set('k', new submessageCtor()) + .set('l', new submessageCtor()); + msg.getMapStringMsgMap().get('k').setFoo(42); + msg.getMapStringMsgMap().get('l').setFoo(84); + msg.getMapInt32StringMap().set(-1, 'a').set(42, 'b'); + msg.getMapInt64StringMap() + .set(0x123456789abc, 'c') + .set(0xcba987654321, 'd'); + msg.getMapBoolStringMap().set(false, 'e').set(true, 'f'); + }; + + /** + * Helper: check all maps on a TestMapFields. + * @param {?} msg + */ + var checkMapFields = function(msg) { + checkMapEquals( + msg.getMapStringStringMap(), + [['asdf', 'jkl;'], ['key 2', 'hello world']]); + checkMapEquals(msg.getMapStringInt32Map(), [['a', 1], ['b', -2]]); + checkMapEquals( + msg.getMapStringInt64Map(), [['c', 0x100000000], ['d', 0x200000000]]); + checkMapEquals(msg.getMapStringBoolMap(), [['e', true], ['f', false]]); + checkMapEquals( + msg.getMapStringDoubleMap(), [['g', 3.14159], ['h', 2.71828]]); + checkMapEquals(msg.getMapStringEnumMap(), [ + ['i', proto.jspb.test.MapValueEnum.MAP_VALUE_BAR], + ['j', proto.jspb.test.MapValueEnum.MAP_VALUE_BAZ] + ]); + checkMapEquals(msg.getMapInt32StringMap(), [[-1, 'a'], [42, 'b']]); + checkMapEquals( + msg.getMapInt64StringMap(), + [[0x123456789abc, 'c'], [0xcba987654321, 'd']]); + checkMapEquals(msg.getMapBoolStringMap(), [[false, 'e'], [true, 'f']]); + + assertEquals(msg.getMapStringMsgMap().getLength(), 2); + assertEquals(msg.getMapStringMsgMap().get('k').getFoo(), 42); + assertEquals(msg.getMapStringMsgMap().get('l').getFoo(), 84); + + var entries = toArray(msg.getMapStringMsgMap().entries()); + assertEquals(entries.length, 2); + entries.forEach(function(entry) { + var key = entry[0]; + var val = entry[1]; + assert(val === msg.getMapStringMsgMap().get(key)); + }); + + msg.getMapStringMsgMap().forEach(function(val, key) { + assert(val === msg.getMapStringMsgMap().get(key)); + }); + }; + + it('testMapStringStringField' + suffix, function() { + var msg = new msgInfo.constructor(); + assertEquals(msg.getMapStringStringMap().getLength(), 0); + assertEquals(msg.getMapStringInt32Map().getLength(), 0); + assertEquals(msg.getMapStringInt64Map().getLength(), 0); + assertEquals(msg.getMapStringBoolMap().getLength(), 0); + assertEquals(msg.getMapStringDoubleMap().getLength(), 0); + assertEquals(msg.getMapStringEnumMap().getLength(), 0); + assertEquals(msg.getMapStringMsgMap().getLength(), 0); + + // Re-create to clear out any internally-cached wrappers, etc. + msg = new msgInfo.constructor(); + var m = msg.getMapStringStringMap(); + assertEquals(m.has('asdf'), false); + assertEquals(m.get('asdf'), undefined); + m.set('asdf', 'hello world'); + assertEquals(m.has('asdf'), true); + assertEquals(m.get('asdf'), 'hello world'); + m.set('jkl;', 'key 2'); + assertEquals(m.has('jkl;'), true); + assertEquals(m.get('jkl;'), 'key 2'); + assertEquals(m.getLength(), 2); + var it = m.entries(); + assertElementsEquals(it.next().value, ['asdf', 'hello world']); + assertElementsEquals(it.next().value, ['jkl;', 'key 2']); + assertEquals(it.next().done, true); + checkMapEquals(m, [['asdf', 'hello world'], ['jkl;', 'key 2']]); + m.del('jkl;'); + assertEquals(m.has('jkl;'), false); + assertEquals(m.get('jkl;'), undefined); + assertEquals(m.getLength(), 1); + it = m.keys(); + assertEquals(it.next().value, 'asdf'); + assertEquals(it.next().done, true); + it = m.values(); + assertEquals(it.next().value, 'hello world'); + assertEquals(it.next().done, true); + + var count = 0; + m.forEach(function(value, key, map) { + assertEquals(map, m); + assertEquals(key, 'asdf'); + assertEquals(value, 'hello world'); + count++; + }); + assertEquals(count, 1); + + m.clear(); + assertEquals(m.getLength(), 0); + }); + + + /** + * Tests operations on maps with all key and value types. + */ + it('testAllMapTypes' + suffix, function() { + var msg = new msgInfo.constructor(); + fillMapFields(msg); + checkMapFields(msg); + }); + + + if (msgInfo.deserializeBinary) { + /** + * Tests serialization and deserialization in binary format. + */ + it('testBinaryFormat' + suffix, function() { + if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(10)) { + // IE8/9 currently doesn't support binary format because they lack + // TypedArray. + return; + } + + // Check that the format is correct. + var msg = new msgInfo.constructor(); + msg.getMapStringStringMap().set('A', 'a'); + var serialized = msg.serializeBinary(); + var expectedSerialized = [ + 0x0a, 0x6, // field 1 (map_string_string), delimited, length 6 + 0x0a, 0x1, // field 1 in submessage (key), delimited, length 1 + 0x41, // ASCII 'A' + 0x12, 0x1, // field 2 in submessage (value), delimited, length 1 + 0x61 // ASCII 'a' + ]; + assertEquals(serialized.length, expectedSerialized.length); + for (var i = 0; i < serialized.length; i++) { + assertEquals(serialized[i], expectedSerialized[i]); + } + + // Check that all map fields successfully round-trip. + msg = new msgInfo.constructor(); + fillMapFields(msg); + serialized = msg.serializeBinary(); + var decoded = msgInfo.deserializeBinary(serialized); + checkMapFields(decoded); + }); + + /** + * Tests deserialization of undefined map keys go to default values in + * binary format. + */ + it('testMapDeserializationForUndefinedKeys', function() { + var testMessageOptionalKeys = + new proto.jspb.test.TestMapFieldsOptionalKeys(); + var mapEntryStringKey = + new proto.jspb.test.MapEntryOptionalKeysStringKey(); + mapEntryStringKey.setValue('a'); + testMessageOptionalKeys.setMapStringString(mapEntryStringKey); + var mapEntryInt32Key = new proto.jspb.test.MapEntryOptionalKeysInt32Key(); + mapEntryInt32Key.setValue('b'); + testMessageOptionalKeys.setMapInt32String(mapEntryInt32Key); + var mapEntryInt64Key = new proto.jspb.test.MapEntryOptionalKeysInt64Key(); + mapEntryInt64Key.setValue('c'); + testMessageOptionalKeys.setMapInt64String(mapEntryInt64Key); + var mapEntryBoolKey = new proto.jspb.test.MapEntryOptionalKeysBoolKey(); + mapEntryBoolKey.setValue('d'); + testMessageOptionalKeys.setMapBoolString(mapEntryBoolKey); + var deserializedMessage = + msgInfo.deserializeBinary(testMessageOptionalKeys.serializeBinary()); + checkMapEquals(deserializedMessage.getMapStringStringMap(), [['', 'a']]); + checkMapEquals(deserializedMessage.getMapInt32StringMap(), [[0, 'b']]); + checkMapEquals(deserializedMessage.getMapInt64StringMap(), [[0, 'c']]); + checkMapEquals(deserializedMessage.getMapBoolStringMap(), [[false, 'd']]); + }); + + /** + * Tests deserialization of undefined map values go to default values in + * binary format. + */ + it('testMapDeserializationForUndefinedValues', function() { + var testMessageOptionalValues = + new proto.jspb.test.TestMapFieldsOptionalValues(); + var mapEntryStringValue = + new proto.jspb.test.MapEntryOptionalValuesStringValue(); + mapEntryStringValue.setKey('a'); + testMessageOptionalValues.setMapStringString(mapEntryStringValue); + var mapEntryInt32Value = + new proto.jspb.test.MapEntryOptionalValuesInt32Value(); + mapEntryInt32Value.setKey('b'); + testMessageOptionalValues.setMapStringInt32(mapEntryInt32Value); + var mapEntryInt64Value = + new proto.jspb.test.MapEntryOptionalValuesInt64Value(); + mapEntryInt64Value.setKey('c'); + testMessageOptionalValues.setMapStringInt64(mapEntryInt64Value); + var mapEntryBoolValue = + new proto.jspb.test.MapEntryOptionalValuesBoolValue(); + mapEntryBoolValue.setKey('d'); + testMessageOptionalValues.setMapStringBool(mapEntryBoolValue); + var mapEntryDoubleValue = + new proto.jspb.test.MapEntryOptionalValuesDoubleValue(); + mapEntryDoubleValue.setKey('e'); + testMessageOptionalValues.setMapStringDouble(mapEntryDoubleValue); + var mapEntryEnumValue = + new proto.jspb.test.MapEntryOptionalValuesEnumValue(); + mapEntryEnumValue.setKey('f'); + testMessageOptionalValues.setMapStringEnum(mapEntryEnumValue); + var mapEntryMessageValue = + new proto.jspb.test.MapEntryOptionalValuesMessageValue(); + mapEntryMessageValue.setKey('g'); + testMessageOptionalValues.setMapStringMsg(mapEntryMessageValue); + var deserializedMessage = msgInfo.deserializeBinary( + testMessageOptionalValues.serializeBinary()); + checkMapEquals(deserializedMessage.getMapStringStringMap(), [['a', '']]); + checkMapEquals(deserializedMessage.getMapStringInt32Map(), [['b', 0]]); + checkMapEquals(deserializedMessage.getMapStringInt64Map(), [['c', 0]]); + checkMapEquals(deserializedMessage.getMapStringBoolMap(), [['d', false]]); + checkMapEquals(deserializedMessage.getMapStringDoubleMap(), [['e', 0.0]]); + checkMapEquals(deserializedMessage.getMapStringEnumMap(), [['f', 0]]); + checkMapEquals(deserializedMessage.getMapStringMsgMap(), [['g', []]]); + }); + } + + + /** + * Exercises the lazy map<->underlying array sync. + */ + it('testLazyMapSync' + suffix, function() { + // Start with a JSPB array containing a few map entries. + var entries = [['a', 'entry 1'], ['c', 'entry 2'], ['b', 'entry 3']]; + var msg = new msgInfo.constructor([entries]); + assertEquals(entries.length, 3); + assertEquals(entries[0][0], 'a'); + assertEquals(entries[1][0], 'c'); + assertEquals(entries[2][0], 'b'); + msg.getMapStringStringMap().del('a'); + assertEquals(entries.length, 3); // not yet sync'd + msg.toArray(); // force a sync + assertEquals(entries.length, 2); + assertEquals(entries[0][0], 'b'); // now in sorted order + assertEquals(entries[1][0], 'c'); + + var a = msg.toArray(); + assertEquals(a[0], entries); // retains original reference + }); + + /** + * Returns IteratorIterables for entries(), keys() and values(). + */ + it('testIteratorIterables' + suffix, function() { + var msg = new msgInfo.constructor(); + var m = msg.getMapStringStringMap(); + m.set('key1', 'value1'); + m.set('key2', 'value2'); + var entryIterator = m.entries(); + assertElementsEquals(entryIterator.next().value, ['key1', 'value1']); + assertElementsEquals(entryIterator.next().value, ['key2', 'value2']); + assertEquals(entryIterator.next().done, true); + + try { + var entryIterable = m.entries()[Symbol.iterator](); + assertElementsEquals(entryIterable.next().value, ['key1', 'value1']); + assertElementsEquals(entryIterable.next().value, ['key2', 'value2']); + assertEquals(entryIterable.next().done, true); + } catch (err) { + // jspb.Map.ArrayIteratorIterable_.prototype[Symbol.iterator] may be + // undefined in some environment. + if (err.name != 'TypeError' && err.name != 'ReferenceError') { + throw err; + } + } + + var keyIterator = m.keys(); + assertEquals(keyIterator.next().value, 'key1'); + assertEquals(keyIterator.next().value, 'key2'); + assertEquals(keyIterator.next().done, true); + + try { + var keyIterable = m.keys()[Symbol.iterator](); + assertEquals(keyIterable.next().value, 'key1'); + assertEquals(keyIterable.next().value, 'key2'); + assertEquals(keyIterable.next().done, true); + } catch (err) { + // jspb.Map.ArrayIteratorIterable_.prototype[Symbol.iterator] may be + // undefined in some environment. + if (err.name != 'TypeError' && err.name != 'ReferenceError') { + throw err; + } + } + var valueIterator = m.values(); + assertEquals(valueIterator.next().value, 'value1'); + assertEquals(valueIterator.next().value, 'value2'); + assertEquals(valueIterator.next().done, true); + + try { + var valueIterable = m.values()[Symbol.iterator](); + assertEquals(valueIterable.next().value, 'value1'); + assertEquals(valueIterable.next().value, 'value2'); + assertEquals(valueIterable.next().done, true); + } catch (err) { + // jspb.Map.ArrayIteratorIterable_.prototype[Symbol.iterator] may be + // undefined in some environment. + if (err.name != 'TypeError' && err.name != 'ReferenceError') { + throw err; + } + } + }); +} + +describe('mapsTest', function() { + makeTests( + { + constructor: proto.jspb.test.TestMapFields, + deserializeBinary: proto.jspb.test.TestMapFields.deserializeBinary + }, + proto.jspb.test.MapValueMessage, '_Binary'); + makeTests( + { + constructor: proto.jspb.test.TestMapFieldsNoBinary, + deserializeBinary: null + }, + proto.jspb.test.MapValueMessageNoBinary, '_NoBinary'); +}); diff --git a/tools/env-vars-generator/protobuf/js/message_test.js b/tools/env-vars-generator/protobuf/js/message_test.js new file mode 100644 index 0000000..2a524de --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/message_test.js @@ -0,0 +1,1111 @@ +// 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. + +// Test suite is written using Jasmine -- see http://jasmine.github.io/ + +goog.setTestOnly(); + +goog.require('goog.testing.PropertyReplacer'); +goog.require('goog.testing.asserts'); +goog.require('goog.userAgent'); + +// CommonJS-LoadFromFile: google-protobuf jspb +goog.require('jspb.Message'); + +// CommonJS-LoadFromFile: test15_pb proto.jspb.filenametest.package1 +goog.require('proto.jspb.filenametest.package1.b'); + +// CommonJS-LoadFromFile: test14_pb proto.jspb.filenametest.package2 +goog.require('proto.jspb.filenametest.package2.TestMessage'); + +// CommonJS-LoadFromFile: test13_pb proto.jspb.filenametest.package1 +goog.require('proto.jspb.filenametest.package1.a'); +goog.require('proto.jspb.filenametest.package1.TestMessage'); + +// CommonJS-LoadFromFile: test12_pb proto.jspb.circulartest +goog.require('proto.jspb.circulartest.ExtensionContainingType1'); +goog.require('proto.jspb.circulartest.ExtensionContainingType2'); +goog.require('proto.jspb.circulartest.ExtensionField1'); +goog.require('proto.jspb.circulartest.ExtensionField2'); +goog.require('proto.jspb.circulartest.ExtensionField3'); +goog.require('proto.jspb.circulartest.MapField1'); +goog.require('proto.jspb.circulartest.MapField2'); +goog.require('proto.jspb.circulartest.MessageField1'); +goog.require('proto.jspb.circulartest.MessageField2'); +goog.require('proto.jspb.circulartest.NestedEnum1'); +goog.require('proto.jspb.circulartest.NestedEnum2'); +goog.require('proto.jspb.circulartest.NestedMessage1'); +goog.require('proto.jspb.circulartest.NestedMessage2'); +goog.require('proto.jspb.circulartest.RepeatedMessageField1'); +goog.require('proto.jspb.circulartest.RepeatedMessageField2'); + +// CommonJS-LoadFromFile: test11_pb proto.jspb.exttest.reverse +goog.require('proto.jspb.exttest.reverse.TestExtensionReverseOrderMessage1'); +goog.require('proto.jspb.exttest.reverse.TestExtensionReverseOrderMessage2'); +goog.require('proto.jspb.exttest.reverse.c'); + +// CommonJS-LoadFromFile: test8_pb proto.jspb.exttest.nested +goog.require('proto.jspb.exttest.nested.TestNestedExtensionsMessage'); +goog.require('proto.jspb.exttest.nested.TestOuterMessage'); + +// CommonJS-LoadFromFile: test5_pb proto.jspb.exttest.beta +goog.require('proto.jspb.exttest.beta.floatingStrField'); + +// CommonJS-LoadFromFile: test3_pb proto.jspb.exttest +goog.require('proto.jspb.exttest.floatingMsgField'); + +// CommonJS-LoadFromFile: test4_pb proto.jspb.exttest +goog.require('proto.jspb.exttest.floatingMsgFieldTwo'); + +// CommonJS-LoadFromFile: test_pb proto.jspb.test +goog.require('proto.jspb.test.BooleanFields'); +goog.require('proto.jspb.test.CloneExtension'); +goog.require('proto.jspb.test.Complex'); +goog.require('proto.jspb.test.DefaultValues'); +goog.require('proto.jspb.test.Empty'); +goog.require('proto.jspb.test.EnumContainer'); +goog.require('proto.jspb.test.floatingMsgField'); +goog.require('proto.jspb.test.FloatingPointFields'); +goog.require('proto.jspb.test.floatingStrField'); +goog.require('proto.jspb.test.HasExtensions'); +goog.require('proto.jspb.test.IndirectExtension'); +goog.require('proto.jspb.test.IsExtension'); +goog.require('proto.jspb.test.OptionalFields'); +goog.require('proto.jspb.test.OuterEnum'); +goog.require('proto.jspb.test.OuterMessage.Complex'); +goog.require('proto.jspb.test.Simple1'); +goog.require('proto.jspb.test.Simple2'); +goog.require('proto.jspb.test.SpecialCases'); +goog.require('proto.jspb.test.TestClone'); +goog.require('proto.jspb.test.TestCloneExtension'); +goog.require('proto.jspb.test.TestEndsWithBytes'); +goog.require('proto.jspb.test.TestGroup'); +goog.require('proto.jspb.test.TestGroup1'); +goog.require('proto.jspb.test.TestLastFieldBeforePivot'); +goog.require('proto.jspb.test.TestMessageWithOneof'); +goog.require('proto.jspb.test.TestReservedNames'); +goog.require('proto.jspb.test.TestReservedNamesExtension'); + +// CommonJS-LoadFromFile: test2_pb proto.jspb.test +goog.require('proto.jspb.test.ExtensionMessage'); +goog.require('proto.jspb.test.TestExtensionsMessage'); + +goog.require('proto.jspb.test.TestAllowAliasEnum'); +// CommonJS-LoadFromFile: testlargenumbers_pb proto.jspb.test +goog.require('proto.jspb.test.MessageWithLargeFieldNumbers'); + +goog.require('proto.jspb.test.simple1'); + +describe('Message test suite', function() { + var stubs = new goog.testing.PropertyReplacer(); + + beforeEach(function() { + stubs.set(jspb.Message, 'SERIALIZE_EMPTY_TRAILING_FIELDS', false); + }); + + afterEach(function() { + stubs.reset(); + }); + + it('testEmptyProto', function() { + var empty1 = new proto.jspb.test.Empty([]); + var empty2 = new proto.jspb.test.Empty([]); + assertObjectEquals({}, empty1.toObject()); + assertObjectEquals('Message should not be corrupted:', empty2, empty1); + }); + + it('testTopLevelEnum', function() { + var response = new proto.jspb.test.EnumContainer([]); + response.setOuterEnum(proto.jspb.test.OuterEnum.FOO); + assertEquals(proto.jspb.test.OuterEnum.FOO, response.getOuterEnum()); + }); + + it('testByteStrings', function() { + var data = new proto.jspb.test.DefaultValues([]); + data.setBytesField('some_bytes'); + assertEquals('some_bytes', data.getBytesField()); + }); + + it('testComplexConversion', function() { + var data1 = ['a', , , [, 11], [[, 22], [, 33]], , ['s1', 's2'], , 1]; + var data2 = ['a', , , [, 11], [[, 22], [, 33]], , ['s1', 's2'], , 1]; + var foo = new proto.jspb.test.Complex(data1); + var bar = new proto.jspb.test.Complex(data2); + var result = foo.toObject(); + assertObjectEquals( + { + aString: 'a', + anOutOfOrderBool: true, + aNestedMessage: {anInt: 11}, + aRepeatedMessageList: [{anInt: 22}, {anInt: 33}], + aRepeatedStringList: ['s1', 's2'], + aFloatingPointField: undefined, + }, + result); + + // Now test with the jspb instances included. + result = foo.toObject(true /* opt_includeInstance */); + assertObjectEquals( + { + aString: 'a', + anOutOfOrderBool: true, + aNestedMessage: + {anInt: 11, $jspbMessageInstance: foo.getANestedMessage()}, + aRepeatedMessageList: [ + {anInt: 22, $jspbMessageInstance: foo.getARepeatedMessageList()[0]}, + {anInt: 33, $jspbMessageInstance: foo.getARepeatedMessageList()[1]} + ], + aRepeatedStringList: ['s1', 's2'], + aFloatingPointField: undefined, + $jspbMessageInstance: foo + }, + result); + }); + + it('testMissingFields', function() { + var foo = new proto.jspb.test.Complex([ + undefined, undefined, undefined, [], undefined, undefined, undefined, + undefined + ]); + var bar = new proto.jspb.test.Complex([ + undefined, undefined, undefined, [], undefined, undefined, undefined, + undefined + ]); + var result = foo.toObject(); + assertObjectEquals( + { + aString: undefined, + anOutOfOrderBool: undefined, + aNestedMessage: {anInt: undefined}, + // Note: JsPb converts undefined repeated fields to empty arrays. + aRepeatedMessageList: [], + aRepeatedStringList: [], + aFloatingPointField: undefined, + }, + result); + }); + + it('testNestedComplexMessage', function() { + // Instantiate the message and set a unique field, just to ensure that we + // are not getting jspb.test.Complex instead. + var msg = new proto.jspb.test.OuterMessage.Complex(); + msg.setInnerComplexField(5); + }); + + it('testSpecialCases', function() { + // Note: Some property names are reserved in JavaScript. + // These names are converted to the Js property named pb_. + var special = new proto.jspb.test.SpecialCases( + ['normal', 'default', 'function', 'var']); + var result = special.toObject(); + assertObjectEquals( + { + normal: 'normal', + pb_default: 'default', + pb_function: 'function', + pb_var: 'var' + }, + result); + }); + + it('testDefaultValues', function() { + var defaultString = 'default<>\'"abc'; + var response = new proto.jspb.test.DefaultValues(); + + // Test toObject + var expectedObject = { + stringField: defaultString, + boolField: true, + intField: 11, + enumField: 13, + emptyField: '', + bytesField: 'bW9v' + }; + assertObjectEquals(expectedObject, response.toObject()); + + + // Test getters + response = new proto.jspb.test.DefaultValues(); + assertEquals(defaultString, response.getStringField()); + assertEquals(true, response.getBoolField()); + assertEquals(11, response.getIntField()); + assertEquals(13, response.getEnumField()); + assertEquals('', response.getEmptyField()); + assertEquals('bW9v', response.getBytesField()); + + function makeDefault(values) { + return new proto.jspb.test.DefaultValues(values); + } + + // Test with undefined values, + // Use push to workaround IE treating undefined array elements as holes. + response = makeDefault([undefined, undefined, undefined, undefined]); + assertEquals(defaultString, response.getStringField()); + assertEquals(true, response.getBoolField()); + assertEquals(11, response.getIntField()); + assertEquals(13, response.getEnumField()); + assertFalse(response.hasStringField()); + assertFalse(response.hasBoolField()); + assertFalse(response.hasIntField()); + assertFalse(response.hasEnumField()); + + // Test with null values, as would be returned by a JSON serializer. + response = makeDefault([null, null, null, null]); + assertEquals(defaultString, response.getStringField()); + assertEquals(true, response.getBoolField()); + assertEquals(11, response.getIntField()); + assertEquals(13, response.getEnumField()); + assertFalse(response.hasStringField()); + assertFalse(response.hasBoolField()); + assertFalse(response.hasIntField()); + assertFalse(response.hasEnumField()); + + // Test with false-like values. + response = makeDefault(['', false, 0, 0]); + assertEquals('', response.getStringField()); + assertEquals(false, response.getBoolField()); + assertEquals(true, response.getIntField() == 0); + assertEquals(true, response.getEnumField() == 0); + assertTrue(response.hasStringField()); + assertTrue(response.hasBoolField()); + assertTrue(response.hasIntField()); + assertTrue(response.hasEnumField()); + + // Test that clearing the values reverts them to the default state. + response = makeDefault(['blah', false, 111, 77]); + response.clearStringField(); + response.clearBoolField(); + response.clearIntField(); + response.clearEnumField(); + assertEquals(defaultString, response.getStringField()); + assertEquals(true, response.getBoolField()); + assertEquals(11, response.getIntField()); + assertEquals(13, response.getEnumField()); + assertFalse(response.hasStringField()); + assertFalse(response.hasBoolField()); + assertFalse(response.hasIntField()); + assertFalse(response.hasEnumField()); + + // Test that setFoo(null) clears the values. + response = makeDefault(['blah', false, 111, 77]); + response.setStringField(null); + response.setBoolField(null); + response.setIntField(undefined); + response.setEnumField(undefined); + assertEquals(defaultString, response.getStringField()); + assertEquals(true, response.getBoolField()); + assertEquals(11, response.getIntField()); + assertEquals(13, response.getEnumField()); + assertFalse(response.hasStringField()); + assertFalse(response.hasBoolField()); + assertFalse(response.hasIntField()); + assertFalse(response.hasEnumField()); + }); + + it('testEqualsSimple', function() { + var s1 = new proto.jspb.test.Simple1(['hi']); + assertTrue(jspb.Message.equals(s1, new proto.jspb.test.Simple1(['hi']))); + assertFalse(jspb.Message.equals(s1, new proto.jspb.test.Simple1(['bye']))); + var s1b = new proto.jspb.test.Simple1(['hi', ['hello']]); + assertTrue(jspb.Message.equals( + s1b, new proto.jspb.test.Simple1(['hi', ['hello']]))); + assertTrue(jspb.Message.equals(s1b, new proto.jspb.test.Simple1([ + 'hi', ['hello', undefined, undefined, undefined] + ]))); + assertFalse(jspb.Message.equals( + s1b, new proto.jspb.test.Simple1(['no', ['hello']]))); + // Test with messages of different types + var s2 = new proto.jspb.test.Simple2(['hi']); + assertFalse(jspb.Message.equals(s1, s2)); + }); + + it('testEquals_softComparison', function() { + var s1 = new proto.jspb.test.Simple1(['hi', [], null]); + assertTrue( + jspb.Message.equals(s1, new proto.jspb.test.Simple1(['hi', []]))); + + var s1b = new proto.jspb.test.Simple1(['hi', [], true]); + assertTrue( + jspb.Message.equals(s1b, new proto.jspb.test.Simple1(['hi', [], 1]))); + }); + + it('testEqualsComplex', function() { + var data1 = ['a', , , [, 11], [[, 22], [, 33]], , ['s1', 's2'], , 1]; + var data2 = ['a', , , [, 11], [[, 22], [, 34]], , ['s1', 's2'], , 1]; + var data3 = ['a', , , [, 11], [[, 22]], , ['s1', 's2'], , 1]; + var data4 = ['hi']; + var c1a = new proto.jspb.test.Complex(data1); + var c1b = new proto.jspb.test.Complex(data1); + var c2 = new proto.jspb.test.Complex(data2); + var c3 = new proto.jspb.test.Complex(data3); + var s1 = new proto.jspb.test.Simple1(data4); + + assertTrue(jspb.Message.equals(c1a, c1b)); + assertFalse(jspb.Message.equals(c1a, c2)); + assertFalse(jspb.Message.equals(c2, c3)); + assertFalse(jspb.Message.equals(c1a, s1)); + }); + + it('testEqualsExtensionsConstructed', function() { + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions([]), + new proto.jspb.test.HasExtensions([{}]))); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]))); + assertFalse(jspb.Message.equals( + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'b'}]}]))); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}]))); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions([, , , {100: [{200: 'a'}]}]))); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions([, , , {100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}]))); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions(['hi', , , {100: [{200: 'a'}]}]))); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions(['hi', , , {100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]))); + }); + + it('testEqualsExtensionsUnconstructed', function() { + assertTrue(jspb.Message.compareFields([], [{}])); + assertTrue(jspb.Message.compareFields([, , , {}], [])); + assertTrue(jspb.Message.compareFields([, , , {}], [, , {}])); + assertTrue(jspb.Message.compareFields( + ['hi', {100: [{200: 'a'}]}], ['hi', {100: [{200: 'a'}]}])); + assertFalse(jspb.Message.compareFields( + ['hi', {100: [{200: 'a'}]}], ['hi', {100: [{200: 'b'}]}])); + assertTrue(jspb.Message.compareFields( + [{100: [{200: 'a'}]}], [{100: [{200: 'a'}]}])); + assertTrue(jspb.Message.compareFields( + [{100: [{200: 'a'}]}], [, , , {100: [{200: 'a'}]}])); + assertTrue(jspb.Message.compareFields( + [, , , {100: [{200: 'a'}]}], [{100: [{200: 'a'}]}])); + assertTrue(jspb.Message.compareFields( + ['hi', {100: [{200: 'a'}]}], ['hi', , , {100: [{200: 'a'}]}])); + assertTrue(jspb.Message.compareFields( + ['hi', , , {100: [{200: 'a'}]}], ['hi', {100: [{200: 'a'}]}])); + }); + + it('testInitializeMessageWithLastFieldNull', function() { + // This tests for regression to bug http://b/117298778 + var msg = new proto.jspb.test.TestLastFieldBeforePivot([null]); + assertNotUndefined(msg.getLastFieldBeforePivot()); + }); + + 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']]); + var soymap = jspb.Message.toMap( + [p1, p2], proto.jspb.test.Simple1.prototype.getAString, + proto.jspb.test.Simple1.prototype.toObject); + assertEquals('k', soymap['k'].aString); + assertArrayEquals(['v'], soymap['k'].aRepeatedStringList); + var protomap = jspb.Message.toMap( + [p1, p2], proto.jspb.test.Simple1.prototype.getAString); + assertEquals('k', protomap['k'].getAString()); + assertArrayEquals(['v'], protomap['k'].getARepeatedStringList()); + }); + + it('testClone', function() { + var supportsUint8Array = + !goog.userAgent.IE || goog.userAgent.isVersionOrHigher('10'); + var original = new proto.jspb.test.TestClone(); + original.setStr('v1'); + var simple1 = new proto.jspb.test.Simple1(['x1', ['y1', 'z1']]); + var simple2 = new proto.jspb.test.Simple1(['x2', ['y2', 'z2']]); + var simple3 = new proto.jspb.test.Simple1(['x3', ['y3', 'z3']]); + original.setSimple1(simple1); + original.setSimple2List([simple2, simple3]); + var bytes1 = supportsUint8Array ? new Uint8Array([1, 2, 3]) : '123'; + original.setBytesField(bytes1); + var extension = new proto.jspb.test.CloneExtension(); + extension.setExt('e1'); + original.setExtension(proto.jspb.test.IsExtension.extField, extension); + var clone = original.clone(); + assertArrayEquals( + [ + 'v1', , ['x1', ['y1', 'z1']], , + [['x2', ['y2', 'z2']], ['x3', ['y3', 'z3']]], bytes1, , + {100: [, 'e1']} + ], + clone.toArray()); + clone.setStr('v2'); + var simple4 = new proto.jspb.test.Simple1(['a1', ['b1', 'c1']]); + var simple5 = new proto.jspb.test.Simple1(['a2', ['b2', 'c2']]); + var simple6 = new proto.jspb.test.Simple1(['a3', ['b3', 'c3']]); + clone.setSimple1(simple4); + clone.setSimple2List([simple5, simple6]); + if (supportsUint8Array) { + clone.getBytesField()[0] = 4; + assertObjectEquals(bytes1, original.getBytesField()); + } + var bytes2 = supportsUint8Array ? new Uint8Array([4, 5, 6]) : '456'; + clone.setBytesField(bytes2); + var newExtension = new proto.jspb.test.CloneExtension(); + newExtension.setExt('e2'); + clone.setExtension(proto.jspb.test.CloneExtension.extField, newExtension); + assertArrayEquals( + [ + 'v2', , ['a1', ['b1', 'c1']], , + [['a2', ['b2', 'c2']], ['a3', ['b3', 'c3']]], bytes2, , + {100: [, 'e2']} + ], + clone.toArray()); + assertArrayEquals( + [ + 'v1', , ['x1', ['y1', 'z1']], , + [['x2', ['y2', 'z2']], ['x3', ['y3', 'z3']]], bytes1, , + {100: [, 'e1']} + ], + original.toArray()); + }); + + it('testCopyInto', function() { + var supportsUint8Array = + !goog.userAgent.IE || goog.userAgent.isVersionOrHigher('10'); + var original = new proto.jspb.test.TestClone(); + original.setStr('v1'); + var dest = new proto.jspb.test.TestClone(); + dest.setStr('override'); + var simple1 = new proto.jspb.test.Simple1(['x1', ['y1', 'z1']]); + var simple2 = new proto.jspb.test.Simple1(['x2', ['y2', 'z2']]); + var simple3 = new proto.jspb.test.Simple1(['x3', ['y3', 'z3']]); + var destSimple1 = new proto.jspb.test.Simple1(['ox1', ['oy1', 'oz1']]); + var destSimple2 = new proto.jspb.test.Simple1(['ox2', ['oy2', 'oz2']]); + var destSimple3 = new proto.jspb.test.Simple1(['ox3', ['oy3', 'oz3']]); + original.setSimple1(simple1); + original.setSimple2List([simple2, simple3]); + dest.setSimple1(destSimple1); + dest.setSimple2List([destSimple2, destSimple3]); + var bytes1 = supportsUint8Array ? new Uint8Array([1, 2, 3]) : '123'; + var bytes2 = supportsUint8Array ? new Uint8Array([4, 5, 6]) : '456'; + original.setBytesField(bytes1); + dest.setBytesField(bytes2); + var extension = new proto.jspb.test.CloneExtension(); + extension.setExt('e1'); + original.setExtension(proto.jspb.test.CloneExtension.extField, extension); + + jspb.Message.copyInto(original, dest); + assertArrayEquals(original.toArray(), dest.toArray()); + assertEquals('x1', dest.getSimple1().getAString()); + assertEquals( + 'e1', + dest.getExtension(proto.jspb.test.CloneExtension.extField).getExt()); + dest.getSimple1().setAString('new value'); + assertNotEquals( + dest.getSimple1().getAString(), original.getSimple1().getAString()); + if (supportsUint8Array) { + dest.getBytesField()[0] = 7; + assertObjectEquals(bytes1, original.getBytesField()); + assertObjectEquals(new Uint8Array([7, 2, 3]), dest.getBytesField()); + } else { + dest.setBytesField('789'); + assertObjectEquals(bytes1, original.getBytesField()); + assertObjectEquals('789', dest.getBytesField()); + } + dest.getExtension(proto.jspb.test.CloneExtension.extField) + .setExt('new value'); + assertNotEquals( + dest.getExtension(proto.jspb.test.CloneExtension.extField).getExt(), + original.getExtension(proto.jspb.test.CloneExtension.extField) + .getExt()); + }); + + it('testCopyInto_notSameType', function() { + var a = new proto.jspb.test.TestClone(); + var b = new proto.jspb.test.Simple1(['str', ['s1', 's2']]); + + var e = assertThrows(function() { + jspb.Message.copyInto(a, b); + }); + assertContains('should have the same type', e.message); + }); + + it('testExtensions', function() { + var extension1 = new proto.jspb.test.IsExtension(['ext1field']); + var extension2 = new proto.jspb.test.Simple1(['str', ['s1', 's2']]); + var extendable = new proto.jspb.test.HasExtensions(['v1', 'v2', 'v3']); + extendable.setExtension(proto.jspb.test.IsExtension.extField, extension1); + extendable.setExtension( + proto.jspb.test.IndirectExtension.simple, extension2); + extendable.setExtension(proto.jspb.test.IndirectExtension.str, 'xyzzy'); + extendable.setExtension( + proto.jspb.test.IndirectExtension.repeatedStrList, ['a', 'b']); + var s1 = new proto.jspb.test.Simple1(['foo', ['s1', 's2']]); + var s2 = new proto.jspb.test.Simple1(['bar', ['t1', 't2']]); + extendable.setExtension( + proto.jspb.test.IndirectExtension.repeatedSimpleList, [s1, s2]); + assertObjectEquals( + extension1, + extendable.getExtension(proto.jspb.test.IsExtension.extField)); + assertObjectEquals( + extension2, + extendable.getExtension(proto.jspb.test.IndirectExtension.simple)); + assertObjectEquals( + 'xyzzy', + extendable.getExtension(proto.jspb.test.IndirectExtension.str)); + assertObjectEquals( + ['a', 'b'], + extendable.getExtension( + proto.jspb.test.IndirectExtension.repeatedStrList)); + assertObjectEquals( + [s1, s2], + extendable.getExtension( + proto.jspb.test.IndirectExtension.repeatedSimpleList)); + // Not supported yet, but it should work... + extendable.setExtension(proto.jspb.test.IndirectExtension.simple, null); + assertNull( + extendable.getExtension(proto.jspb.test.IndirectExtension.simple)); + extendable.setExtension(proto.jspb.test.IndirectExtension.str, null); + assertNull(extendable.getExtension(proto.jspb.test.IndirectExtension.str)); + + + // Extension fields with jspb.ignore = true are ignored. + assertUndefined(proto.jspb.test.IndirectExtension['ignored']); + assertUndefined(proto.jspb.test.HasExtensions['ignoredFloating']); + }); + + it('testFloatingExtensions', function() { + // From an autogenerated container. + var extendable = new proto.jspb.test.HasExtensions(['v1', 'v2', 'v3']); + var extension = new proto.jspb.test.Simple1(['foo', ['s1', 's2']]); + extendable.setExtension(proto.jspb.test.simple1, extension); + assertObjectEquals( + extension, extendable.getExtension(proto.jspb.test.simple1)); + + // From _lib mode. + extension = new proto.jspb.test.ExtensionMessage(['s1']); + extendable = new proto.jspb.test.TestExtensionsMessage([16]); + extendable.setExtension(proto.jspb.test.floatingMsgField, extension); + extendable.setExtension(proto.jspb.test.floatingStrField, 's2'); + assertObjectEquals( + extension, extendable.getExtension(proto.jspb.test.floatingMsgField)); + assertObjectEquals( + 's2', extendable.getExtension(proto.jspb.test.floatingStrField)); + assertNotUndefined(proto.jspb.exttest.floatingMsgField); + assertNotUndefined(proto.jspb.exttest.floatingMsgFieldTwo); + assertNotUndefined(proto.jspb.exttest.beta.floatingStrField); + }); + + it('testNestedExtensions', function() { + var extendable = + new proto.jspb.exttest.nested.TestNestedExtensionsMessage(); + var extension = + new proto.jspb.exttest.nested.TestOuterMessage.NestedExtensionMessage( + ['s1']); + extendable.setExtension( + proto.jspb.exttest.nested.TestOuterMessage.innerExtension, extension); + assertObjectEquals( + extension, + extendable.getExtension( + proto.jspb.exttest.nested.TestOuterMessage.innerExtension)); + }); + + it('testToObject_extendedObject', function() { + var extension1 = new proto.jspb.test.IsExtension(['ext1field']); + var extension2 = new proto.jspb.test.Simple1(['str', ['s1', 's2'], true]); + var extendable = new proto.jspb.test.HasExtensions(['v1', 'v2', 'v3']); + extendable.setExtension(proto.jspb.test.IsExtension.extField, extension1); + extendable.setExtension( + proto.jspb.test.IndirectExtension.simple, extension2); + extendable.setExtension(proto.jspb.test.IndirectExtension.str, 'xyzzy'); + extendable.setExtension( + proto.jspb.test.IndirectExtension.repeatedStrList, ['a', 'b']); + var s1 = new proto.jspb.test.Simple1(['foo', ['s1', 's2'], true]); + var s2 = new proto.jspb.test.Simple1(['bar', ['t1', 't2'], false]); + extendable.setExtension( + proto.jspb.test.IndirectExtension.repeatedSimpleList, [s1, s2]); + assertObjectEquals( + { + str1: 'v1', + str2: 'v2', + str3: 'v3', + extField: {ext1: 'ext1field'}, + simple: { + aString: 'str', + aRepeatedStringList: ['s1', 's2'], + aBoolean: true + }, + str: 'xyzzy', + repeatedStrList: ['a', 'b'], + repeatedSimpleList: [ + {aString: 'foo', aRepeatedStringList: ['s1', 's2'], aBoolean: true}, + {aString: 'bar', aRepeatedStringList: ['t1', 't2'], aBoolean: false} + ] + }, + extendable.toObject()); + + // Now, with instances included. + assertObjectEquals( + { + str1: 'v1', + str2: 'v2', + str3: 'v3', + extField: { + ext1: 'ext1field', + $jspbMessageInstance: + extendable.getExtension(proto.jspb.test.IsExtension.extField) + }, + simple: { + aString: 'str', + aRepeatedStringList: ['s1', 's2'], + aBoolean: true, + $jspbMessageInstance: extendable.getExtension( + proto.jspb.test.IndirectExtension.simple) + }, + str: 'xyzzy', + repeatedStrList: ['a', 'b'], + repeatedSimpleList: [ + { + aString: 'foo', + aRepeatedStringList: ['s1', 's2'], + aBoolean: true, + $jspbMessageInstance: s1 + }, + { + aString: 'bar', + aRepeatedStringList: ['t1', 't2'], + aBoolean: false, + $jspbMessageInstance: s2 + } + ], + $jspbMessageInstance: extendable + }, + extendable.toObject(true /* opt_includeInstance */)); + }); + + it('testInitialization_emptyArray', function() { + var msg = new proto.jspb.test.HasExtensions([]); + assertArrayEquals([], msg.toArray()); + }); + + it('testInitialization_justExtensionObject', function() { + var msg = new proto.jspb.test.Empty([{1: 'hi'}]); + // The extensionObject is not moved from its original location. + assertArrayEquals([{1: 'hi'}], msg.toArray()); + }); + + it('testInitialization_incompleteList', function() { + var msg = new proto.jspb.test.Empty([1, {4: 'hi'}]); + // The extensionObject is not moved from its original location. + assertArrayEquals([1, {4: 'hi'}], msg.toArray()); + }); + + it('testInitialization_forwardCompatible', function() { + var msg = new proto.jspb.test.Empty([1, 2, 3, {1: 'hi'}]); + assertArrayEquals([1, 2, 3, {1: 'hi'}], msg.toArray()); + }); + + it('testExtendedMessageEnsureObject', + /** @suppress {visibility} */ function() { + var data = + new proto.jspb.test.HasExtensions(['str1', {'a_key': 'an_object'}]); + assertEquals('an_object', data.extensionObject_['a_key']); + }); + + it('testToObject_hasExtensionField', function() { + var data = + new proto.jspb.test.HasExtensions(['str1', {100: ['ext1'], 102: ''}]); + var obj = data.toObject(); + assertEquals('str1', obj.str1); + assertEquals('ext1', obj.extField.ext1); + assertEquals('', obj.str); + }); + + it('testGetExtension', function() { + var data = new proto.jspb.test.HasExtensions(['str1', {100: ['ext1']}]); + assertEquals('str1', data.getStr1()); + var extension = data.getExtension(proto.jspb.test.IsExtension.extField); + assertNotNull(extension); + assertEquals('ext1', extension.getExt1()); + }); + + it('testSetExtension', function() { + var data = new proto.jspb.test.HasExtensions(); + var extensionMessage = new proto.jspb.test.IsExtension(['is_extension']); + data.setExtension(proto.jspb.test.IsExtension.extField, extensionMessage); + var obj = data.toObject(); + assertNotNull(data.getExtension(proto.jspb.test.IsExtension.extField)); + assertEquals('is_extension', obj.extField.ext1); + }); + + /** + * Note that group is long deprecated, we only support it because JsPb has + * a goal of being able to generate JS classes for all proto descriptors. + */ + it('testGroups', function() { + var group = new proto.jspb.test.TestGroup(); + var someGroup = new proto.jspb.test.TestGroup.RepeatedGroup(); + someGroup.setId('g1'); + someGroup.setSomeBoolList([true, false]); + group.setRepeatedGroupList([someGroup]); + var groups = group.getRepeatedGroupList(); + assertEquals('g1', groups[0].getId()); + assertObjectEquals([true, false], groups[0].getSomeBoolList()); + assertObjectEquals( + {id: 'g1', someBoolList: [true, false]}, groups[0].toObject()); + assertObjectEquals( + { + repeatedGroupList: [{id: 'g1', someBoolList: [true, false]}], + requiredGroup: {id: undefined}, + optionalGroup: undefined, + requiredSimple: {aRepeatedStringList: [], aString: undefined}, + optionalSimple: undefined, + id: undefined + }, + group.toObject()); + var group1 = new proto.jspb.test.TestGroup1(); + group1.setGroup(someGroup); + assertEquals(someGroup, group1.getGroup()); + }); + + it('testNonExtensionFieldsAfterExtensionRange', function() { + var data = [{'1': 'a_string'}]; + var message = new proto.jspb.test.Complex(data); + assertArrayEquals([], message.getARepeatedStringList()); + }); + + it('testReservedGetterNames', function() { + var message = new proto.jspb.test.TestReservedNames(); + message.setExtension$(11); + message.setExtension(proto.jspb.test.TestReservedNamesExtension.foo, 12); + assertEquals(11, message.getExtension$()); + assertEquals( + 12, + message.getExtension(proto.jspb.test.TestReservedNamesExtension.foo)); + assertObjectEquals({extension: 11, foo: 12}, message.toObject()); + }); + + it('testInitializeMessageWithUnsetOneof', function() { + var message = new proto.jspb.test.TestMessageWithOneof([]); + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase + .PARTIAL_ONEOF_NOT_SET, + message.getPartialOneofCase()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.RecursiveOneofCase + .RECURSIVE_ONEOF_NOT_SET, + message.getRecursiveOneofCase()); + }); + + it('testUnsetsOneofCaseWhenFieldIsCleared', function() { + var message = new proto.jspb.test.TestMessageWithOneof; + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase + .PARTIAL_ONEOF_NOT_SET, + message.getPartialOneofCase()); + + message.setPone('hi'); + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PONE, + message.getPartialOneofCase()); + + message.clearPone(); + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase + .PARTIAL_ONEOF_NOT_SET, + message.getPartialOneofCase()); + }); + + it('testFloatingPointFieldsSupportNan', function() { + var assertNan = function(x) { + assertTrue( + 'Expected ' + x + ' (' + goog.typeOf(x) + ') to be NaN.', + typeof x === 'number' && isNaN(x)); + }; + + var message = new proto.jspb.test.FloatingPointFields([ + 'NaN', 'NaN', ['NaN', 'NaN'], 'NaN', 'NaN', 'NaN', ['NaN', 'NaN'], 'NaN' + ]); + assertNan(message.getOptionalFloatField()); + assertNan(message.getRequiredFloatField()); + assertNan(message.getRepeatedFloatFieldList()[0]); + assertNan(message.getRepeatedFloatFieldList()[1]); + assertNan(message.getDefaultFloatField()); + assertNan(message.getOptionalDoubleField()); + assertNan(message.getRequiredDoubleField()); + assertNan(message.getRepeatedDoubleFieldList()[0]); + assertNan(message.getRepeatedDoubleFieldList()[1]); + assertNan(message.getDefaultDoubleField()); + }); + + it('testFloatingPointsAreConvertedFromStringInput', function() { + var assertInf = function(x) { + assertTrue( + 'Expected ' + x + ' (' + goog.typeOf(x) + ') to be Infinity.', + x === Infinity); + }; + var message = new proto.jspb.test.FloatingPointFields([ + Infinity, 'Infinity', ['Infinity', Infinity], 'Infinity', 'Infinity', + 'Infinity', ['Infinity', Infinity], 'Infinity' + ]); + assertInf(message.getOptionalFloatField()); + assertInf(message.getRequiredFloatField()); + assertInf(message.getRepeatedFloatFieldList()[0]); + assertInf(message.getRepeatedFloatFieldList()[1]); + assertInf(message.getDefaultFloatField()); + assertInf(message.getOptionalDoubleField()); + assertInf(message.getRequiredDoubleField()); + assertInf(message.getRepeatedDoubleFieldList()[0]); + assertInf(message.getRepeatedDoubleFieldList()[1]); + assertInf(message.getDefaultDoubleField()); + }); + + it('testBooleansAreConvertedFromNumberInput', function() { + var assertBooleanFieldTrue = function(x) { + assertTrue( + 'Expected ' + x + ' (' + goog.typeOf(x) + ') to be True.', + x === true); + }; + var message = new proto.jspb.test.BooleanFields([1, 1, [true, 1]]); + assertBooleanFieldTrue(message.getOptionalBooleanField()); + assertBooleanFieldTrue(message.getRequiredBooleanField()); + assertBooleanFieldTrue(message.getRepeatedBooleanFieldList()[0]); + assertBooleanFieldTrue(message.getRepeatedBooleanFieldList()[1]); + assertBooleanFieldTrue(message.getDefaultBooleanField()); + + var assertBooleanFieldFalse = function(x) { + assertTrue( + 'Expected ' + x + ' (' + goog.typeOf(x) + ') to be False.', + x === false); + }; + message = new proto.jspb.test.BooleanFields([0, 0, [0, 0]]); + assertBooleanFieldFalse(message.getOptionalBooleanField()); + assertBooleanFieldFalse(message.getRequiredBooleanField()); + assertBooleanFieldFalse(message.getRepeatedBooleanFieldList()[0]); + assertBooleanFieldFalse(message.getRepeatedBooleanFieldList()[1]); + }); + + it('testExtensionReverseOrder', function() { + var message2 = + new proto.jspb.exttest.reverse.TestExtensionReverseOrderMessage2; + + message2.setExtension( + proto.jspb.exttest.reverse.TestExtensionReverseOrderMessage1.a, 233); + message2.setExtension( + proto.jspb.exttest.reverse.TestExtensionReverseOrderMessage1 + .TestExtensionReverseOrderNestedMessage1.b, + 2333); + message2.setExtension(proto.jspb.exttest.reverse.c, 23333); + + assertEquals( + 233, + message2.getExtension( + proto.jspb.exttest.reverse.TestExtensionReverseOrderMessage1.a)); + assertEquals( + 2333, + message2.getExtension( + proto.jspb.exttest.reverse.TestExtensionReverseOrderMessage1 + .TestExtensionReverseOrderNestedMessage1.b)); + assertEquals(23333, message2.getExtension(proto.jspb.exttest.reverse.c)); + }); + + it('testCircularDepsBaseOnMessageField', function() { + var nestMessage1 = new proto.jspb.circulartest.MessageField1; + var nestMessage2 = new proto.jspb.circulartest.MessageField2; + var message1 = new proto.jspb.circulartest.MessageField1; + var message2 = new proto.jspb.circulartest.MessageField2; + + nestMessage1.setA(1); + nestMessage2.setA(2); + message1.setB(nestMessage2); + message2.setB(nestMessage1); + + + assertEquals(2, message1.getB().getA()); + assertEquals(1, message2.getB().getA()); + }); + + + it('testCircularDepsBaseOnRepeatedMessageField', function() { + var nestMessage1 = new proto.jspb.circulartest.RepeatedMessageField1; + var nestMessage2 = new proto.jspb.circulartest.RepeatedMessageField2; + var message1 = new proto.jspb.circulartest.RepeatedMessageField1; + var message2 = new proto.jspb.circulartest.RepeatedMessageField2; + + nestMessage1.setA(1); + nestMessage2.setA(2); + message1.setB(nestMessage2); + message2.addB(nestMessage1); + + + assertEquals(2, message1.getB().getA()); + assertEquals(1, message2.getBList()[0].getA()); + }); + + it('testCircularDepsBaseOnMapField', function() { + var nestMessage1 = new proto.jspb.circulartest.MapField1; + var nestMessage2 = new proto.jspb.circulartest.MapField2; + var message1 = new proto.jspb.circulartest.MapField1; + var message2 = new proto.jspb.circulartest.MapField2; + + nestMessage1.setA(1); + nestMessage2.setA(2); + message1.setB(nestMessage2); + message2.getBMap().set(1, nestMessage1); + + + assertEquals(2, message1.getB().getA()); + assertEquals(1, message2.getBMap().get(1).getA()); + }); + + it('testCircularDepsBaseOnNestedMessage', function() { + var nestMessage1 = + new proto.jspb.circulartest.NestedMessage1.NestedNestedMessage; + var nestMessage2 = new proto.jspb.circulartest.NestedMessage2; + var message1 = new proto.jspb.circulartest.NestedMessage1; + var message2 = new proto.jspb.circulartest.NestedMessage2; + + nestMessage1.setA(1); + nestMessage2.setA(2); + message1.setB(nestMessage2); + message2.setB(nestMessage1); + + + assertEquals(2, message1.getB().getA()); + assertEquals(1, message2.getB().getA()); + }); + + it('testCircularDepsBaseOnNestedEnum', function() { + var nestMessage2 = new proto.jspb.circulartest.NestedEnum2; + var message1 = new proto.jspb.circulartest.NestedEnum1; + var message2 = new proto.jspb.circulartest.NestedEnum2; + + nestMessage2.setA(2); + message1.setB(nestMessage2); + message2.setB(proto.jspb.circulartest.NestedEnum1.NestedNestedEnum.VALUE_1); + + + assertEquals(2, message1.getB().getA()); + assertEquals( + proto.jspb.circulartest.NestedEnum1.NestedNestedEnum.VALUE_1, + message2.getB()); + }); + + it('testCircularDepsBaseOnExtensionContainingType', function() { + var nestMessage2 = new proto.jspb.circulartest.ExtensionContainingType2; + var message1 = new proto.jspb.circulartest.ExtensionContainingType1; + + nestMessage2.setA(2); + message1.setB(nestMessage2); + message1.setExtension( + proto.jspb.circulartest.ExtensionContainingType2.c, 1); + + + assertEquals(2, message1.getB().getA()); + assertEquals( + 1, + message1.getExtension( + proto.jspb.circulartest.ExtensionContainingType2.c)); + }); + + it('testCircularDepsBaseOnExtensionField', function() { + var nestMessage2 = new proto.jspb.circulartest.ExtensionField2; + var message1 = new proto.jspb.circulartest.ExtensionField1; + var message3 = new proto.jspb.circulartest.ExtensionField3; + + nestMessage2.setA(2); + message1.setB(nestMessage2); + message3.setExtension(proto.jspb.circulartest.ExtensionField2.c, message1); + + + assertEquals( + 2, + message3.getExtension(proto.jspb.circulartest.ExtensionField2.c) + .getB() + .getA()); + }); + + it('testSameMessageNameOuputs', function() { + var package1Message = new proto.jspb.filenametest.package1.TestMessage; + var package2Message = new proto.jspb.filenametest.package2.TestMessage; + + package1Message.setExtension(proto.jspb.filenametest.package1.a, 10); + package1Message.setExtension(proto.jspb.filenametest.package1.b, 11); + package2Message.setA(12); + + assertEquals( + 10, package1Message.getExtension(proto.jspb.filenametest.package1.a)); + assertEquals( + 11, package1Message.getExtension(proto.jspb.filenametest.package1.b)); + assertEquals(12, package2Message.getA()); + }); + + + it('testMessageWithLargeFieldNumbers', function() { + var message = new proto.jspb.test.MessageWithLargeFieldNumbers; + + message.setAString('string'); + assertEquals('string', message.getAString()); + + message.setAString(''); + assertEquals('', message.getAString()); + + message.setAString('new string'); + assertEquals('new string', message.getAString()); + + message.setABoolean(true); + assertEquals(true, message.getABoolean()); + + message.setABoolean(false); + assertEquals(false, message.getABoolean()); + + message.setABoolean(true); + assertEquals(true, message.getABoolean()); + + message.setAInt(42); + assertEquals(42, message.getAInt()); + + message.setAInt(0); + assertEquals(0, message.getAInt()); + + message.setAInt(42); + assertEquals(42, message.getAInt()); + }); +}); diff --git a/tools/env-vars-generator/protobuf/js/package.json b/tools/env-vars-generator/protobuf/js/package.json new file mode 100644 index 0000000..f7e8a3f --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/package.json @@ -0,0 +1,27 @@ +{ + "name": "google-protobuf", + "version": "3.19.4", + "description": "Protocol Buffers for JavaScript", + "main": "google-protobuf.js", + "files": [ + "google" + ], + "dependencies": {}, + "devDependencies": { + "glob": "~7.1.4", + "google-closure-compiler": "~20190819.0.0", + "google-closure-deps": "^20210406.0.0", + "google-closure-library": "~20190819.0.0", + "gulp": "~4.0.2", + "jasmine": "~3.4.0" + }, + "scripts": { + "test": "node ./node_modules/gulp/bin/gulp.js test" + }, + "repository": { + "type": "git", + "url": "https://github.com/protocolbuffers/protobuf/tree/master/js" + }, + "author": "Google Protocol Buffers Team", + "license": "BSD-3-Clause" +} diff --git a/tools/env-vars-generator/protobuf/js/proto3_test.js b/tools/env-vars-generator/protobuf/js/proto3_test.js new file mode 100644 index 0000000..8de1575 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/proto3_test.js @@ -0,0 +1,478 @@ +// 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. + +goog.require('goog.crypt.base64'); +goog.require('goog.testing.asserts'); +// CommonJS-LoadFromFile: testbinary_pb proto.jspb.test +goog.require('proto.jspb.test.ForeignMessage'); +// CommonJS-LoadFromFile: proto3_test_pb proto.jspb.test +goog.require('proto.jspb.test.Proto3Enum'); +goog.require('proto.jspb.test.TestProto3'); +// CommonJS-LoadFromFile: google/protobuf/any_pb proto.google.protobuf +goog.require('proto.google.protobuf.Any'); +// CommonJS-LoadFromFile: google/protobuf/timestamp_pb proto.google.protobuf +goog.require('proto.google.protobuf.Timestamp'); +// CommonJS-LoadFromFile: google/protobuf/struct_pb proto.google.protobuf +goog.require('proto.google.protobuf.Struct'); +goog.require('jspb.Message'); + +var BYTES = new Uint8Array([1, 2, 8, 9]); +var BYTES_B64 = goog.crypt.base64.encodeByteArray(BYTES); + + +/** + * Helper: compare a bytes field to an expected value + * @param {Uint8Array|string} arr + * @param {Uint8Array} expected + * @return {boolean} + */ +function bytesCompare(arr, expected) { + if (typeof arr === 'string') { + arr = goog.crypt.base64.decodeStringToUint8Array(arr); + } + if (arr.length != expected.length) { + return false; + } + for (var i = 0; i < arr.length; i++) { + if (arr[i] != expected[i]) { + return false; + } + } + return true; +} + + +describe('proto3Test', function() { + /** + * Test default values don't affect equality test. + */ + it('testEqualsProto3', function() { + var msg1 = new proto.jspb.test.TestProto3(); + var msg2 = new proto.jspb.test.TestProto3(); + msg2.setSingularString(''); + + assertTrue(jspb.Message.equals(msg1, msg2)); + }); + + + /** + * Test setting when a field has default semantics. + */ + it('testSetProto3ToValueAndBackToDefault', function() { + var msg = new proto.jspb.test.TestProto3(); + + // Setting should work normally. + msg.setSingularString('optionalString'); + assertEquals(msg.getSingularString(), 'optionalString'); + + // Clearing should work too ... + msg.setSingularString(''); + assertEquals(msg.getSingularString(), ''); + + // ... and shouldn't affect the equality with a brand new message. + assertTrue(jspb.Message.equals(msg, new proto.jspb.test.TestProto3())); + }); + + /** + * Test defaults for proto3 message fields. + */ + it('testProto3FieldDefaults', function() { + var msg = new proto.jspb.test.TestProto3(); + + assertEquals(msg.getSingularInt32(), 0); + assertEquals(msg.getSingularInt64(), 0); + assertEquals(msg.getSingularUint32(), 0); + assertEquals(msg.getSingularUint64(), 0); + assertEquals(msg.getSingularSint32(), 0); + assertEquals(msg.getSingularSint64(), 0); + assertEquals(msg.getSingularFixed32(), 0); + assertEquals(msg.getSingularFixed64(), 0); + assertEquals(msg.getSingularSfixed32(), 0); + assertEquals(msg.getSingularSfixed64(), 0); + assertEquals(msg.getSingularFloat(), 0); + assertEquals(msg.getSingularDouble(), 0); + assertEquals(msg.getSingularString(), ''); + + // TODO(b/26173701): when we change bytes fields default getter to return + // Uint8Array, we'll want to switch this assertion to match the u8 case. + assertEquals(typeof msg.getSingularBytes(), 'string'); + assertEquals(msg.getSingularBytes_asU8() instanceof Uint8Array, true); + assertEquals(typeof msg.getSingularBytes_asB64(), 'string'); + assertEquals(msg.getSingularBytes().length, 0); + assertEquals(msg.getSingularBytes_asU8().length, 0); + assertEquals(msg.getSingularBytes_asB64(), ''); + + assertEquals( + msg.getSingularForeignEnum(), proto.jspb.test.Proto3Enum.PROTO3_FOO); + assertEquals(msg.getSingularForeignMessage(), undefined); + assertEquals(msg.getSingularForeignMessage(), undefined); + + assertEquals(msg.getRepeatedInt32List().length, 0); + assertEquals(msg.getRepeatedInt64List().length, 0); + assertEquals(msg.getRepeatedUint32List().length, 0); + assertEquals(msg.getRepeatedUint64List().length, 0); + assertEquals(msg.getRepeatedSint32List().length, 0); + assertEquals(msg.getRepeatedSint64List().length, 0); + assertEquals(msg.getRepeatedFixed32List().length, 0); + assertEquals(msg.getRepeatedFixed64List().length, 0); + assertEquals(msg.getRepeatedSfixed32List().length, 0); + assertEquals(msg.getRepeatedSfixed64List().length, 0); + assertEquals(msg.getRepeatedFloatList().length, 0); + assertEquals(msg.getRepeatedDoubleList().length, 0); + assertEquals(msg.getRepeatedStringList().length, 0); + assertEquals(msg.getRepeatedBytesList().length, 0); + assertEquals(msg.getRepeatedForeignEnumList().length, 0); + assertEquals(msg.getRepeatedForeignMessageList().length, 0); + }); + + /** + * Test presence for proto3 optional fields. + */ + it('testProto3Optional', function() { + var msg = new proto.jspb.test.TestProto3(); + + assertEquals(msg.getOptionalInt32(), 0); + assertEquals(msg.getOptionalInt64(), 0); + assertEquals(msg.getOptionalUint32(), 0); + assertEquals(msg.getOptionalUint64(), 0); + assertEquals(msg.getOptionalSint32(), 0); + assertEquals(msg.getOptionalSint64(), 0); + assertEquals(msg.getOptionalFixed32(), 0); + assertEquals(msg.getOptionalFixed64(), 0); + assertEquals(msg.getOptionalSfixed32(), 0); + assertEquals(msg.getOptionalSfixed64(), 0); + assertEquals(msg.getOptionalFloat(), 0); + assertEquals(msg.getOptionalDouble(), 0); + assertEquals(msg.getOptionalString(), ''); + + // TODO(b/26173701): when we change bytes fields default getter to return + // Uint8Array, we'll want to switch this assertion to match the u8 case. + assertEquals(typeof msg.getOptionalBytes(), 'string'); + assertEquals(msg.getOptionalBytes_asU8() instanceof Uint8Array, true); + assertEquals(typeof msg.getOptionalBytes_asB64(), 'string'); + assertEquals(msg.getOptionalBytes().length, 0); + assertEquals(msg.getOptionalBytes_asU8().length, 0); + assertEquals(msg.getOptionalBytes_asB64(), ''); + + assertEquals( + msg.getOptionalForeignEnum(), proto.jspb.test.Proto3Enum.PROTO3_FOO); + assertEquals(msg.getOptionalForeignMessage(), undefined); + assertEquals(msg.getOptionalForeignMessage(), undefined); + + // Serializing an empty proto yields the empty string. + assertEquals(msg.serializeBinary().length, 0); + + // Values start as unset, but can be explicitly set even to default values + // like 0. + assertFalse(msg.hasOptionalInt32()); + msg.setOptionalInt32(0); + assertTrue(msg.hasOptionalInt32()); + + assertFalse(msg.hasOptionalInt64()); + msg.setOptionalInt64(0); + assertTrue(msg.hasOptionalInt64()); + + assertFalse(msg.hasOptionalString()); + msg.setOptionalString(''); + assertTrue(msg.hasOptionalString()); + + // Now the proto will have a non-zero size, even though its values are 0. + var serialized = msg.serializeBinary(); + assertNotEquals(serialized.length, 0); + + var msg2 = proto.jspb.test.TestProto3.deserializeBinary(serialized); + assertTrue(msg2.hasOptionalInt32()); + assertTrue(msg2.hasOptionalInt64()); + assertTrue(msg2.hasOptionalString()); + + // We can clear fields to go back to empty. + msg2.clearOptionalInt32(); + assertFalse(msg2.hasOptionalInt32()); + + msg2.clearOptionalString(); + assertFalse(msg2.hasOptionalString()); + }); + + /** + * Test that all fields can be set ,and read via a serialization roundtrip. + */ + it('testProto3FieldSetGet', function() { + var msg = new proto.jspb.test.TestProto3(); + + msg.setSingularInt32(-42); + msg.setSingularInt64(-0x7fffffff00000000); + msg.setSingularUint32(0x80000000); + msg.setSingularUint64(0xf000000000000000); + msg.setSingularSint32(-100); + msg.setSingularSint64(-0x8000000000000000); + msg.setSingularFixed32(1234); + msg.setSingularFixed64(0x1234567800000000); + msg.setSingularSfixed32(-1234); + msg.setSingularSfixed64(-0x1234567800000000); + msg.setSingularFloat(1.5); + msg.setSingularDouble(-1.5); + msg.setSingularBool(true); + msg.setSingularString('hello world'); + msg.setSingularBytes(BYTES); + var submsg = new proto.jspb.test.ForeignMessage(); + submsg.setC(16); + msg.setSingularForeignMessage(submsg); + msg.setSingularForeignEnum(proto.jspb.test.Proto3Enum.PROTO3_BAR); + + msg.setRepeatedInt32List([-42]); + msg.setRepeatedInt64List([-0x7fffffff00000000]); + msg.setRepeatedUint32List([0x80000000]); + msg.setRepeatedUint64List([0xf000000000000000]); + msg.setRepeatedSint32List([-100]); + msg.setRepeatedSint64List([-0x8000000000000000]); + msg.setRepeatedFixed32List([1234]); + msg.setRepeatedFixed64List([0x1234567800000000]); + msg.setRepeatedSfixed32List([-1234]); + msg.setRepeatedSfixed64List([-0x1234567800000000]); + msg.setRepeatedFloatList([1.5]); + msg.setRepeatedDoubleList([-1.5]); + msg.setRepeatedBoolList([true]); + msg.setRepeatedStringList(['hello world']); + msg.setRepeatedBytesList([BYTES]); + submsg = new proto.jspb.test.ForeignMessage(); + submsg.setC(1000); + msg.setRepeatedForeignMessageList([submsg]); + msg.setRepeatedForeignEnumList([proto.jspb.test.Proto3Enum.PROTO3_BAR]); + + msg.setOneofString('asdf'); + + var serialized = msg.serializeBinary(); + msg = proto.jspb.test.TestProto3.deserializeBinary(serialized); + + assertEquals(msg.getSingularInt32(), -42); + assertEquals(msg.getSingularInt64(), -0x7fffffff00000000); + assertEquals(msg.getSingularUint32(), 0x80000000); + assertEquals(msg.getSingularUint64(), 0xf000000000000000); + assertEquals(msg.getSingularSint32(), -100); + assertEquals(msg.getSingularSint64(), -0x8000000000000000); + assertEquals(msg.getSingularFixed32(), 1234); + assertEquals(msg.getSingularFixed64(), 0x1234567800000000); + assertEquals(msg.getSingularSfixed32(), -1234); + assertEquals(msg.getSingularSfixed64(), -0x1234567800000000); + assertEquals(msg.getSingularFloat(), 1.5); + assertEquals(msg.getSingularDouble(), -1.5); + assertEquals(msg.getSingularBool(), true); + assertEquals(msg.getSingularString(), 'hello world'); + assertEquals(true, bytesCompare(msg.getSingularBytes(), BYTES)); + assertEquals(msg.getSingularForeignMessage().getC(), 16); + assertEquals( + msg.getSingularForeignEnum(), proto.jspb.test.Proto3Enum.PROTO3_BAR); + + assertElementsEquals(msg.getRepeatedInt32List(), [-42]); + assertElementsEquals(msg.getRepeatedInt64List(), [-0x7fffffff00000000]); + assertElementsEquals(msg.getRepeatedUint32List(), [0x80000000]); + assertElementsEquals(msg.getRepeatedUint64List(), [0xf000000000000000]); + assertElementsEquals(msg.getRepeatedSint32List(), [-100]); + assertElementsEquals(msg.getRepeatedSint64List(), [-0x8000000000000000]); + assertElementsEquals(msg.getRepeatedFixed32List(), [1234]); + assertElementsEquals(msg.getRepeatedFixed64List(), [0x1234567800000000]); + assertElementsEquals(msg.getRepeatedSfixed32List(), [-1234]); + assertElementsEquals(msg.getRepeatedSfixed64List(), [-0x1234567800000000]); + assertElementsEquals(msg.getRepeatedFloatList(), [1.5]); + assertElementsEquals(msg.getRepeatedDoubleList(), [-1.5]); + assertElementsEquals(msg.getRepeatedBoolList(), [true]); + assertElementsEquals(msg.getRepeatedStringList(), ['hello world']); + assertEquals(msg.getRepeatedBytesList().length, 1); + assertEquals(true, bytesCompare(msg.getRepeatedBytesList()[0], BYTES)); + assertEquals(msg.getRepeatedForeignMessageList().length, 1); + assertEquals(msg.getRepeatedForeignMessageList()[0].getC(), 1000); + assertElementsEquals( + msg.getRepeatedForeignEnumList(), + [proto.jspb.test.Proto3Enum.PROTO3_BAR]); + + assertEquals(msg.getOneofString(), 'asdf'); + }); + + + /** + * Test that oneofs continue to have a notion of field presence. + */ + it('testOneofs', function() { + // Default instance. + var msg = new proto.jspb.test.TestProto3(); + assertEquals(msg.getOneofUint32(), 0); + assertEquals(msg.getOneofForeignMessage(), undefined); + assertEquals(msg.getOneofString(), ''); + assertEquals(msg.getOneofBytes(), ''); + + assertFalse(msg.hasOneofUint32()); + assertFalse(msg.hasOneofForeignMessage()); + assertFalse(msg.hasOneofString()); + assertFalse(msg.hasOneofBytes()); + + // Integer field. + msg.setOneofUint32(42); + assertEquals(msg.getOneofUint32(), 42); + assertEquals(msg.getOneofForeignMessage(), undefined); + assertEquals(msg.getOneofString(), ''); + assertEquals(msg.getOneofBytes(), ''); + + assertTrue(msg.hasOneofUint32()); + assertFalse(msg.hasOneofForeignMessage()); + assertFalse(msg.hasOneofString()); + assertFalse(msg.hasOneofBytes()); + + // Sub-message field. + var submsg = new proto.jspb.test.ForeignMessage(); + msg.setOneofForeignMessage(submsg); + assertEquals(msg.getOneofUint32(), 0); + assertEquals(msg.getOneofForeignMessage(), submsg); + assertEquals(msg.getOneofString(), ''); + assertEquals(msg.getOneofBytes(), ''); + + assertFalse(msg.hasOneofUint32()); + assertTrue(msg.hasOneofForeignMessage()); + assertFalse(msg.hasOneofString()); + assertFalse(msg.hasOneofBytes()); + + // String field. + msg.setOneofString('hello'); + assertEquals(msg.getOneofUint32(), 0); + assertEquals(msg.getOneofForeignMessage(), undefined); + assertEquals(msg.getOneofString(), 'hello'); + assertEquals(msg.getOneofBytes(), ''); + + assertFalse(msg.hasOneofUint32()); + assertFalse(msg.hasOneofForeignMessage()); + assertTrue(msg.hasOneofString()); + assertFalse(msg.hasOneofBytes()); + + // Bytes field. + msg.setOneofBytes(goog.crypt.base64.encodeString('\u00FF\u00FF')); + assertEquals(msg.getOneofUint32(), 0); + assertEquals(msg.getOneofForeignMessage(), undefined); + assertEquals(msg.getOneofString(), ''); + assertEquals( + msg.getOneofBytes_asB64(), + goog.crypt.base64.encodeString('\u00FF\u00FF')); + + assertFalse(msg.hasOneofUint32()); + assertFalse(msg.hasOneofForeignMessage()); + assertFalse(msg.hasOneofString()); + assertTrue(msg.hasOneofBytes()); + }); + + + /** + * Test that "default"-valued primitive fields are not emitted on the wire. + */ + it('testNoSerializeDefaults', function() { + var msg = new proto.jspb.test.TestProto3(); + + // Set each primitive to a non-default value, then back to its default, to + // ensure that the serialization is actually checking the value and not just + // whether it has ever been set. + msg.setSingularInt32(42); + msg.setSingularInt32(0); + msg.setSingularDouble(3.14); + msg.setSingularDouble(0.0); + msg.setSingularBool(true); + msg.setSingularBool(false); + msg.setSingularString('hello world'); + msg.setSingularString(''); + msg.setSingularBytes(goog.crypt.base64.encodeString('\u00FF\u00FF')); + msg.setSingularBytes(''); + msg.setSingularForeignMessage(new proto.jspb.test.ForeignMessage()); + msg.setSingularForeignMessage(null); + msg.setSingularForeignEnum(proto.jspb.test.Proto3Enum.PROTO3_BAR); + msg.setSingularForeignEnum(proto.jspb.test.Proto3Enum.PROTO3_FOO); + msg.setOneofUint32(32); + msg.clearOneofUint32(); + + + var serialized = msg.serializeBinary(); + assertEquals(0, serialized.length); + }); + + /** + * Test that base64 string and Uint8Array are interchangeable in bytes fields. + */ + it('testBytesFieldsInterop', function() { + var msg = new proto.jspb.test.TestProto3(); + // Set as a base64 string and check all the getters work. + msg.setSingularBytes(BYTES_B64); + assertTrue(bytesCompare(msg.getSingularBytes_asU8(), BYTES)); + assertTrue(bytesCompare(msg.getSingularBytes_asB64(), BYTES)); + assertTrue(bytesCompare(msg.getSingularBytes(), BYTES)); + + // Test binary serialize round trip doesn't break it. + msg = proto.jspb.test.TestProto3.deserializeBinary(msg.serializeBinary()); + assertTrue(bytesCompare(msg.getSingularBytes_asU8(), BYTES)); + assertTrue(bytesCompare(msg.getSingularBytes_asB64(), BYTES)); + assertTrue(bytesCompare(msg.getSingularBytes(), BYTES)); + + msg = new proto.jspb.test.TestProto3(); + // Set as a Uint8Array and check all the getters work. + msg.setSingularBytes(BYTES); + assertTrue(bytesCompare(msg.getSingularBytes_asU8(), BYTES)); + assertTrue(bytesCompare(msg.getSingularBytes_asB64(), BYTES)); + assertTrue(bytesCompare(msg.getSingularBytes(), BYTES)); + }); + + it('testTimestampWellKnownType', function() { + var msg = new proto.google.protobuf.Timestamp(); + msg.fromDate(new Date(123456789)); + assertEquals(123456, msg.getSeconds()); + assertEquals(789000000, msg.getNanos()); + var date = msg.toDate(); + assertEquals(123456789, date.getTime()); + var anotherMsg = proto.google.protobuf.Timestamp.fromDate(date); + assertEquals(msg.getSeconds(), anotherMsg.getSeconds()); + assertEquals(msg.getNanos(), anotherMsg.getNanos()); + }); + + it('testStructWellKnownType', function() { + var jsObj = { + abc: 'def', + number: 12345.678, + nullKey: null, + boolKey: true, + listKey: [1, null, true, false, 'abc'], + structKey: {foo: 'bar', somenum: 123}, + complicatedKey: [{xyz: {abc: [3, 4, null, false]}}, 'zzz'] + }; + + var struct = proto.google.protobuf.Struct.fromJavaScript(jsObj); + var jsObj2 = struct.toJavaScript(); + + assertEquals('def', jsObj2.abc); + assertEquals(12345.678, jsObj2.number); + assertEquals(null, jsObj2.nullKey); + assertEquals(true, jsObj2.boolKey); + assertEquals('abc', jsObj2.listKey[4]); + assertEquals('bar', jsObj2.structKey.foo); + assertEquals(4, jsObj2.complicatedKey[0].xyz.abc[1]); + }); +}); diff --git a/tools/env-vars-generator/protobuf/js/test10.proto b/tools/env-vars-generator/protobuf/js/test10.proto new file mode 100644 index 0000000..9fa5256 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/test10.proto @@ -0,0 +1,39 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package jspb.exttest.strict.ten; + +import "test9.proto"; + +message Simple10 { + jspb.exttest.strict.nine.Simple9 a = 1; +} diff --git a/tools/env-vars-generator/protobuf/js/test12.proto b/tools/env-vars-generator/protobuf/js/test12.proto new file mode 100644 index 0000000..4ece1d0 --- /dev/null +++ b/tools/env-vars-generator/protobuf/js/test12.proto @@ -0,0 +1,119 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto2"; + + +package jspb.circulartest; + +message MessageField1 { + optional int32 a = 1; + optional MessageField2 b = 2; +} + +message MessageField2 { + optional int32 a = 1; + optional MessageField1 b = 2; +} + + +message RepeatedMessageField1 { + optional int32 a = 1; + optional RepeatedMessageField2 b = 2; +} + +message RepeatedMessageField2 { + optional int32 a = 1; + repeated RepeatedMessageField1 b = 2; +} + +message MapField1 { + optional int32 a = 1; + optional MapField2 b = 2; +} + +message MapField2 { + optional int32 a = 1; + map b = 2; +} + +message NestedMessage1 { + optional NestedMessage2 b = 2; + message NestedNestedMessage { + optional int32 a = 1; + } +} + +message NestedMessage2 { + optional int32 a = 1; + optional NestedMessage1.NestedNestedMessage b = 2; +} + +message NestedEnum1 { + optional NestedEnum2 b = 2; + enum NestedNestedEnum { + UNDEFINED = 0; + VALUE_1 = 1; + } +} + +message NestedEnum2 { + optional int32 a = 1; + optional NestedEnum1.NestedNestedEnum b = 2; +} + +message ExtensionContainingType1 { + optional int32 a = 1; + optional ExtensionContainingType2 b = 2; + extensions 99 to 100; +} + +message ExtensionContainingType2 { + optional int32 a = 1; + extend ExtensionContainingType1 { + optional int32 c = 99; + } +} + +message ExtensionField1 { + optional int32 a = 1; + optional ExtensionField2 b = 2; +} + +message ExtensionField2 { + optional int32 a = 1; + extend ExtensionField3 { + optional ExtensionField1 c = 99; + } +} + +message ExtensionField3 { + extensions 99 to 100; +} diff --git a/tools/env-vars-generator/protobuf/kokoro/docs/python.cfg b/tools/env-vars-generator/protobuf/kokoro/docs/python.cfg new file mode 100644 index 0000000..382f431 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/docs/python.cfg @@ -0,0 +1,7 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +# Tell the trampoline which build file to use. +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/protobuf/kokoro/docs/publish-python.sh" +} diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/32-bit/Dockerfile b/tools/env-vars-generator/protobuf/kokoro/linux/32-bit/Dockerfile new file mode 100644 index 0000000..1278889 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/32-bit/Dockerfile @@ -0,0 +1,143 @@ +# This Dockerfile specifies the recipe for creating an image for the tests +# to run in. +# +# We install as many test dependencies here as we can, because these setup +# steps can be cached. They do *not* run every time we run the build. +# The Docker image is only rebuilt when the Dockerfile (ie. this file) +# changes. + +# Base Dockerfile for gRPC dev images +FROM 32bit/debian:latest + +# Apt source for php +RUN echo "deb http://ppa.launchpad.net/ondrej/php/ubuntu trusty main" | tee /etc/apt/sources.list.d/various-php.list && \ + apt-key adv --keyserver keyserver.ubuntu.com --recv-keys F4FCBB07 + +# Install dependencies. We start with the basic ones require to build protoc +# and the C++ build +RUN apt-get clean && apt-get update && apt-get install -y --force-yes \ + autoconf \ + autotools-dev \ + build-essential \ + bzip2 \ + ccache \ + curl \ + gcc \ + git \ + libc6 \ + libc6-dbg \ + libc6-dev \ + libgtest-dev \ + libtool \ + make \ + parallel \ + time \ + wget \ + unzip \ + # -- For python -- + python-setuptools \ + python-pip \ + python-dev \ + # -- For C++ benchmarks -- + cmake \ + # -- For PHP -- + php5.5 \ + php5.5-dev \ + php5.5-xml \ + php5.6 \ + php5.6-dev \ + php5.6-xml \ + php7.0 \ + php7.0-dev \ + php7.0-xml \ + phpunit \ + valgrind \ + libxml2-dev \ + && apt-get clean + +################## +# PHP dependencies. +RUN wget http://am1.php.net/get/php-5.5.38.tar.bz2/from/this/mirror +RUN mv mirror php-5.5.38.tar.bz2 +RUN tar -xvf php-5.5.38.tar.bz2 +RUN cd php-5.5.38 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-5.5-zts && \ + make && make install && make clean && cd .. +RUN cd php-5.5.38 && make clean && ./configure --enable-bcmath --prefix=/usr/local/php-5.5 && \ + make && make install && make clean && cd .. + +RUN wget http://am1.php.net/get/php-5.6.30.tar.bz2/from/this/mirror +RUN mv mirror php-5.6.30.tar.bz2 +RUN tar -xvf php-5.6.30.tar.bz2 +RUN cd php-5.6.30 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-5.6-zts && \ + make && make install && cd .. +RUN cd php-5.6.30 && make clean && ./configure --enable-bcmath --prefix=/usr/local/php-5.6 && \ + make && make install && cd .. + +RUN wget http://am1.php.net/get/php-7.0.18.tar.bz2/from/this/mirror +RUN mv mirror php-7.0.18.tar.bz2 +RUN tar -xvf php-7.0.18.tar.bz2 +RUN cd php-7.0.18 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-7.0-zts && \ + make && make install && cd .. +RUN cd php-7.0.18 && make clean && ./configure --enable-bcmath --prefix=/usr/local/php-7.0 && \ + make && make install && cd .. + +RUN wget http://am1.php.net/get/php-7.1.4.tar.bz2/from/this/mirror +RUN mv mirror php-7.1.4.tar.bz2 +RUN tar -xvf php-7.1.4.tar.bz2 +RUN cd php-7.1.4 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-7.1-zts && \ + make && make install && cd .. +RUN cd php-7.1.4 && make clean && ./configure --enable-bcmath --prefix=/usr/local/php-7.1 && \ + make && make install && cd .. + +RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" +RUN php composer-setup.php +RUN mv composer.phar /usr/bin/composer +RUN php -r "unlink('composer-setup.php');" +RUN composer config -g -- disable-tls true +RUN composer config -g -- secure-http false +RUN cd /tmp && \ + git clone https://github.com/google/protobuf.git && \ + cd protobuf/php && \ + git reset --hard 49b44bff2b6257a119f9c6a342d6151c736586b8 && \ + ln -sfn /usr/local/php-5.5/bin/php /usr/bin/php && \ + ln -sfn /usr/local/php-5.5/bin/php-config /usr/bin/php-config && \ + ln -sfn /usr/local/php-5.5/bin/phpize /usr/bin/phpize && \ + composer install && \ + mv vendor /usr/local/vendor-5.5 && \ + ln -sfn /usr/local/php-5.6/bin/php /usr/bin/php && \ + ln -sfn /usr/local/php-5.6/bin/php-config /usr/bin/php-config && \ + ln -sfn /usr/local/php-5.6/bin/phpize /usr/bin/phpize && \ + composer install && \ + mv vendor /usr/local/vendor-5.6 && \ + ln -sfn /usr/local/php-7.0/bin/php /usr/bin/php && \ + ln -sfn /usr/local/php-7.0/bin/php-config /usr/bin/php-config && \ + ln -sfn /usr/local/php-7.0/bin/phpize /usr/bin/phpize && \ + composer install && \ + mv vendor /usr/local/vendor-7.0 && \ + ln -sfn /usr/local/php-7.1/bin/php /usr/bin/php && \ + ln -sfn /usr/local/php-7.1/bin/php-config /usr/bin/php-config && \ + ln -sfn /usr/local/php-7.1/bin/phpize /usr/bin/phpize && \ + composer install && \ + mv vendor /usr/local/vendor-7.1 + +################## +# Python dependencies + +# These packages exist in apt-get, but their versions are too old, so we have +# to get updates from pip. + +RUN pip install pip --upgrade +RUN pip install virtualenv tox yattag + +################## +# Prepare ccache + +RUN ln -s /usr/bin/ccache /usr/local/bin/gcc +RUN ln -s /usr/bin/ccache /usr/local/bin/g++ +RUN ln -s /usr/bin/ccache /usr/local/bin/cc +RUN ln -s /usr/bin/ccache /usr/local/bin/c++ +RUN ln -s /usr/bin/ccache /usr/local/bin/clang +RUN ln -s /usr/bin/ccache /usr/local/bin/clang++ + +# Define the default command. +CMD ["bash"] diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/32-bit/build.sh b/tools/env-vars-generator/protobuf/kokoro/linux/32-bit/build.sh new file mode 100755 index 0000000..8c0a41e --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/32-bit/build.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# +# This is the top-level script we give to Kokoro as the entry point for +# running the "pull request 32" project: +# +# This script selects a specific Dockerfile (for building a Docker image) and +# a script to run inside that image. Then we delegate to the general +# build_and_run_docker.sh script. + +# Change to repo root +cd $(dirname $0)/../../.. + +export DOCKERHUB_ORGANIZATION=protobuftesting +export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/php_32bit +export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh +export OUTPUT_DIR=testoutput +export TEST_SET="php_all_32" +./kokoro/linux/build_and_run_docker.sh diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/aarch64/protoc_crosscompile_aarch64.sh b/tools/env-vars-generator/protobuf/kokoro/linux/aarch64/protoc_crosscompile_aarch64.sh new file mode 100755 index 0000000..77942a4 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/aarch64/protoc_crosscompile_aarch64.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# +# Builds protobuf C++ with aarch64 crosscompiler. + +set -ex + +./autogen.sh +CXXFLAGS="-fPIC -g -O2" ./configure --host=aarch64 +make -j8 diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/aarch64/test_cpp_aarch64.sh b/tools/env-vars-generator/protobuf/kokoro/linux/aarch64/test_cpp_aarch64.sh new file mode 100755 index 0000000..26f95f3 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/aarch64/test_cpp_aarch64.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# +# Crosscompiles protobuf C++ under dockcross docker image and runs the tests under an emulator. + +set -e + +# go to the repo root +cd $(dirname $0)/../../.. + +# Initialize any submodules. +git submodule update --init --recursive + +# run the C++ build and test script under dockcross/linux-arm64 image +kokoro/linux/aarch64/dockcross_helpers/run_dockcross_linux_aarch64.sh kokoro/linux/aarch64/cpp_crosscompile_and_run_tests_with_qemu_aarch64.sh diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/aarch64/test_ruby_aarch64.sh b/tools/env-vars-generator/protobuf/kokoro/linux/aarch64/test_ruby_aarch64.sh new file mode 100755 index 0000000..91ee5f2 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/aarch64/test_ruby_aarch64.sh @@ -0,0 +1,27 @@ +#!/bin/bash + +set -ex + +# go to the repo root +cd $(dirname $0)/../../.. + +if [[ -t 0 ]]; then + DOCKER_TTY_ARGS="-it" +else + # The input device on kokoro is not a TTY, so -it does not work. + DOCKER_TTY_ARGS= +fi + +# crosscompile protoc as we will later need it for the ruby build. +# we build it under the dockcross/manylinux2014-aarch64 image so that the resulting protoc binary is compatible +# with a wide range of linux distros (including any docker images we will use later to build and test ruby) +kokoro/linux/aarch64/dockcross_helpers/run_dockcross_manylinux2014_aarch64.sh kokoro/linux/aarch64/protoc_crosscompile_aarch64.sh + +# use an actual aarch64 docker image (with a real aarch64 ruby) to run build & test protobuf ruby under an emulator +# * mount the protobuf root as /work to be able to access the crosscompiled files +# * to avoid running the process inside docker as root (which can pollute the workspace with files owned by root), we force +# running under current user's UID and GID. To be able to do that, we need to provide a home directory for the user +# otherwise the UID would be homeless under the docker container and pip install wouldn't work. For simplicity, +# we just run map the user's home to a throwaway temporary directory + +docker run $DOCKER_TTY_ARGS --rm --user "$(id -u):$(id -g)" -e "HOME=/home/fake-user" -v "$(mktemp -d):/home/fake-user" -v "$(pwd)":/work -w /work arm64v8/ruby:2.7.3-buster kokoro/linux/aarch64/ruby_build_and_run_tests_with_qemu_aarch64.sh \ No newline at end of file diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/aarch64/testimage_protobuf_php_arm64v8/Dockerfile b/tools/env-vars-generator/protobuf/kokoro/linux/aarch64/testimage_protobuf_php_arm64v8/Dockerfile new file mode 100644 index 0000000..eae1bbc --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/aarch64/testimage_protobuf_php_arm64v8/Dockerfile @@ -0,0 +1,3 @@ +FROM arm64v8/debian:buster + +RUN apt-get update && apt-get install -y php7.3-cli php7.3-dev php7.3-bcmath composer phpunit curl git valgrind && apt-get clean diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/benchmark/run.sh b/tools/env-vars-generator/protobuf/kokoro/linux/benchmark/run.sh new file mode 100755 index 0000000..acd8737 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/benchmark/run.sh @@ -0,0 +1,99 @@ +#!/bin/bash +# +# Change to repo root +cd $(dirname $0)/../../.. + +set -ex + +export OUTPUT_DIR=testoutput +repo_root="$(pwd)" + +# TODO(jtattermusch): Add back support for benchmarking with tcmalloc for C++ and python. +# This feature was removed since it used to use tcmalloc from https://github.com/gperftools/gperftools.git +# which is very outdated. See https://github.com/protocolbuffers/protobuf/issues/8725. + +# download datasets for benchmark +pushd benchmarks +datasets=$(for file in $(find . -type f -name "dataset.*.pb" -not -path "./tmp/*"); do echo "$(pwd)/$file"; done | xargs) +echo $datasets +popd + +# build Python protobuf +./autogen.sh +./configure CXXFLAGS="-fPIC -O2" +make -j8 +pushd python +virtualenv -p python3 env +source env/bin/activate +python3 setup.py build --cpp_implementation +pip3 install --install-option="--cpp_implementation" . +popd + +# build and run Python benchmark +# We do this before building protobuf C++ since C++ build +# will rewrite some libraries used by protobuf python. +pushd benchmarks +make python-pure-python-benchmark +make python-cpp-reflection-benchmark +make -j8 python-cpp-generated-code-benchmark +echo "[" > tmp/python_result.json +echo "benchmarking pure python..." +./python-pure-python-benchmark --json --behavior_prefix="pure-python-benchmark" $datasets >> tmp/python_result.json +echo "," >> "tmp/python_result.json" +echo "benchmarking python cpp reflection..." +env LD_LIBRARY_PATH="${repo_root}/src/.libs" ./python-cpp-reflection-benchmark --json --behavior_prefix="cpp-reflection-benchmark" $datasets >> tmp/python_result.json +echo "," >> "tmp/python_result.json" +echo "benchmarking python cpp generated code..." +env LD_LIBRARY_PATH="${repo_root}/src/.libs" ./python-cpp-generated-code-benchmark --json --behavior_prefix="cpp-generated-code-benchmark" $datasets >> tmp/python_result.json +echo "]" >> "tmp/python_result.json" +popd + +# build CPP protobuf +./configure +make clean && make -j8 + +pushd java +mvn package -B -Dmaven.test.skip=true +popd + +pushd benchmarks + +# build and run C++ benchmark +# "make clean" deletes the contents of the tmp/ directory, so we move it elsewhere and then restore it once build is done. +# TODO(jtattermusch): find a less clumsy way of protecting python_result.json contents +mv tmp/python_result.json . && make clean && make -j8 cpp-benchmark && mv python_result.json tmp +echo "benchmarking cpp..." +env ./cpp-benchmark --benchmark_min_time=5.0 --benchmark_out_format=json --benchmark_out="tmp/cpp_result.json" $datasets + +# TODO(jtattermusch): add benchmarks for https://github.com/protocolbuffers/protobuf-go. +# The original benchmarks for https://github.com/golang/protobuf were removed +# because: +# * they were broken and haven't been producing results for a long time +# * the https://github.com/golang/protobuf implementation has been superseded by +# https://github.com/protocolbuffers/protobuf-go + +# build and run java benchmark (java 11 is required) +make java-benchmark +echo "benchmarking java..." +./java-benchmark -Cresults.file.options.file="tmp/java_result.json" $datasets + +# TODO(jtattermusch): re-enable JS benchmarks once https://github.com/protocolbuffers/protobuf/issues/8747 is fixed. +# build and run js benchmark +# make js-benchmark +# echo "benchmarking js..." +# ./js-benchmark $datasets --json_output=$(pwd)/tmp/node_result.json + +# TODO(jtattermusch): add php-c-benchmark. Currently its build is broken. + +# persist raw the results in the build job log (for better debuggability) +cat tmp/cpp_result.json +cat tmp/java_result.json +cat tmp/python_result.json + +# print the postprocessed results to the build job log +# TODO(jtattermusch): re-enable uploading results to bigquery (it is currently broken) +make python_add_init +env LD_LIBRARY_PATH="${repo_root}/src/.libs" python3 -m util.result_parser \ + -cpp="../tmp/cpp_result.json" -java="../tmp/java_result.json" -python="../tmp/python_result.json" +popd + diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/cpp_distcheck/continuous.cfg b/tools/env-vars-generator/protobuf/kokoro/linux/cpp_distcheck/continuous.cfg new file mode 100644 index 0000000..4289f6a --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/cpp_distcheck/continuous.cfg @@ -0,0 +1,5 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/cpp_distcheck/build.sh" +timeout_mins: 1440 diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/cpp_tcmalloc/continuous.cfg b/tools/env-vars-generator/protobuf/kokoro/linux/cpp_tcmalloc/continuous.cfg new file mode 100644 index 0000000..46312a9 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/cpp_tcmalloc/continuous.cfg @@ -0,0 +1,5 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/cpp_tcmalloc/build.sh" +timeout_mins: 1440 diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/cpp_tcmalloc/presubmit.cfg b/tools/env-vars-generator/protobuf/kokoro/linux/cpp_tcmalloc/presubmit.cfg new file mode 100644 index 0000000..46312a9 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/cpp_tcmalloc/presubmit.cfg @@ -0,0 +1,5 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/cpp_tcmalloc/build.sh" +timeout_mins: 1440 diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/csharp/continuous.cfg b/tools/env-vars-generator/protobuf/kokoro/linux/csharp/continuous.cfg new file mode 100644 index 0000000..3d17767 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/csharp/continuous.cfg @@ -0,0 +1,5 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/csharp/build.sh" +timeout_mins: 1440 diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/dockerfile/test/python38/Dockerfile b/tools/env-vars-generator/protobuf/kokoro/linux/dockerfile/test/python38/Dockerfile new file mode 100644 index 0000000..56efc9d --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/dockerfile/test/python38/Dockerfile @@ -0,0 +1,31 @@ +FROM python:3.8-buster + +# Install dependencies. We start with the basic ones require to build protoc +# and the C++ build +RUN apt-get update && apt-get install -y \ + autoconf \ + autotools-dev \ + build-essential \ + bzip2 \ + ccache \ + curl \ + gcc \ + git \ + libc6 \ + libc6-dbg \ + libc6-dev \ + libgtest-dev \ + libtool \ + make \ + parallel \ + time \ + wget \ + && apt-get clean \ + && rm -rf /var/lib/apt/lists/* + +# Install Python libraries. +RUN python -m pip install --no-cache-dir --upgrade \ + pip \ + setuptools \ + tox \ + wheel diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/dockerfile/test/python39/Dockerfile b/tools/env-vars-generator/protobuf/kokoro/linux/dockerfile/test/python39/Dockerfile new file mode 100644 index 0000000..ee7554d --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/dockerfile/test/python39/Dockerfile @@ -0,0 +1,31 @@ +FROM python:3.9-buster + +# Install dependencies. We start with the basic ones require to build protoc +# and the C++ build +RUN apt-get update && apt-get install -y \ + autoconf \ + autotools-dev \ + build-essential \ + bzip2 \ + ccache \ + curl \ + gcc \ + git \ + libc6 \ + libc6-dbg \ + libc6-dev \ + libgtest-dev \ + libtool \ + make \ + parallel \ + time \ + wget \ + && apt-get clean \ + && rm -rf /var/lib/apt/lists/* + +# Install Python libraries. +RUN python -m pip install --no-cache-dir --upgrade \ + pip \ + setuptools \ + tox \ + wheel diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/java_linkage_monitor/continuous.cfg b/tools/env-vars-generator/protobuf/kokoro/linux/java_linkage_monitor/continuous.cfg new file mode 100644 index 0000000..d0486cc --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/java_linkage_monitor/continuous.cfg @@ -0,0 +1,11 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/java_linkage_monitor/build.sh" +timeout_mins: 120 + +action { + define_artifacts { + regex: "**/sponge_log.xml" + } +} diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/jruby92/continuous.cfg b/tools/env-vars-generator/protobuf/kokoro/linux/jruby92/continuous.cfg new file mode 100644 index 0000000..3339584 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/jruby92/continuous.cfg @@ -0,0 +1,11 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/jruby92/build.sh" +timeout_mins: 120 + +action { + define_artifacts { + regex: "**/sponge_log.xml" + } +} diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/python27/continuous.cfg b/tools/env-vars-generator/protobuf/kokoro/linux/python27/continuous.cfg new file mode 100644 index 0000000..dd98469 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/python27/continuous.cfg @@ -0,0 +1,11 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/python27/build.sh" +timeout_mins: 120 + +action { + define_artifacts { + regex: "**/sponge_log.xml" + } +} diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/python27_cpp/build.sh b/tools/env-vars-generator/protobuf/kokoro/linux/python27_cpp/build.sh new file mode 100755 index 0000000..1a972ee --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/python27_cpp/build.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# +# This is the top-level script we give to Kokoro as the entry point for +# running the "pull request" project: +# +# This script selects a specific Dockerfile (for building a Docker image) and +# a script to run inside that image. Then we delegate to the general +# build_and_run_docker.sh script. + +# Change to repo root +cd $(dirname $0)/../../.. + +export DOCKERHUB_ORGANIZATION=protobuftesting +export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python27 +export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh +export OUTPUT_DIR=testoutput +export TEST_SET="python27_cpp" +./kokoro/linux/build_and_run_docker.sh diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/python27_cpp/presubmit.cfg b/tools/env-vars-generator/protobuf/kokoro/linux/python27_cpp/presubmit.cfg new file mode 100644 index 0000000..ace22d0 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/python27_cpp/presubmit.cfg @@ -0,0 +1,11 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/python27_cpp/build.sh" +timeout_mins: 120 + +action { + define_artifacts { + regex: "**/sponge_log.xml" + } +} diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/python35/build.sh b/tools/env-vars-generator/protobuf/kokoro/linux/python35/build.sh new file mode 100755 index 0000000..66ea03f --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/python35/build.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# +# This is the top-level script we give to Kokoro as the entry point for +# running the "pull request" project: +# +# This script selects a specific Dockerfile (for building a Docker image) and +# a script to run inside that image. Then we delegate to the general +# build_and_run_docker.sh script. + +# Change to repo root +cd $(dirname $0)/../../.. + +export DOCKERHUB_ORGANIZATION=protobuftesting +export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python35 +export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh +export OUTPUT_DIR=testoutput +export TEST_SET="python35" +./kokoro/linux/build_and_run_docker.sh diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/python35/presubmit.cfg b/tools/env-vars-generator/protobuf/kokoro/linux/python35/presubmit.cfg new file mode 100644 index 0000000..2b3e12c --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/python35/presubmit.cfg @@ -0,0 +1,11 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/python35/build.sh" +timeout_mins: 120 + +action { + define_artifacts { + regex: "**/sponge_log.xml" + } +} diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/python35_cpp/build.sh b/tools/env-vars-generator/protobuf/kokoro/linux/python35_cpp/build.sh new file mode 100755 index 0000000..4d0dbd4 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/python35_cpp/build.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# +# This is the top-level script we give to Kokoro as the entry point for +# running the "pull request" project: +# +# This script selects a specific Dockerfile (for building a Docker image) and +# a script to run inside that image. Then we delegate to the general +# build_and_run_docker.sh script. + +# Change to repo root +cd $(dirname $0)/../../.. + +export DOCKERHUB_ORGANIZATION=protobuftesting +export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python35 +export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh +export OUTPUT_DIR=testoutput +export TEST_SET="python35_cpp" +./kokoro/linux/build_and_run_docker.sh diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/python38/build.sh b/tools/env-vars-generator/protobuf/kokoro/linux/python38/build.sh new file mode 100755 index 0000000..299c7ba --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/python38/build.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# +# This is the top-level script we give to Kokoro as the entry point for +# running the "pull request" project: +# +# This script selects a specific Dockerfile (for building a Docker image) and +# a script to run inside that image. Then we delegate to the general +# build_and_run_docker.sh script. + +# Change to repo root +cd $(dirname $0)/../../.. + +export DOCKERHUB_ORGANIZATION=protobuftesting +export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python38 +export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh +export OUTPUT_DIR=testoutput +export TEST_SET="python38" +./kokoro/linux/build_and_run_docker.sh diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/python38_cpp/build.sh b/tools/env-vars-generator/protobuf/kokoro/linux/python38_cpp/build.sh new file mode 100755 index 0000000..b43859b --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/python38_cpp/build.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# +# This is the top-level script we give to Kokoro as the entry point for +# running the "pull request" project: +# +# This script selects a specific Dockerfile (for building a Docker image) and +# a script to run inside that image. Then we delegate to the general +# build_and_run_docker.sh script. + +# Change to repo root +cd $(dirname $0)/../../.. + +export DOCKERHUB_ORGANIZATION=protobuftesting +export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python38 +export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh +export OUTPUT_DIR=testoutput +export TEST_SET="python38_cpp" +./kokoro/linux/build_and_run_docker.sh diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/python39_cpp/presubmit.cfg b/tools/env-vars-generator/protobuf/kokoro/linux/python39_cpp/presubmit.cfg new file mode 100644 index 0000000..dd84fbe --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/python39_cpp/presubmit.cfg @@ -0,0 +1,11 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/python39_cpp/build.sh" +timeout_mins: 120 + +action { + define_artifacts { + regex: "**/sponge_log.xml" + } +} diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/python_cpp/continuous.cfg b/tools/env-vars-generator/protobuf/kokoro/linux/python_cpp/continuous.cfg new file mode 100644 index 0000000..b1b0e55 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/python_cpp/continuous.cfg @@ -0,0 +1,11 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/python_cpp/build.sh" +timeout_mins: 120 + +action { + define_artifacts { + regex: "**/sponge_log.xml" + } +} diff --git a/tools/env-vars-generator/protobuf/kokoro/linux/ruby26/build.sh b/tools/env-vars-generator/protobuf/kokoro/linux/ruby26/build.sh new file mode 100755 index 0000000..72d2d45 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/linux/ruby26/build.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# +# This is the top-level script we give to Kokoro as the entry point for +# running the "pull request" project: +# +# This script selects a specific Dockerfile (for building a Docker image) and +# a script to run inside that image. Then we delegate to the general +# build_and_run_docker.sh script. + +# Change to repo root +cd $(dirname $0)/../../.. + +export DOCKERHUB_ORGANIZATION=protobuftesting +export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/ruby +export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh +export OUTPUT_DIR=testoutput +export TEST_SET="ruby26" +./kokoro/linux/build_and_run_docker.sh diff --git a/tools/env-vars-generator/protobuf/kokoro/macos/objectivec_cocoapods_integration/build.sh b/tools/env-vars-generator/protobuf/kokoro/macos/objectivec_cocoapods_integration/build.sh new file mode 100755 index 0000000..f96d289 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/macos/objectivec_cocoapods_integration/build.sh @@ -0,0 +1,11 @@ +#!/bin/bash +# +# Build file to set up and run tests + +# Change to repo root +cd $(dirname $0)/../../.. + +# Prepare worker environment to run tests +source kokoro/macos/prepare_build_macos_rc + +./tests.sh objectivec_cocoapods_integration diff --git a/tools/env-vars-generator/protobuf/kokoro/macos/objectivec_ios_debug/continuous.cfg b/tools/env-vars-generator/protobuf/kokoro/macos/objectivec_ios_debug/continuous.cfg new file mode 100644 index 0000000..473d545 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/macos/objectivec_ios_debug/continuous.cfg @@ -0,0 +1,5 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/macos/objectivec_ios_debug/build.sh" +timeout_mins: 1440 diff --git a/tools/env-vars-generator/protobuf/kokoro/macos/php7.0_mac/build.sh b/tools/env-vars-generator/protobuf/kokoro/macos/php7.0_mac/build.sh new file mode 100755 index 0000000..e5a37e3 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/macos/php7.0_mac/build.sh @@ -0,0 +1,11 @@ +#!/bin/bash +# +# Build file to set up and run tests + +# Change to repo root +cd $(dirname $0)/../../.. + +# Prepare worker environment to run tests +source kokoro/macos/prepare_build_macos_rc + +./tests.sh php7.0_mac diff --git a/tools/env-vars-generator/protobuf/kokoro/macos/php7.0_mac/presubmit.cfg b/tools/env-vars-generator/protobuf/kokoro/macos/php7.0_mac/presubmit.cfg new file mode 100644 index 0000000..c2c1811 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/macos/php7.0_mac/presubmit.cfg @@ -0,0 +1,5 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/macos/php7.0_mac/build.sh" +timeout_mins: 1440 diff --git a/tools/env-vars-generator/protobuf/kokoro/macos/php7.3_mac/continuous.cfg b/tools/env-vars-generator/protobuf/kokoro/macos/php7.3_mac/continuous.cfg new file mode 100644 index 0000000..9a71745 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/macos/php7.3_mac/continuous.cfg @@ -0,0 +1,5 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/macos/php7.3_mac/build.sh" +timeout_mins: 1440 diff --git a/tools/env-vars-generator/protobuf/kokoro/macos/php7.3_mac/presubmit.cfg b/tools/env-vars-generator/protobuf/kokoro/macos/php7.3_mac/presubmit.cfg new file mode 100644 index 0000000..9a71745 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/macos/php7.3_mac/presubmit.cfg @@ -0,0 +1,5 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/macos/php7.3_mac/build.sh" +timeout_mins: 1440 diff --git a/tools/env-vars-generator/protobuf/kokoro/macos/prepare_build_macos_rc b/tools/env-vars-generator/protobuf/kokoro/macos/prepare_build_macos_rc new file mode 100755 index 0000000..c0017b6 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/macos/prepare_build_macos_rc @@ -0,0 +1,40 @@ +#!/bin/bash +# +# This script sets up a Kokoro MacOS worker for running Protobuf tests + +set -eux + +## +# Select Xcode version + +# Remember to update the Xcode version when Xcode_11.3.app is not available. +# If xcode is not available, it will probably encounter the failure for +# "autom4te: need GNU m4 1.4 or later: /usr/bin/m4" +# go/kokoro/userdocs/macos/selecting_xcode.md for more information. +export DEVELOPER_DIR=/Applications/Xcode_11.3.app/Contents/Developer + +## +# Select C/C++ compilers + +export CC=gcc +export CXX=g++ + +## +# Install Tox + +if [[ "${KOKORO_INSTALL_TOX:-}" == "yes" ]] ; then + sudo python3 -m pip install --upgrade pip tox +fi + +## +# Install RVM + +if [[ "${KOKORO_INSTALL_RVM:-}" == "yes" ]] ; then + curl -sSL https://rvm.io/mpapis.asc | gpg --import - + curl -sSL https://rvm.io/pkuczynski.asc | gpg --import - + + # Old OpenSSL versions cannot handle the SSL certificate used by + # https://get.rvm.io, so as a workaround we download RVM directly from + # GitHub. See this issue for details: https://github.com/rvm/rvm/issues/5133 + curl -sSL https://raw.githubusercontent.com/rvm/rvm/master/binscripts/rvm-installer | bash -s stable --ruby +fi diff --git a/tools/env-vars-generator/protobuf/kokoro/macos/python/build.sh b/tools/env-vars-generator/protobuf/kokoro/macos/python/build.sh new file mode 100755 index 0000000..388e24b --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/macos/python/build.sh @@ -0,0 +1,12 @@ +#!/bin/bash +# +# Build file to set up and run tests + +# Change to repo root +cd $(dirname $0)/../../.. + +# Prepare worker environment to run tests +KOKORO_INSTALL_TOX=yes +source kokoro/macos/prepare_build_macos_rc + +./tests.sh python diff --git a/tools/env-vars-generator/protobuf/kokoro/macos/python/presubmit.cfg b/tools/env-vars-generator/protobuf/kokoro/macos/python/presubmit.cfg new file mode 100644 index 0000000..0fc8b50 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/macos/python/presubmit.cfg @@ -0,0 +1,5 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/macos/python/build.sh" +timeout_mins: 1440 diff --git a/tools/env-vars-generator/protobuf/kokoro/macos/ruby26/continuous.cfg b/tools/env-vars-generator/protobuf/kokoro/macos/ruby26/continuous.cfg new file mode 100644 index 0000000..688f63c --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/macos/ruby26/continuous.cfg @@ -0,0 +1,5 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/macos/ruby26/build.sh" +timeout_mins: 1440 diff --git a/tools/env-vars-generator/protobuf/kokoro/macos/ruby27/build.sh b/tools/env-vars-generator/protobuf/kokoro/macos/ruby27/build.sh new file mode 100755 index 0000000..baebdb7 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/macos/ruby27/build.sh @@ -0,0 +1,12 @@ +#!/bin/bash +# +# Build file to set up and run tests + +# Change to repo root +cd $(dirname $0)/../../.. + +# Prepare worker environment to run tests +KOKORO_INSTALL_RVM=yes +source kokoro/macos/prepare_build_macos_rc + +./tests.sh ruby27 diff --git a/tools/env-vars-generator/protobuf/kokoro/macos/ruby30/continuous.cfg b/tools/env-vars-generator/protobuf/kokoro/macos/ruby30/continuous.cfg new file mode 100644 index 0000000..d505117 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/macos/ruby30/continuous.cfg @@ -0,0 +1,5 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/macos/ruby30/build.sh" +timeout_mins: 1440 diff --git a/tools/env-vars-generator/protobuf/kokoro/release/csharp/windows/build_nuget.bat b/tools/env-vars-generator/protobuf/kokoro/release/csharp/windows/build_nuget.bat new file mode 100644 index 0000000..590c391 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/release/csharp/windows/build_nuget.bat @@ -0,0 +1,17 @@ +@rem enter repo root +cd /d %~dp0\..\..\..\.. + +cd csharp + +@rem Install dotnet SDK +powershell -File install_dotnet_sdk.ps1 +set PATH=%LOCALAPPDATA%\Microsoft\dotnet;%PATH% + +@rem Disable some unwanted dotnet options +set DOTNET_SKIP_FIRST_TIME_EXPERIENCE=true +set DOTNET_CLI_TELEMETRY_OPTOUT=true + +@rem Work around https://github.com/dotnet/core/issues/5881 +dotnet nuget locals all --clear + +call build_packages.bat diff --git a/tools/env-vars-generator/protobuf/kokoro/release/python/linux/continuous.cfg b/tools/env-vars-generator/protobuf/kokoro/release/python/linux/continuous.cfg new file mode 100644 index 0000000..c0b9a01 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/release/python/linux/continuous.cfg @@ -0,0 +1,8 @@ +# Config file for running tests in Kokoro +build_file: "protobuf/kokoro/release/python/linux/build_artifacts.sh" + +action { + define_artifacts { + regex: "github/protobuf/artifacts/**" + } +} diff --git a/tools/env-vars-generator/protobuf/kokoro/release/python/macos/config.sh b/tools/env-vars-generator/protobuf/kokoro/release/python/macos/config.sh new file mode 100644 index 0000000..1b0a302 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/release/python/macos/config.sh @@ -0,0 +1,67 @@ +# Define custom utilities +# Test for OSX with [ -n "$IS_OSX" ] + +function remove_travis_ve_pip { + # Removing the system virtualenv or pip can be very problematic for + # macOS on Kokoro, so just leave them be. + :; +} + +function install_pip { + check_python + PIP_CMD="sudo $PYTHON_EXE -m pip${pip_args:+ $pip_args}" + $PIP_CMD install --upgrade pip +} + +function install_virtualenv { + check_python + check_pip + $PIP_CMD install --upgrade virtualenv + VIRTUALENV_CMD="$PYTHON_EXE -m virtualenv" +} + +function pre_build { + # Any stuff that you need to do before you start building the wheels + # Runs in the root directory of this repository. + pushd protobuf + + # Build protoc + ./autogen.sh + ./configure + + CXXFLAGS="-std=c++14 -fPIC -g -O2" ./configure + make -j8 + + # Generate python dependencies. + pushd python + python setup.py build_py + popd + + popd +} + +function bdist_wheel_cmd { + # Builds wheel with bdist_wheel, puts into wheelhouse + # + # It may sometimes be useful to use bdist_wheel for the wheel building + # process. For example, versioneer has problems with versions which are + # fixed with bdist_wheel: + # https://github.com/warner/python-versioneer/issues/121 + local abs_wheelhouse=$1 + + # Modify build version + pwd + ls + python setup.py bdist_wheel --cpp_implementation --compile_static_extension + cp dist/*.whl $abs_wheelhouse +} + +function build_wheel { + build_wheel_cmd "bdist_wheel_cmd" $@ +} + +function run_tests { + # Runs tests on installed distribution from an empty directory + python --version + python -c "from google.protobuf.pyext import _message;" +} diff --git a/tools/env-vars-generator/protobuf/kokoro/release/python/windows/continuous.cfg b/tools/env-vars-generator/protobuf/kokoro/release/python/windows/continuous.cfg new file mode 100644 index 0000000..5261606 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/release/python/windows/continuous.cfg @@ -0,0 +1,8 @@ +# Configuration for Windows protoc release builds +build_file: "protobuf/kokoro/release/python/windows/build_artifacts.bat" + +action { + define_artifacts { + regex: "github/protobuf/artifacts/**" + } +} diff --git a/tools/env-vars-generator/protobuf/kokoro/release/ruby/linux/ruby/ruby_build_environment.sh b/tools/env-vars-generator/protobuf/kokoro/release/ruby/linux/ruby/ruby_build_environment.sh new file mode 100755 index 0000000..87c0f75 --- /dev/null +++ b/tools/env-vars-generator/protobuf/kokoro/release/ruby/linux/ruby/ruby_build_environment.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +set +ex +[[ -s /etc/profile.d/rvm.sh ]] && . /etc/profile.d/rvm.sh +set -e # rvm commands are very verbose +rvm --default use ruby-2.4.1 +# The version needs to be updated if the version specified in Gemfile.lock is changed +gem install bundler -v '1.17.3' +set -ex diff --git a/tools/env-vars-generator/protobuf/m4/acx_check_suncc.m4 b/tools/env-vars-generator/protobuf/m4/acx_check_suncc.m4 new file mode 100644 index 0000000..0a9a577 --- /dev/null +++ b/tools/env-vars-generator/protobuf/m4/acx_check_suncc.m4 @@ -0,0 +1,73 @@ +dnl Check for the presence of the Sun Studio compiler. +dnl If Sun Studio compiler is found, set appropriate flags. +dnl Additionally, Sun Studio doesn't default to 64-bit by itself, +dnl nor does it automatically look in standard Solaris places for +dnl 64-bit libs, so we must add those options and paths to the search +dnl paths. + +dnl TODO(kenton): This is pretty hacky. It sets CXXFLAGS, which the autoconf +dnl docs say should never be overridden except by the user. It also isn't +dnl cross-compile safe. We should fix these problems, but since I don't have +dnl Sun CC at my disposal for testing, someone else will have to do it. + +AC_DEFUN([ACX_CHECK_SUNCC],[ + + AC_LANG_PUSH([C++]) + AC_CHECK_DECL([__SUNPRO_CC], [SUNCC="yes"], [SUNCC="no"]) + AC_LANG_POP() + + + AC_ARG_ENABLE([64bit-solaris], + [AS_HELP_STRING([--disable-64bit-solaris], + [Build 64 bit binary on Solaris @<:@default=on@:>@])], + [ac_enable_64bit="$enableval"], + [ac_enable_64bit="yes"]) + + AS_IF([test "$SUNCC" = "yes" -a "x${ac_cv_env_CXXFLAGS_set}" = "x"],[ + dnl Sun Studio has a crashing bug with -xO4 in some cases. Keep this + dnl at -xO3 until a proper test to detect those crashes can be done. + CXXFLAGS="-g0 -xO3 -xlibmil -xdepend -xbuiltin -mt -template=no%extdef ${CXXFLAGS}" + ]) + + case $host_os in + *solaris*) + AC_CHECK_PROGS(ISAINFO, [isainfo], [no]) + AS_IF([test "x$ISAINFO" != "xno"], + [isainfo_b=`${ISAINFO} -b`], + [isainfo_b="x"]) + + AS_IF([test "$isainfo_b" != "x"],[ + + isainfo_k=`${ISAINFO} -k` + + AS_IF([test "x$ac_enable_64bit" = "xyes"],[ + + AS_IF([test "x$libdir" = "x\${exec_prefix}/lib"],[ + dnl The user hasn't overridden the default libdir, so we'll + dnl the dir suffix to match solaris 32/64-bit policy + libdir="${libdir}/${isainfo_k}" + ]) + + dnl This should just be set in CPPFLAGS and in LDFLAGS, but libtool + dnl does the wrong thing if you don't put it into CXXFLAGS. sigh. + dnl (It also needs it in CFLAGS, or it does a different wrong thing!) + CXXFLAGS="${CXXFLAGS} -m64" + ac_cv_env_CXXFLAGS_set=set + ac_cv_env_CXXFLAGS_value='-m64' + + CFLAGS="${CFLAGS} -m64" + ac_cv_env_CFLAGS_set=set + ac_cv_env_CFLAGS_value='-m64' + + AS_IF([test "$target_cpu" = "sparc" -a "x$SUNCC" = "xyes" ],[ + CXXFLAGS="-xmemalign=8s ${CXXFLAGS}" + ]) + ]) + ]) + ;; + esac + + AS_IF([test "$target_cpu" = "sparc" -a "x$SUNCC" = "xyes" ],[ + CXXFLAGS="-xregs=no%appl ${CXXFLAGS}" + ]) +]) diff --git a/tools/env-vars-generator/protobuf/m4/ax_prog_cxx_for_build.m4 b/tools/env-vars-generator/protobuf/m4/ax_prog_cxx_for_build.m4 new file mode 100644 index 0000000..8cc0f73 --- /dev/null +++ b/tools/env-vars-generator/protobuf/m4/ax_prog_cxx_for_build.m4 @@ -0,0 +1,110 @@ +# =========================================================================== +# http://www.gnu.org/software/autoconf-archive/ax_prog_cxx_for_build.html +# =========================================================================== +# +# SYNOPSIS +# +# AX_PROG_CXX_FOR_BUILD +# +# DESCRIPTION +# +# This macro searches for a C++ compiler that generates native +# executables, that is a C++ compiler that surely is not a cross-compiler. +# This can be useful if you have to generate source code at compile-time +# like for example GCC does. +# +# The macro sets the CXX_FOR_BUILD and CXXCPP_FOR_BUILD macros to anything +# needed to compile or link (CXX_FOR_BUILD) and preprocess +# (CXXCPP_FOR_BUILD). The value of these variables can be overridden by +# the user by specifying a compiler with an environment variable (like you +# do for standard CXX). +# +# LICENSE +# +# Copyright (c) 2008 Paolo Bonzini +# Copyright (c) 2012 Avionic Design GmbH +# +# Based on the AX_PROG_CC_FOR_BUILD macro by Paolo Bonzini. +# +# Copying and distribution of this file, with or without modification, are +# permitted in any medium without royalty provided the copyright notice +# and this notice are preserved. This file is offered as-is, without any +# warranty. + +#serial 2 + +AU_ALIAS([AC_PROG_CXX_FOR_BUILD], [AX_PROG_CXX_FOR_BUILD]) +AC_DEFUN([AX_PROG_CXX_FOR_BUILD], [dnl +AC_REQUIRE([AX_PROG_CC_FOR_BUILD])dnl +AC_REQUIRE([AC_PROG_CXX])dnl +AC_REQUIRE([AC_PROG_CXXCPP])dnl +AC_REQUIRE([AC_CANONICAL_HOST])dnl + +dnl Use the standard macros, but make them use other variable names +dnl +pushdef([ac_cv_prog_CXXCPP], ac_cv_build_prog_CXXCPP)dnl +pushdef([ac_cv_prog_gxx], ac_cv_build_prog_gxx)dnl +pushdef([ac_cv_prog_cxx_works], ac_cv_build_prog_cxx_works)dnl +pushdef([ac_cv_prog_cxx_cross], ac_cv_build_prog_cxx_cross)dnl +pushdef([ac_cv_prog_cxx_g], ac_cv_build_prog_cxx_g)dnl +pushdef([CXX], CXX_FOR_BUILD)dnl +pushdef([CXXCPP], CXXCPP_FOR_BUILD)dnl +pushdef([CXXFLAGS], CXXFLAGS_FOR_BUILD)dnl +pushdef([CPPFLAGS], CPPFLAGS_FOR_BUILD)dnl +pushdef([CXXCPPFLAGS], CXXCPPFLAGS_FOR_BUILD)dnl +pushdef([host], build)dnl +pushdef([host_alias], build_alias)dnl +pushdef([host_cpu], build_cpu)dnl +pushdef([host_vendor], build_vendor)dnl +pushdef([host_os], build_os)dnl +pushdef([ac_cv_host], ac_cv_build)dnl +pushdef([ac_cv_host_alias], ac_cv_build_alias)dnl +pushdef([ac_cv_host_cpu], ac_cv_build_cpu)dnl +pushdef([ac_cv_host_vendor], ac_cv_build_vendor)dnl +pushdef([ac_cv_host_os], ac_cv_build_os)dnl +pushdef([ac_cxxcpp], ac_build_cxxcpp)dnl +pushdef([ac_compile], ac_build_compile)dnl +pushdef([ac_link], ac_build_link)dnl + +save_cross_compiling=$cross_compiling +save_ac_tool_prefix=$ac_tool_prefix +cross_compiling=no +ac_tool_prefix= + +AC_PROG_CXX +AC_PROG_CXXCPP + +ac_tool_prefix=$save_ac_tool_prefix +cross_compiling=$save_cross_compiling + +dnl Restore the old definitions +dnl +popdef([ac_link])dnl +popdef([ac_compile])dnl +popdef([ac_cxxcpp])dnl +popdef([ac_cv_host_os])dnl +popdef([ac_cv_host_vendor])dnl +popdef([ac_cv_host_cpu])dnl +popdef([ac_cv_host_alias])dnl +popdef([ac_cv_host])dnl +popdef([host_os])dnl +popdef([host_vendor])dnl +popdef([host_cpu])dnl +popdef([host_alias])dnl +popdef([host])dnl +popdef([CXXCPPFLAGS])dnl +popdef([CPPFLAGS])dnl +popdef([CXXFLAGS])dnl +popdef([CXXCPP])dnl +popdef([CXX])dnl +popdef([ac_cv_prog_cxx_g])dnl +popdef([ac_cv_prog_cxx_cross])dnl +popdef([ac_cv_prog_cxx_works])dnl +popdef([ac_cv_prog_gxx])dnl +popdef([ac_cv_prog_CXXCPP])dnl + +dnl Finally, set Makefile variables +dnl +AC_SUBST([CXXFLAGS_FOR_BUILD])dnl +AC_SUBST([CXXCPPFLAGS_FOR_BUILD])dnl +]) diff --git a/tools/env-vars-generator/protobuf/m4/ax_pthread.m4 b/tools/env-vars-generator/protobuf/m4/ax_pthread.m4 new file mode 100644 index 0000000..1598d07 --- /dev/null +++ b/tools/env-vars-generator/protobuf/m4/ax_pthread.m4 @@ -0,0 +1,507 @@ +# =========================================================================== +# https://www.gnu.org/software/autoconf-archive/ax_pthread.html +# =========================================================================== +# +# SYNOPSIS +# +# AX_PTHREAD([ACTION-IF-FOUND[, ACTION-IF-NOT-FOUND]]) +# +# DESCRIPTION +# +# This macro figures out how to build C programs using POSIX threads. It +# sets the PTHREAD_LIBS output variable to the threads library and linker +# flags, and the PTHREAD_CFLAGS output variable to any special C compiler +# flags that are needed. (The user can also force certain compiler +# flags/libs to be tested by setting these environment variables.) +# +# Also sets PTHREAD_CC to any special C compiler that is needed for +# multi-threaded programs (defaults to the value of CC otherwise). (This +# is necessary on AIX to use the special cc_r compiler alias.) +# +# NOTE: You are assumed to not only compile your program with these flags, +# but also to link with them as well. For example, you might link with +# $PTHREAD_CC $CFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS $LIBS +# +# If you are only building threaded programs, you may wish to use these +# variables in your default LIBS, CFLAGS, and CC: +# +# LIBS="$PTHREAD_LIBS $LIBS" +# CFLAGS="$CFLAGS $PTHREAD_CFLAGS" +# CC="$PTHREAD_CC" +# +# In addition, if the PTHREAD_CREATE_JOINABLE thread-attribute constant +# has a nonstandard name, this macro defines PTHREAD_CREATE_JOINABLE to +# that name (e.g. PTHREAD_CREATE_UNDETACHED on AIX). +# +# Also HAVE_PTHREAD_PRIO_INHERIT is defined if pthread is found and the +# PTHREAD_PRIO_INHERIT symbol is defined when compiling with +# PTHREAD_CFLAGS. +# +# ACTION-IF-FOUND is a list of shell commands to run if a threads library +# is found, and ACTION-IF-NOT-FOUND is a list of commands to run it if it +# is not found. If ACTION-IF-FOUND is not specified, the default action +# will define HAVE_PTHREAD. +# +# Please let the authors know if this macro fails on any platform, or if +# you have any other suggestions or comments. This macro was based on work +# by SGJ on autoconf scripts for FFTW (http://www.fftw.org/) (with help +# from M. Frigo), as well as ac_pthread and hb_pthread macros posted by +# Alejandro Forero Cuervo to the autoconf macro repository. We are also +# grateful for the helpful feedback of numerous users. +# +# Updated for Autoconf 2.68 by Daniel Richard G. +# +# LICENSE +# +# Copyright (c) 2008 Steven G. Johnson +# Copyright (c) 2011 Daniel Richard G. +# Copyright (c) 2019 Marc Stevens +# +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the +# Free Software Foundation, either version 3 of the License, or (at your +# option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +# Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +# +# As a special exception, the respective Autoconf Macro's copyright owner +# gives unlimited permission to copy, distribute and modify the configure +# scripts that are the output of Autoconf when processing the Macro. You +# need not follow the terms of the GNU General Public License when using +# or distributing such scripts, even though portions of the text of the +# Macro appear in them. The GNU General Public License (GPL) does govern +# all other use of the material that constitutes the Autoconf Macro. +# +# This special exception to the GPL applies to versions of the Autoconf +# Macro released by the Autoconf Archive. When you make and distribute a +# modified version of the Autoconf Macro, you may extend this special +# exception to the GPL to apply to your modified version as well. + +#serial 27 + +AU_ALIAS([ACX_PTHREAD], [AX_PTHREAD]) +AC_DEFUN([AX_PTHREAD], [ +AC_REQUIRE([AC_CANONICAL_HOST]) +AC_REQUIRE([AC_PROG_CC]) +AC_REQUIRE([AC_PROG_SED]) +AC_LANG_PUSH([C]) +ax_pthread_ok=no + +# We used to check for pthread.h first, but this fails if pthread.h +# requires special compiler flags (e.g. on Tru64 or Sequent). +# It gets checked for in the link test anyway. + +# First of all, check if the user has set any of the PTHREAD_LIBS, +# etcetera environment variables, and if threads linking works using +# them: +if test "x$PTHREAD_CFLAGS$PTHREAD_LIBS" != "x"; then + ax_pthread_save_CC="$CC" + ax_pthread_save_CFLAGS="$CFLAGS" + ax_pthread_save_LIBS="$LIBS" + AS_IF([test "x$PTHREAD_CC" != "x"], [CC="$PTHREAD_CC"]) + CFLAGS="$CFLAGS $PTHREAD_CFLAGS" + LIBS="$PTHREAD_LIBS $LIBS" + AC_MSG_CHECKING([for pthread_join using $CC $PTHREAD_CFLAGS $PTHREAD_LIBS]) + AC_LINK_IFELSE([AC_LANG_CALL([], [pthread_join])], [ax_pthread_ok=yes]) + AC_MSG_RESULT([$ax_pthread_ok]) + if test "x$ax_pthread_ok" = "xno"; then + PTHREAD_LIBS="" + PTHREAD_CFLAGS="" + fi + CC="$ax_pthread_save_CC" + CFLAGS="$ax_pthread_save_CFLAGS" + LIBS="$ax_pthread_save_LIBS" +fi + +# We must check for the threads library under a number of different +# names; the ordering is very important because some systems +# (e.g. DEC) have both -lpthread and -lpthreads, where one of the +# libraries is broken (non-POSIX). + +# Create a list of thread flags to try. Items with a "," contain both +# C compiler flags (before ",") and linker flags (after ","). Other items +# starting with a "-" are C compiler flags, and remaining items are +# library names, except for "none" which indicates that we try without +# any flags at all, and "pthread-config" which is a program returning +# the flags for the Pth emulation library. + +ax_pthread_flags="pthreads none -Kthread -pthread -pthreads -mthreads pthread --thread-safe -mt pthread-config" + +# The ordering *is* (sometimes) important. Some notes on the +# individual items follow: + +# pthreads: AIX (must check this before -lpthread) +# none: in case threads are in libc; should be tried before -Kthread and +# other compiler flags to prevent continual compiler warnings +# -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h) +# -pthread: Linux/gcc (kernel threads), BSD/gcc (userland threads), Tru64 +# (Note: HP C rejects this with "bad form for `-t' option") +# -pthreads: Solaris/gcc (Note: HP C also rejects) +# -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it +# doesn't hurt to check since this sometimes defines pthreads and +# -D_REENTRANT too), HP C (must be checked before -lpthread, which +# is present but should not be used directly; and before -mthreads, +# because the compiler interprets this as "-mt" + "-hreads") +# -mthreads: Mingw32/gcc, Lynx/gcc +# pthread: Linux, etcetera +# --thread-safe: KAI C++ +# pthread-config: use pthread-config program (for GNU Pth library) + +case $host_os in + + freebsd*) + + # -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able) + # lthread: LinuxThreads port on FreeBSD (also preferred to -pthread) + + ax_pthread_flags="-kthread lthread $ax_pthread_flags" + ;; + + hpux*) + + # From the cc(1) man page: "[-mt] Sets various -D flags to enable + # multi-threading and also sets -lpthread." + + ax_pthread_flags="-mt -pthread pthread $ax_pthread_flags" + ;; + + openedition*) + + # IBM z/OS requires a feature-test macro to be defined in order to + # enable POSIX threads at all, so give the user a hint if this is + # not set. (We don't define these ourselves, as they can affect + # other portions of the system API in unpredictable ways.) + + AC_EGREP_CPP([AX_PTHREAD_ZOS_MISSING], + [ +# if !defined(_OPEN_THREADS) && !defined(_UNIX03_THREADS) + AX_PTHREAD_ZOS_MISSING +# endif + ], + [AC_MSG_WARN([IBM z/OS requires -D_OPEN_THREADS or -D_UNIX03_THREADS to enable pthreads support.])]) + ;; + + solaris*) + + # On Solaris (at least, for some versions), libc contains stubbed + # (non-functional) versions of the pthreads routines, so link-based + # tests will erroneously succeed. (N.B.: The stubs are missing + # pthread_cleanup_push, or rather a function called by this macro, + # so we could check for that, but who knows whether they'll stub + # that too in a future libc.) So we'll check first for the + # standard Solaris way of linking pthreads (-mt -lpthread). + + ax_pthread_flags="-mt,-lpthread pthread $ax_pthread_flags" + ;; +esac + +# Are we compiling with Clang? + +AC_CACHE_CHECK([whether $CC is Clang], + [ax_cv_PTHREAD_CLANG], + [ax_cv_PTHREAD_CLANG=no + # Note that Autoconf sets GCC=yes for Clang as well as GCC + if test "x$GCC" = "xyes"; then + AC_EGREP_CPP([AX_PTHREAD_CC_IS_CLANG], + [/* Note: Clang 2.7 lacks __clang_[a-z]+__ */ +# if defined(__clang__) && defined(__llvm__) + AX_PTHREAD_CC_IS_CLANG +# endif + ], + [ax_cv_PTHREAD_CLANG=yes]) + fi + ]) +ax_pthread_clang="$ax_cv_PTHREAD_CLANG" + + +# GCC generally uses -pthread, or -pthreads on some platforms (e.g. SPARC) + +# Note that for GCC and Clang -pthread generally implies -lpthread, +# except when -nostdlib is passed. +# This is problematic using libtool to build C++ shared libraries with pthread: +# [1] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25460 +# [2] https://bugzilla.redhat.com/show_bug.cgi?id=661333 +# [3] https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=468555 +# To solve this, first try -pthread together with -lpthread for GCC + +AS_IF([test "x$GCC" = "xyes"], + [ax_pthread_flags="-pthread,-lpthread -pthread -pthreads $ax_pthread_flags"]) + +# Clang takes -pthread (never supported any other flag), but we'll try with -lpthread first + +AS_IF([test "x$ax_pthread_clang" = "xyes"], + [ax_pthread_flags="-pthread,-lpthread -pthread"]) + + +# The presence of a feature test macro requesting re-entrant function +# definitions is, on some systems, a strong hint that pthreads support is +# correctly enabled + +case $host_os in + darwin* | hpux* | linux* | osf* | solaris*) + ax_pthread_check_macro="_REENTRANT" + ;; + + aix*) + ax_pthread_check_macro="_THREAD_SAFE" + ;; + + *) + ax_pthread_check_macro="--" + ;; +esac +AS_IF([test "x$ax_pthread_check_macro" = "x--"], + [ax_pthread_check_cond=0], + [ax_pthread_check_cond="!defined($ax_pthread_check_macro)"]) + + +if test "x$ax_pthread_ok" = "xno"; then +for ax_pthread_try_flag in $ax_pthread_flags; do + + case $ax_pthread_try_flag in + none) + AC_MSG_CHECKING([whether pthreads work without any flags]) + ;; + + *,*) + PTHREAD_CFLAGS=`echo $ax_pthread_try_flag | sed "s/^\(.*\),\(.*\)$/\1/"` + PTHREAD_LIBS=`echo $ax_pthread_try_flag | sed "s/^\(.*\),\(.*\)$/\2/"` + AC_MSG_CHECKING([whether pthreads work with "$PTHREAD_CFLAGS" and "$PTHREAD_LIBS"]) + ;; + + -*) + AC_MSG_CHECKING([whether pthreads work with $ax_pthread_try_flag]) + PTHREAD_CFLAGS="$ax_pthread_try_flag" + ;; + + pthread-config) + AC_CHECK_PROG([ax_pthread_config], [pthread-config], [yes], [no]) + AS_IF([test "x$ax_pthread_config" = "xno"], [continue]) + PTHREAD_CFLAGS="`pthread-config --cflags`" + PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`" + ;; + + *) + AC_MSG_CHECKING([for the pthreads library -l$ax_pthread_try_flag]) + PTHREAD_LIBS="-l$ax_pthread_try_flag" + ;; + esac + + ax_pthread_save_CFLAGS="$CFLAGS" + ax_pthread_save_LIBS="$LIBS" + CFLAGS="$CFLAGS $PTHREAD_CFLAGS" + LIBS="$PTHREAD_LIBS $LIBS" + + # Check for various functions. We must include pthread.h, + # since some functions may be macros. (On the Sequent, we + # need a special flag -Kthread to make this header compile.) + # We check for pthread_join because it is in -lpthread on IRIX + # while pthread_create is in libc. We check for pthread_attr_init + # due to DEC craziness with -lpthreads. We check for + # pthread_cleanup_push because it is one of the few pthread + # functions on Solaris that doesn't have a non-functional libc stub. + # We try pthread_create on general principles. + + AC_LINK_IFELSE([AC_LANG_PROGRAM([#include +# if $ax_pthread_check_cond +# error "$ax_pthread_check_macro must be defined" +# endif + static void *some_global = NULL; + static void routine(void *a) + { + /* To avoid any unused-parameter or + unused-but-set-parameter warning. */ + some_global = a; + } + static void *start_routine(void *a) { return a; }], + [pthread_t th; pthread_attr_t attr; + pthread_create(&th, 0, start_routine, 0); + pthread_join(th, 0); + pthread_attr_init(&attr); + pthread_cleanup_push(routine, 0); + pthread_cleanup_pop(0) /* ; */])], + [ax_pthread_ok=yes], + []) + + CFLAGS="$ax_pthread_save_CFLAGS" + LIBS="$ax_pthread_save_LIBS" + + AC_MSG_RESULT([$ax_pthread_ok]) + AS_IF([test "x$ax_pthread_ok" = "xyes"], [break]) + + PTHREAD_LIBS="" + PTHREAD_CFLAGS="" +done +fi + + +# Clang needs special handling, because older versions handle the -pthread +# option in a rather... idiosyncratic way + +if test "x$ax_pthread_clang" = "xyes"; then + + # Clang takes -pthread; it has never supported any other flag + + # (Note 1: This will need to be revisited if a system that Clang + # supports has POSIX threads in a separate library. This tends not + # to be the way of modern systems, but it's conceivable.) + + # (Note 2: On some systems, notably Darwin, -pthread is not needed + # to get POSIX threads support; the API is always present and + # active. We could reasonably leave PTHREAD_CFLAGS empty. But + # -pthread does define _REENTRANT, and while the Darwin headers + # ignore this macro, third-party headers might not.) + + # However, older versions of Clang make a point of warning the user + # that, in an invocation where only linking and no compilation is + # taking place, the -pthread option has no effect ("argument unused + # during compilation"). They expect -pthread to be passed in only + # when source code is being compiled. + # + # Problem is, this is at odds with the way Automake and most other + # C build frameworks function, which is that the same flags used in + # compilation (CFLAGS) are also used in linking. Many systems + # supported by AX_PTHREAD require exactly this for POSIX threads + # support, and in fact it is often not straightforward to specify a + # flag that is used only in the compilation phase and not in + # linking. Such a scenario is extremely rare in practice. + # + # Even though use of the -pthread flag in linking would only print + # a warning, this can be a nuisance for well-run software projects + # that build with -Werror. So if the active version of Clang has + # this misfeature, we search for an option to squash it. + + AC_CACHE_CHECK([whether Clang needs flag to prevent "argument unused" warning when linking with -pthread], + [ax_cv_PTHREAD_CLANG_NO_WARN_FLAG], + [ax_cv_PTHREAD_CLANG_NO_WARN_FLAG=unknown + # Create an alternate version of $ac_link that compiles and + # links in two steps (.c -> .o, .o -> exe) instead of one + # (.c -> exe), because the warning occurs only in the second + # step + ax_pthread_save_ac_link="$ac_link" + ax_pthread_sed='s/conftest\.\$ac_ext/conftest.$ac_objext/g' + ax_pthread_link_step=`$as_echo "$ac_link" | sed "$ax_pthread_sed"` + ax_pthread_2step_ac_link="($ac_compile) && (echo ==== >&5) && ($ax_pthread_link_step)" + ax_pthread_save_CFLAGS="$CFLAGS" + for ax_pthread_try in '' -Qunused-arguments -Wno-unused-command-line-argument unknown; do + AS_IF([test "x$ax_pthread_try" = "xunknown"], [break]) + CFLAGS="-Werror -Wunknown-warning-option $ax_pthread_try -pthread $ax_pthread_save_CFLAGS" + ac_link="$ax_pthread_save_ac_link" + AC_LINK_IFELSE([AC_LANG_SOURCE([[int main(void){return 0;}]])], + [ac_link="$ax_pthread_2step_ac_link" + AC_LINK_IFELSE([AC_LANG_SOURCE([[int main(void){return 0;}]])], + [break]) + ]) + done + ac_link="$ax_pthread_save_ac_link" + CFLAGS="$ax_pthread_save_CFLAGS" + AS_IF([test "x$ax_pthread_try" = "x"], [ax_pthread_try=no]) + ax_cv_PTHREAD_CLANG_NO_WARN_FLAG="$ax_pthread_try" + ]) + + case "$ax_cv_PTHREAD_CLANG_NO_WARN_FLAG" in + no | unknown) ;; + *) PTHREAD_CFLAGS="$ax_cv_PTHREAD_CLANG_NO_WARN_FLAG $PTHREAD_CFLAGS" ;; + esac + +fi # $ax_pthread_clang = yes + + + +# Various other checks: +if test "x$ax_pthread_ok" = "xyes"; then + ax_pthread_save_CFLAGS="$CFLAGS" + ax_pthread_save_LIBS="$LIBS" + CFLAGS="$CFLAGS $PTHREAD_CFLAGS" + LIBS="$PTHREAD_LIBS $LIBS" + + # Detect AIX lossage: JOINABLE attribute is called UNDETACHED. + AC_CACHE_CHECK([for joinable pthread attribute], + [ax_cv_PTHREAD_JOINABLE_ATTR], + [ax_cv_PTHREAD_JOINABLE_ATTR=unknown + for ax_pthread_attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do + AC_LINK_IFELSE([AC_LANG_PROGRAM([#include ], + [int attr = $ax_pthread_attr; return attr /* ; */])], + [ax_cv_PTHREAD_JOINABLE_ATTR=$ax_pthread_attr; break], + []) + done + ]) + AS_IF([test "x$ax_cv_PTHREAD_JOINABLE_ATTR" != "xunknown" && \ + test "x$ax_cv_PTHREAD_JOINABLE_ATTR" != "xPTHREAD_CREATE_JOINABLE" && \ + test "x$ax_pthread_joinable_attr_defined" != "xyes"], + [AC_DEFINE_UNQUOTED([PTHREAD_CREATE_JOINABLE], + [$ax_cv_PTHREAD_JOINABLE_ATTR], + [Define to necessary symbol if this constant + uses a non-standard name on your system.]) + ax_pthread_joinable_attr_defined=yes + ]) + + AC_CACHE_CHECK([whether more special flags are required for pthreads], + [ax_cv_PTHREAD_SPECIAL_FLAGS], + [ax_cv_PTHREAD_SPECIAL_FLAGS=no + case $host_os in + solaris*) + ax_cv_PTHREAD_SPECIAL_FLAGS="-D_POSIX_PTHREAD_SEMANTICS" + ;; + esac + ]) + AS_IF([test "x$ax_cv_PTHREAD_SPECIAL_FLAGS" != "xno" && \ + test "x$ax_pthread_special_flags_added" != "xyes"], + [PTHREAD_CFLAGS="$ax_cv_PTHREAD_SPECIAL_FLAGS $PTHREAD_CFLAGS" + ax_pthread_special_flags_added=yes]) + + AC_CACHE_CHECK([for PTHREAD_PRIO_INHERIT], + [ax_cv_PTHREAD_PRIO_INHERIT], + [AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include ]], + [[int i = PTHREAD_PRIO_INHERIT; + return i;]])], + [ax_cv_PTHREAD_PRIO_INHERIT=yes], + [ax_cv_PTHREAD_PRIO_INHERIT=no]) + ]) + AS_IF([test "x$ax_cv_PTHREAD_PRIO_INHERIT" = "xyes" && \ + test "x$ax_pthread_prio_inherit_defined" != "xyes"], + [AC_DEFINE([HAVE_PTHREAD_PRIO_INHERIT], [1], [Have PTHREAD_PRIO_INHERIT.]) + ax_pthread_prio_inherit_defined=yes + ]) + + CFLAGS="$ax_pthread_save_CFLAGS" + LIBS="$ax_pthread_save_LIBS" + + # More AIX lossage: compile with *_r variant + if test "x$GCC" != "xyes"; then + case $host_os in + aix*) + AS_CASE(["x/$CC"], + [x*/c89|x*/c89_128|x*/c99|x*/c99_128|x*/cc|x*/cc128|x*/xlc|x*/xlc_v6|x*/xlc128|x*/xlc128_v6], + [#handle absolute path differently from PATH based program lookup + AS_CASE(["x$CC"], + [x/*], + [AS_IF([AS_EXECUTABLE_P([${CC}_r])],[PTHREAD_CC="${CC}_r"])], + [AC_CHECK_PROGS([PTHREAD_CC],[${CC}_r],[$CC])])]) + ;; + esac + fi +fi + +test -n "$PTHREAD_CC" || PTHREAD_CC="$CC" + +AC_SUBST([PTHREAD_LIBS]) +AC_SUBST([PTHREAD_CFLAGS]) +AC_SUBST([PTHREAD_CC]) + +# Finally, execute ACTION-IF-FOUND/ACTION-IF-NOT-FOUND: +if test "x$ax_pthread_ok" = "xyes"; then + ifelse([$1],,[AC_DEFINE([HAVE_PTHREAD],[1],[Define if you have POSIX threads libraries and header files.])],[$1]) + : +else + ax_pthread_ok=no + $2 +fi +AC_LANG_POP +])dnl AX_PTHREAD diff --git a/tools/env-vars-generator/protobuf/objectivec/.gitignore b/tools/env-vars-generator/protobuf/objectivec/.gitignore new file mode 100644 index 0000000..f786ffc --- /dev/null +++ b/tools/env-vars-generator/protobuf/objectivec/.gitignore @@ -0,0 +1,23 @@ +## Build generated +build/ +DerivedData/ + +## Various settings +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata/ + +## Other +*.moved-aside +*.xccheckout +*.xcscmblueprint + +## Obj-C/Swift specific +*.hmap +*.ipa diff --git a/tools/env-vars-generator/protobuf/objectivec/DevTools/pddm.py b/tools/env-vars-generator/protobuf/objectivec/DevTools/pddm.py new file mode 100755 index 0000000..b572cc7 --- /dev/null +++ b/tools/env-vars-generator/protobuf/objectivec/DevTools/pddm.py @@ -0,0 +1,690 @@ +#! /usr/bin/python +# +# Protocol Buffers - Google's data interchange format +# Copyright 2015 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. + +"""PDDM - Poor Developers' Debug-able Macros + +A simple markup that can be added in comments of source so they can then be +expanded out into code. Most of this could be done with CPP macros, but then +developers can't really step through them in the debugger, this way they are +expanded to the same code, but you can debug them. + +Any file can be processed, but the syntax is designed around a C based compiler. +Processed lines start with "//%". There are three types of sections you can +create: Text (left alone), Macro Definitions, and Macro Expansions. There is +no order required between definitions and expansions, all definitions are read +before any expansions are processed (thus, if desired, definitions can be put +at the end of the file to keep them out of the way of the code). + +Macro Definitions are started with "//%PDDM-DEFINE Name(args)" and all lines +afterwards that start with "//%" are included in the definition. Multiple +macros can be defined in one block by just using a another "//%PDDM-DEFINE" +line to start the next macro. Optionally, a macro can be ended with +"//%PDDM-DEFINE-END", this can be useful when you want to make it clear that +trailing blank lines are included in the macro. You can also end a definition +with an expansion. + +Macro Expansions are started by single lines containing +"//%PDDM-EXPAND Name(args)" and then with "//%PDDM-EXPAND-END" or another +expansions. All lines in-between are replaced by the result of the expansion. +The first line of the expansion is always a blank like just for readability. + +Expansion itself is pretty simple, one macro can invoke another macro, but +you cannot nest the invoke of a macro in another macro (i.e. - can't do +"foo(bar(a))", but you can define foo(a) and bar(b) where bar invokes foo() +within its expansion. + +When macros are expanded, the arg references can also add "$O" suffix to the +name (i.e. - "NAME$O") to specify an option to be applied. The options are: + + $S - Replace each character in the value with a space. + $l - Lowercase the first letter of the value. + $L - Lowercase the whole value. + $u - Uppercase the first letter of the value. + $U - Uppercase the whole value. + +Within a macro you can use ## to cause things to get joined together after +expansion (i.e. - "a##b" within a macro will become "ab"). + +Example: + + int foo(MyEnum x) { + switch (x) { + //%PDDM-EXPAND case(Enum_Left, 1) + //%PDDM-EXPAND case(Enum_Center, 2) + //%PDDM-EXPAND case(Enum_Right, 3) + //%PDDM-EXPAND-END + } + + //%PDDM-DEFINE case(_A, _B) + //% case _A: + //% return _B; + + A macro ends at the start of the next one, or an optional %PDDM-DEFINE-END + can be used to avoid adding extra blank lines/returns (or make it clear when + it is desired). + + One macro can invoke another by simply using its name NAME(ARGS). You cannot + nest an invoke inside another (i.e. - NAME1(NAME2(ARGS)) isn't supported). + + Within a macro you can use ## to cause things to get joined together after + processing (i.e. - "a##b" within a macro will become "ab"). + + +""" + +import optparse +import os +import re +import sys + + +# Regex for macro definition. +_MACRO_RE = re.compile(r'(?P\w+)\((?P.*?)\)') +# Regex for macro's argument definition. +_MACRO_ARG_NAME_RE = re.compile(r'^\w+$') + +# Line inserted after each EXPAND. +_GENERATED_CODE_LINE = ( + '// This block of code is generated, do not edit it directly.' +) + + +def _MacroRefRe(macro_names): + # Takes in a list of macro names and makes a regex that will match invokes + # of those macros. + return re.compile(r'\b(?P(?P(%s))\((?P.*?)\))' % + '|'.join(macro_names)) + + +def _MacroArgRefRe(macro_arg_names): + # Takes in a list of macro arg names and makes a regex that will match + # uses of those args. + return re.compile(r'\b(?P(%s))(\$(?P

+ /// Unit tests for JSON parsing. + /// + public class JsonParserTest + { + // Sanity smoke test + [Test] + public void AllTypesRoundtrip() + { + AssertRoundtrip(SampleMessages.CreateFullTestAllTypes()); + } + + [Test] + public void Maps() + { + AssertRoundtrip(new TestMap { MapStringString = { { "with spaces", "bar" }, { "a", "b" } } }); + AssertRoundtrip(new TestMap { MapInt32Int32 = { { 0, 1 }, { 2, 3 } } }); + AssertRoundtrip(new TestMap { MapBoolBool = { { false, true }, { true, false } } }); + } + + [Test] + [TestCase(" 1 ")] + [TestCase("+1")] + [TestCase("1,000")] + [TestCase("1.5")] + public void IntegerMapKeysAreStrict(string keyText) + { + // Test that integer parsing is strict. We assume that if this is correct for int32, + // it's correct for other numeric key types. + var json = "{ \"mapInt32Int32\": { \"" + keyText + "\" : \"1\" } }"; + Assert.Throws(() => JsonParser.Default.Parse(json)); + } + + [Test] + public void OriginalFieldNameAccepted() + { + var json = "{ \"single_int32\": 10 }"; + var expected = new TestAllTypes { SingleInt32 = 10 }; + Assert.AreEqual(expected, TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + public void SourceContextRoundtrip() + { + AssertRoundtrip(new SourceContext { FileName = "foo.proto" }); + } + + [Test] + public void SingularWrappers_DefaultNonNullValues() + { + var message = new TestWellKnownTypes + { + StringField = "", + BytesField = ByteString.Empty, + BoolField = false, + FloatField = 0f, + DoubleField = 0d, + Int32Field = 0, + Int64Field = 0, + Uint32Field = 0, + Uint64Field = 0 + }; + AssertRoundtrip(message); + } + + [Test] + public void SingularWrappers_NonDefaultValues() + { + var message = new TestWellKnownTypes + { + StringField = "x", + BytesField = ByteString.CopyFrom(1, 2, 3), + BoolField = true, + FloatField = 12.5f, + DoubleField = 12.25d, + Int32Field = 1, + Int64Field = 2, + Uint32Field = 3, + Uint64Field = 4 + }; + AssertRoundtrip(message); + } + + [Test] + public void SingularWrappers_ExplicitNulls() + { + // When we parse the "valueField": null part, we remember it... basically, it's one case + // where explicit default values don't fully roundtrip. + var message = new TestWellKnownTypes { ValueField = Value.ForNull() }; + var json = new JsonFormatter(new JsonFormatter.Settings(true)).Format(message); + var parsed = JsonParser.Default.Parse(json); + Assert.AreEqual(message, parsed); + } + + [Test] + [TestCase(typeof(BoolValue), "true", true)] + [TestCase(typeof(Int32Value), "32", 32)] + [TestCase(typeof(Int64Value), "32", 32L)] + [TestCase(typeof(Int64Value), "\"32\"", 32L)] + [TestCase(typeof(UInt32Value), "32", 32U)] + [TestCase(typeof(UInt64Value), "\"32\"", 32UL)] + [TestCase(typeof(UInt64Value), "32", 32UL)] + [TestCase(typeof(StringValue), "\"foo\"", "foo")] + [TestCase(typeof(FloatValue), "1.5", 1.5f)] + [TestCase(typeof(DoubleValue), "1.5", 1.5d)] + public void Wrappers_Standalone(System.Type wrapperType, string json, object expectedValue) + { + IMessage parsed = (IMessage)Activator.CreateInstance(wrapperType); + IMessage expected = (IMessage)Activator.CreateInstance(wrapperType); + JsonParser.Default.Merge(parsed, "null"); + Assert.AreEqual(expected, parsed); + + JsonParser.Default.Merge(parsed, json); + expected.Descriptor.Fields[WrappersReflection.WrapperValueFieldNumber].Accessor.SetValue(expected, expectedValue); + Assert.AreEqual(expected, parsed); + } + + [Test] + public void ExplicitNullValue() + { + string json = "{\"valueField\": null}"; + var message = JsonParser.Default.Parse(json); + Assert.AreEqual(new TestWellKnownTypes { ValueField = Value.ForNull() }, message); + } + + [Test] + public void BytesWrapper_Standalone() + { + ByteString data = ByteString.CopyFrom(1, 2, 3); + // Can't do this with attributes... + var parsed = JsonParser.Default.Parse(WrapInQuotes(data.ToBase64())); + var expected = new BytesValue { Value = data }; + Assert.AreEqual(expected, parsed); + } + + [Test] + public void RepeatedWrappers() + { + var message = new RepeatedWellKnownTypes + { + BoolField = { true, false }, + BytesField = { ByteString.CopyFrom(1, 2, 3), ByteString.CopyFrom(4, 5, 6), ByteString.Empty }, + DoubleField = { 12.5, -1.5, 0d }, + FloatField = { 123.25f, -20f, 0f }, + Int32Field = { int.MaxValue, int.MinValue, 0 }, + Int64Field = { long.MaxValue, long.MinValue, 0L }, + StringField = { "First", "Second", "" }, + Uint32Field = { uint.MaxValue, uint.MinValue, 0U }, + Uint64Field = { ulong.MaxValue, ulong.MinValue, 0UL }, + }; + AssertRoundtrip(message); + } + + [Test] + public void RepeatedField_NullElementProhibited() + { + string json = "{ \"repeated_foreign_message\": [null] }"; + Assert.Throws(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + public void RepeatedField_NullOverallValueAllowed() + { + string json = "{ \"repeated_foreign_message\": null }"; + Assert.AreEqual(new TestAllTypes(), TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("{ \"mapInt32Int32\": { \"10\": null }")] + [TestCase("{ \"mapStringString\": { \"abc\": null }")] + [TestCase("{ \"mapInt32ForeignMessage\": { \"10\": null }")] + public void MapField_NullValueProhibited(string json) + { + Assert.Throws(() => TestMap.Parser.ParseJson(json)); + } + + [Test] + public void MapField_NullOverallValueAllowed() + { + string json = "{ \"mapInt32Int32\": null }"; + Assert.AreEqual(new TestMap(), TestMap.Parser.ParseJson(json)); + } + + [Test] + public void IndividualWrapperTypes() + { + Assert.AreEqual(new StringValue { Value = "foo" }, StringValue.Parser.ParseJson("\"foo\"")); + Assert.AreEqual(new Int32Value { Value = 1 }, Int32Value.Parser.ParseJson("1")); + // Can parse strings directly too + Assert.AreEqual(new Int32Value { Value = 1 }, Int32Value.Parser.ParseJson("\"1\"")); + } + + private static void AssertRoundtrip(T message) where T : IMessage, new() + { + var clone = message.Clone(); + var json = JsonFormatter.Default.Format(message); + var parsed = JsonParser.Default.Parse(json); + Assert.AreEqual(clone, parsed); + } + + [Test] + [TestCase("0", 0)] + [TestCase("-0", 0)] // Not entirely clear whether we intend to allow this... + [TestCase("1", 1)] + [TestCase("-1", -1)] + [TestCase("2147483647", 2147483647)] + [TestCase("-2147483648", -2147483648)] + public void StringToInt32_Valid(string jsonValue, int expectedParsedValue) + { + string json = "{ \"singleInt32\": \"" + jsonValue + "\"}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleInt32); + } + + [Test] + [TestCase("+0")] + [TestCase(" 1")] + [TestCase("1 ")] + [TestCase("00")] + [TestCase("-00")] + [TestCase("--1")] + [TestCase("+1")] + [TestCase("1.5")] + [TestCase("1e10")] + [TestCase("2147483648")] + [TestCase("-2147483649")] + public void StringToInt32_Invalid(string jsonValue) + { + string json = "{ \"singleInt32\": \"" + jsonValue + "\"}"; + Assert.Throws(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("0", 0U)] + [TestCase("1", 1U)] + [TestCase("4294967295", 4294967295U)] + public void StringToUInt32_Valid(string jsonValue, uint expectedParsedValue) + { + string json = "{ \"singleUint32\": \"" + jsonValue + "\"}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleUint32); + } + + // Assume that anything non-bounds-related is covered in the Int32 case + [Test] + [TestCase("-1")] + [TestCase("4294967296")] + public void StringToUInt32_Invalid(string jsonValue) + { + string json = "{ \"singleUint32\": \"" + jsonValue + "\"}"; + Assert.Throws(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("0", 0L)] + [TestCase("1", 1L)] + [TestCase("-1", -1L)] + [TestCase("9223372036854775807", 9223372036854775807)] + [TestCase("-9223372036854775808", -9223372036854775808)] + public void StringToInt64_Valid(string jsonValue, long expectedParsedValue) + { + string json = "{ \"singleInt64\": \"" + jsonValue + "\"}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleInt64); + } + + // Assume that anything non-bounds-related is covered in the Int32 case + [Test] + [TestCase("-9223372036854775809")] + [TestCase("9223372036854775808")] + public void StringToInt64_Invalid(string jsonValue) + { + string json = "{ \"singleInt64\": \"" + jsonValue + "\"}"; + Assert.Throws(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("0", 0UL)] + [TestCase("1", 1UL)] + [TestCase("18446744073709551615", 18446744073709551615)] + public void StringToUInt64_Valid(string jsonValue, ulong expectedParsedValue) + { + string json = "{ \"singleUint64\": \"" + jsonValue + "\"}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleUint64); + } + + // Assume that anything non-bounds-related is covered in the Int32 case + [Test] + [TestCase("-1")] + [TestCase("18446744073709551616")] + public void StringToUInt64_Invalid(string jsonValue) + { + string json = "{ \"singleUint64\": \"" + jsonValue + "\"}"; + Assert.Throws(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("0", 0d)] + [TestCase("1", 1d)] + [TestCase("1.000000", 1d)] + [TestCase("1.0000000000000000000000001", 1d)] // We don't notice that we haven't preserved the exact value + [TestCase("-1", -1d)] + [TestCase("1e1", 10d)] + [TestCase("1e01", 10d)] // Leading decimals are allowed in exponents + [TestCase("1E1", 10d)] // Either case is fine + [TestCase("-1e1", -10d)] + [TestCase("1.5e1", 15d)] + [TestCase("-1.5e1", -15d)] + [TestCase("15e-1", 1.5d)] + [TestCase("-15e-1", -1.5d)] + [TestCase("1.79769e308", 1.79769e308)] + [TestCase("-1.79769e308", -1.79769e308)] + [TestCase("Infinity", double.PositiveInfinity)] + [TestCase("-Infinity", double.NegativeInfinity)] + [TestCase("NaN", double.NaN)] + public void StringToDouble_Valid(string jsonValue, double expectedParsedValue) + { + string json = "{ \"singleDouble\": \"" + jsonValue + "\"}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleDouble); + } + + [Test] + [TestCase("1.7977e308")] + [TestCase("-1.7977e308")] + [TestCase("1e309")] + [TestCase("1,0")] + [TestCase("1.0.0")] + [TestCase("+1")] + [TestCase("00")] + [TestCase("01")] + [TestCase("-00")] + [TestCase("-01")] + [TestCase("--1")] + [TestCase(" Infinity")] + [TestCase(" -Infinity")] + [TestCase("NaN ")] + [TestCase("Infinity ")] + [TestCase("-Infinity ")] + [TestCase(" NaN")] + [TestCase("INFINITY")] + [TestCase("nan")] + [TestCase("\u00BD")] // 1/2 as a single Unicode character. Just sanity checking... + public void StringToDouble_Invalid(string jsonValue) + { + string json = "{ \"singleDouble\": \"" + jsonValue + "\"}"; + Assert.Throws(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("0", 0f)] + [TestCase("1", 1f)] + [TestCase("1.000000", 1f)] + [TestCase("-1", -1f)] + [TestCase("3.402823e38", 3.402823e38f)] + [TestCase("-3.402823e38", -3.402823e38f)] + [TestCase("1.5e1", 15f)] + [TestCase("15e-1", 1.5f)] + public void StringToFloat_Valid(string jsonValue, float expectedParsedValue) + { + string json = "{ \"singleFloat\": \"" + jsonValue + "\"}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleFloat); + } + + [Test] + [TestCase("3.402824e38")] + [TestCase("-3.402824e38")] + [TestCase("1,0")] + [TestCase("1.0.0")] + [TestCase("+1")] + [TestCase("00")] + [TestCase("--1")] + public void StringToFloat_Invalid(string jsonValue) + { + string json = "{ \"singleFloat\": \"" + jsonValue + "\"}"; + Assert.Throws(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("0", 0)] + [TestCase("-0", 0)] // Not entirely clear whether we intend to allow this... + [TestCase("1", 1)] + [TestCase("-1", -1)] + [TestCase("2147483647", 2147483647)] + [TestCase("-2147483648", -2147483648)] + [TestCase("1e1", 10)] + [TestCase("-1e1", -10)] + [TestCase("10.00", 10)] + [TestCase("-10.00", -10)] + public void NumberToInt32_Valid(string jsonValue, int expectedParsedValue) + { + string json = "{ \"singleInt32\": " + jsonValue + "}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleInt32); + } + + [Test] + [TestCase("+0", typeof(InvalidJsonException))] + [TestCase("00", typeof(InvalidJsonException))] + [TestCase("-00", typeof(InvalidJsonException))] + [TestCase("--1", typeof(InvalidJsonException))] + [TestCase("+1", typeof(InvalidJsonException))] + [TestCase("1.5", typeof(InvalidProtocolBufferException))] + // Value is out of range + [TestCase("1e10", typeof(InvalidProtocolBufferException))] + [TestCase("2147483648", typeof(InvalidProtocolBufferException))] + [TestCase("-2147483649", typeof(InvalidProtocolBufferException))] + public void NumberToInt32_Invalid(string jsonValue, System.Type expectedExceptionType) + { + string json = "{ \"singleInt32\": " + jsonValue + "}"; + Assert.Throws(expectedExceptionType, () => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("0", 0U)] + [TestCase("1", 1U)] + [TestCase("4294967295", 4294967295U)] + public void NumberToUInt32_Valid(string jsonValue, uint expectedParsedValue) + { + string json = "{ \"singleUint32\": " + jsonValue + "}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleUint32); + } + + // Assume that anything non-bounds-related is covered in the Int32 case + [Test] + [TestCase("-1")] + [TestCase("4294967296")] + public void NumberToUInt32_Invalid(string jsonValue) + { + string json = "{ \"singleUint32\": " + jsonValue + "}"; + Assert.Throws(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("0", 0L)] + [TestCase("1", 1L)] + [TestCase("-1", -1L)] + // long.MaxValue isn't actually representable as a double. This string value is the highest + // representable value which isn't greater than long.MaxValue. + [TestCase("9223372036854774784", 9223372036854774784)] + [TestCase("-9223372036854775808", -9223372036854775808)] + public void NumberToInt64_Valid(string jsonValue, long expectedParsedValue) + { + string json = "{ \"singleInt64\": " + jsonValue + "}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleInt64); + } + + // Assume that anything non-bounds-related is covered in the Int32 case + [Test] + [TestCase("9223372036854775808")] + // Theoretical bound would be -9223372036854775809, but when that is parsed to a double + // we end up with the exact value of long.MinValue due to lack of precision. The value here + // is the "next double down". + [TestCase("-9223372036854780000")] + public void NumberToInt64_Invalid(string jsonValue) + { + string json = "{ \"singleInt64\": " + jsonValue + "}"; + Assert.Throws(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("0", 0UL)] + [TestCase("1", 1UL)] + // ulong.MaxValue isn't representable as a double. This value is the largest double within + // the range of ulong. + [TestCase("18446744073709549568", 18446744073709549568UL)] + public void NumberToUInt64_Valid(string jsonValue, ulong expectedParsedValue) + { + string json = "{ \"singleUint64\": " + jsonValue + "}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleUint64); + } + + // Assume that anything non-bounds-related is covered in the Int32 case + [Test] + [TestCase("-1")] + [TestCase("18446744073709551616")] + public void NumberToUInt64_Invalid(string jsonValue) + { + string json = "{ \"singleUint64\": " + jsonValue + "}"; + Assert.Throws(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("0", 0d)] + [TestCase("1", 1d)] + [TestCase("1.000000", 1d)] + [TestCase("1.0000000000000000000000001", 1d)] // We don't notice that we haven't preserved the exact value + [TestCase("-1", -1d)] + [TestCase("1e1", 10d)] + [TestCase("1e01", 10d)] // Leading decimals are allowed in exponents + [TestCase("1E1", 10d)] // Either case is fine + [TestCase("-1e1", -10d)] + [TestCase("1.5e1", 15d)] + [TestCase("-1.5e1", -15d)] + [TestCase("15e-1", 1.5d)] + [TestCase("-15e-1", -1.5d)] + [TestCase("1.79769e308", 1.79769e308)] + [TestCase("-1.79769e308", -1.79769e308)] + public void NumberToDouble_Valid(string jsonValue, double expectedParsedValue) + { + string json = "{ \"singleDouble\": " + jsonValue + "}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleDouble); + } + + [Test] + [TestCase("1.7977e308")] + [TestCase("-1.7977e308")] + [TestCase("1e309")] + [TestCase("1,0")] + [TestCase("1.0.0")] + [TestCase("+1")] + [TestCase("00")] + [TestCase("--1")] + [TestCase("\u00BD")] // 1/2 as a single Unicode character. Just sanity checking... + public void NumberToDouble_Invalid(string jsonValue) + { + string json = "{ \"singleDouble\": " + jsonValue + "}"; + Assert.Throws(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("0", 0f)] + [TestCase("1", 1f)] + [TestCase("1.000000", 1f)] + [TestCase("-1", -1f)] + [TestCase("3.402823e38", 3.402823e38f)] + [TestCase("-3.402823e38", -3.402823e38f)] + [TestCase("1.5e1", 15f)] + [TestCase("15e-1", 1.5f)] + public void NumberToFloat_Valid(string jsonValue, float expectedParsedValue) + { + string json = "{ \"singleFloat\": " + jsonValue + "}"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(expectedParsedValue, parsed.SingleFloat); + } + + [Test] + [TestCase("3.402824e38", typeof(InvalidProtocolBufferException))] + [TestCase("-3.402824e38", typeof(InvalidProtocolBufferException))] + [TestCase("1,0", typeof(InvalidJsonException))] + [TestCase("1.0.0", typeof(InvalidJsonException))] + [TestCase("+1", typeof(InvalidJsonException))] + [TestCase("00", typeof(InvalidJsonException))] + [TestCase("--1", typeof(InvalidJsonException))] + public void NumberToFloat_Invalid(string jsonValue, System.Type expectedExceptionType) + { + string json = "{ \"singleFloat\": " + jsonValue + "}"; + Assert.Throws(expectedExceptionType, () => TestAllTypes.Parser.ParseJson(json)); + } + + // The simplest way of testing that the value has parsed correctly is to reformat it, + // as we trust the formatting. In many cases that will give the same result as the input, + // so in those cases we accept an expectedFormatted value of null. Sometimes the results + // will be different though, due to a different number of digits being provided. + [Test] + // Z offset + [TestCase("2015-10-09T14:46:23.123456789Z", null)] + [TestCase("2015-10-09T14:46:23.123456Z", null)] + [TestCase("2015-10-09T14:46:23.123Z", null)] + [TestCase("2015-10-09T14:46:23Z", null)] + [TestCase("2015-10-09T14:46:23.123456000Z", "2015-10-09T14:46:23.123456Z")] + [TestCase("2015-10-09T14:46:23.1234560Z", "2015-10-09T14:46:23.123456Z")] + [TestCase("2015-10-09T14:46:23.123000000Z", "2015-10-09T14:46:23.123Z")] + [TestCase("2015-10-09T14:46:23.1230Z", "2015-10-09T14:46:23.123Z")] + [TestCase("2015-10-09T14:46:23.00Z", "2015-10-09T14:46:23Z")] + + // +00:00 offset + [TestCase("2015-10-09T14:46:23.123456789+00:00", "2015-10-09T14:46:23.123456789Z")] + [TestCase("2015-10-09T14:46:23.123456+00:00", "2015-10-09T14:46:23.123456Z")] + [TestCase("2015-10-09T14:46:23.123+00:00", "2015-10-09T14:46:23.123Z")] + [TestCase("2015-10-09T14:46:23+00:00", "2015-10-09T14:46:23Z")] + [TestCase("2015-10-09T14:46:23.123456000+00:00", "2015-10-09T14:46:23.123456Z")] + [TestCase("2015-10-09T14:46:23.1234560+00:00", "2015-10-09T14:46:23.123456Z")] + [TestCase("2015-10-09T14:46:23.123000000+00:00", "2015-10-09T14:46:23.123Z")] + [TestCase("2015-10-09T14:46:23.1230+00:00", "2015-10-09T14:46:23.123Z")] + [TestCase("2015-10-09T14:46:23.00+00:00", "2015-10-09T14:46:23Z")] + + // Other offsets (assume by now that the subsecond handling is okay) + [TestCase("2015-10-09T15:46:23.123456789+01:00", "2015-10-09T14:46:23.123456789Z")] + [TestCase("2015-10-09T13:46:23.123456789-01:00", "2015-10-09T14:46:23.123456789Z")] + [TestCase("2015-10-09T15:16:23.123456789+00:30", "2015-10-09T14:46:23.123456789Z")] + [TestCase("2015-10-09T14:16:23.123456789-00:30", "2015-10-09T14:46:23.123456789Z")] + [TestCase("2015-10-09T16:31:23.123456789+01:45", "2015-10-09T14:46:23.123456789Z")] + [TestCase("2015-10-09T13:01:23.123456789-01:45", "2015-10-09T14:46:23.123456789Z")] + [TestCase("2015-10-10T08:46:23.123456789+18:00", "2015-10-09T14:46:23.123456789Z")] + [TestCase("2015-10-08T20:46:23.123456789-18:00", "2015-10-09T14:46:23.123456789Z")] + + // Leap years and min/max + [TestCase("2016-02-29T14:46:23.123456789Z", null)] + [TestCase("2000-02-29T14:46:23.123456789Z", null)] + [TestCase("0001-01-01T00:00:00Z", null)] + [TestCase("9999-12-31T23:59:59.999999999Z", null)] + public void Timestamp_Valid(string jsonValue, string expectedFormatted) + { + expectedFormatted = expectedFormatted ?? jsonValue; + string json = WrapInQuotes(jsonValue); + var parsed = Timestamp.Parser.ParseJson(json); + Assert.AreEqual(WrapInQuotes(expectedFormatted), parsed.ToString()); + } + + [Test] + [TestCase("2015-10-09 14:46:23.123456789Z", Description = "No T between date and time")] + [TestCase("2015/10/09T14:46:23.123456789Z", Description = "Wrong date separators")] + [TestCase("2015-10-09T14.46.23.123456789Z", Description = "Wrong time separators")] + [TestCase("2015-10-09T14:46:23,123456789Z", Description = "Wrong fractional second separators (valid ISO-8601 though)")] + [TestCase(" 2015-10-09T14:46:23.123456789Z", Description = "Whitespace at start")] + [TestCase("2015-10-09T14:46:23.123456789Z ", Description = "Whitespace at end")] + [TestCase("2015-10-09T14:46:23.1234567890", Description = "Too many digits")] + [TestCase("2015-10-09T14:46:23.123456789", Description = "No offset")] + [TestCase("2015-13-09T14:46:23.123456789Z", Description = "Invalid month")] + [TestCase("2015-10-32T14:46:23.123456789Z", Description = "Invalid day")] + [TestCase("2015-10-09T24:00:00.000000000Z", Description = "Invalid hour (valid ISO-8601 though)")] + [TestCase("2015-10-09T14:60:23.123456789Z", Description = "Invalid minutes")] + [TestCase("2015-10-09T14:46:60.123456789Z", Description = "Invalid seconds")] + [TestCase("2015-10-09T14:46:23.123456789+18:01", Description = "Offset too large (positive)")] + [TestCase("2015-10-09T14:46:23.123456789-18:01", Description = "Offset too large (negative)")] + [TestCase("2015-10-09T14:46:23.123456789-00:00", Description = "Local offset (-00:00) makes no sense here")] + [TestCase("0001-01-01T00:00:00+00:01", Description = "Value before earliest when offset applied")] + [TestCase("9999-12-31T23:59:59.999999999-00:01", Description = "Value after latest when offset applied")] + [TestCase("2100-02-29T14:46:23.123456789Z", Description = "Feb 29th on a non-leap-year")] + public void Timestamp_Invalid(string jsonValue) + { + string json = WrapInQuotes(jsonValue); + Assert.Throws(() => Timestamp.Parser.ParseJson(json)); + } + + [Test] + public void StructValue_Null() + { + Assert.AreEqual(new Value { NullValue = 0 }, Value.Parser.ParseJson("null")); + } + + [Test] + public void StructValue_String() + { + Assert.AreEqual(new Value { StringValue = "hi" }, Value.Parser.ParseJson("\"hi\"")); + } + + [Test] + public void StructValue_Bool() + { + Assert.AreEqual(new Value { BoolValue = true }, Value.Parser.ParseJson("true")); + Assert.AreEqual(new Value { BoolValue = false }, Value.Parser.ParseJson("false")); + } + + [Test] + public void StructValue_List() + { + Assert.AreEqual(Value.ForList(Value.ForNumber(1), Value.ForString("x")), Value.Parser.ParseJson("[1, \"x\"]")); + } + + [Test] + public void ParseListValue() + { + Assert.AreEqual(new ListValue { Values = { Value.ForNumber(1), Value.ForString("x") } }, ListValue.Parser.ParseJson("[1, \"x\"]")); + } + + [Test] + public void StructValue_Struct() + { + Assert.AreEqual( + Value.ForStruct(new Struct { Fields = { { "x", Value.ForNumber(1) }, { "y", Value.ForString("z") } } }), + Value.Parser.ParseJson("{ \"x\": 1, \"y\": \"z\" }")); + } + + [Test] + public void ParseStruct() + { + Assert.AreEqual(new Struct { Fields = { { "x", Value.ForNumber(1) }, { "y", Value.ForString("z") } } }, + Struct.Parser.ParseJson("{ \"x\": 1, \"y\": \"z\" }")); + } + + // TODO for duration parsing: upper and lower bounds. + // +/- 315576000000 seconds + + [Test] + [TestCase("1.123456789s", null)] + [TestCase("1.123456s", null)] + [TestCase("1.123s", null)] + [TestCase("1.12300s", "1.123s")] + [TestCase("1.12345s", "1.123450s")] + [TestCase("1s", null)] + [TestCase("-1.123456789s", null)] + [TestCase("-1.123456s", null)] + [TestCase("-1.123s", null)] + [TestCase("-1s", null)] + [TestCase("0.123s", null)] + [TestCase("-0.123s", null)] + [TestCase("123456.123s", null)] + [TestCase("-123456.123s", null)] + // Upper and lower bounds + [TestCase("315576000000s", null)] + [TestCase("-315576000000s", null)] + public void Duration_Valid(string jsonValue, string expectedFormatted) + { + expectedFormatted = expectedFormatted ?? jsonValue; + string json = WrapInQuotes(jsonValue); + var parsed = Duration.Parser.ParseJson(json); + Assert.AreEqual(WrapInQuotes(expectedFormatted), parsed.ToString()); + } + + // The simplest way of testing that the value has parsed correctly is to reformat it, + // as we trust the formatting. In many cases that will give the same result as the input, + // so in those cases we accept an expectedFormatted value of null. Sometimes the results + // will be different though, due to a different number of digits being provided. + [Test] + [TestCase("1.1234567890s", Description = "Too many digits")] + [TestCase("1.123456789", Description = "No suffix")] + [TestCase("1.123456789ss", Description = "Too much suffix")] + [TestCase("1.123456789S", Description = "Upper case suffix")] + [TestCase("+1.123456789s", Description = "Leading +")] + [TestCase(".123456789s", Description = "No integer before the fraction")] + [TestCase("1,123456789s", Description = "Comma as decimal separator")] + [TestCase("1x1.123456789s", Description = "Non-digit in integer part")] + [TestCase("1.1x3456789s", Description = "Non-digit in fractional part")] + [TestCase(" 1.123456789s", Description = "Whitespace before fraction")] + [TestCase("1.123456789s ", Description = "Whitespace after value")] + [TestCase("01.123456789s", Description = "Leading zero (positive)")] + [TestCase("-01.123456789s", Description = "Leading zero (negative)")] + [TestCase("--0.123456789s", Description = "Double minus sign")] + // Violate upper/lower bounds in various ways + [TestCase("315576000001s", Description = "Integer part too large")] + [TestCase("3155760000000s", Description = "Integer part too long (positive)")] + [TestCase("-3155760000000s", Description = "Integer part too long (negative)")] + public void Duration_Invalid(string jsonValue) + { + string json = WrapInQuotes(jsonValue); + Assert.Throws(() => Duration.Parser.ParseJson(json)); + } + + // Not as many tests for field masks as I'd like; more to be added when we have more + // detailed specifications. + + [Test] + [TestCase("")] + [TestCase("foo", "foo")] + [TestCase("foo,bar", "foo", "bar")] + [TestCase("foo.bar", "foo.bar")] + [TestCase("fooBar", "foo_bar")] + [TestCase("fooBar.bazQux", "foo_bar.baz_qux")] + public void FieldMask_Valid(string jsonValue, params string[] expectedPaths) + { + string json = WrapInQuotes(jsonValue); + var parsed = FieldMask.Parser.ParseJson(json); + CollectionAssert.AreEqual(expectedPaths, parsed.Paths); + } + + [Test] + [TestCase("foo_bar")] + public void FieldMask_Invalid(string jsonValue) + { + string json = WrapInQuotes(jsonValue); + Assert.Throws(() => FieldMask.Parser.ParseJson(json)); + } + + [Test] + public void Any_RegularMessage() + { + var registry = TypeRegistry.FromMessages(TestAllTypes.Descriptor); + var formatter = new JsonFormatter(new JsonFormatter.Settings(false, TypeRegistry.FromMessages(TestAllTypes.Descriptor))); + var message = new TestAllTypes { SingleInt32 = 10, SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } }; + var original = Any.Pack(message); + var json = formatter.Format(original); // This is tested in JsonFormatterTest + var parser = new JsonParser(new JsonParser.Settings(10, registry)); + Assert.AreEqual(original, parser.Parse(json)); + string valueFirstJson = "{ \"singleInt32\": 10, \"singleNestedMessage\": { \"bb\": 20 }, \"@type\": \"type.googleapis.com/protobuf_unittest.TestAllTypes\" }"; + Assert.AreEqual(original, parser.Parse(valueFirstJson)); + } + + [Test] + public void Any_CustomPrefix() + { + var registry = TypeRegistry.FromMessages(TestAllTypes.Descriptor); + var message = new TestAllTypes { SingleInt32 = 10 }; + var original = Any.Pack(message, "custom.prefix/middle-part"); + var parser = new JsonParser(new JsonParser.Settings(10, registry)); + string json = "{ \"@type\": \"custom.prefix/middle-part/protobuf_unittest.TestAllTypes\", \"singleInt32\": 10 }"; + Assert.AreEqual(original, parser.Parse(json)); + } + + [Test] + public void Any_UnknownType() + { + string json = "{ \"@type\": \"type.googleapis.com/bogus\" }"; + Assert.Throws(() => Any.Parser.ParseJson(json)); + } + + [Test] + public void Any_NoTypeUrl() + { + string json = "{ \"foo\": \"bar\" }"; + Assert.Throws(() => Any.Parser.ParseJson(json)); + } + + [Test] + public void Any_WellKnownType() + { + var registry = TypeRegistry.FromMessages(Timestamp.Descriptor); + var formatter = new JsonFormatter(new JsonFormatter.Settings(false, registry)); + var timestamp = new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp(); + var original = Any.Pack(timestamp); + var json = formatter.Format(original); // This is tested in JsonFormatterTest + var parser = new JsonParser(new JsonParser.Settings(10, registry)); + Assert.AreEqual(original, parser.Parse(json)); + string valueFirstJson = "{ \"value\": \"1673-06-19T12:34:56Z\", \"@type\": \"type.googleapis.com/google.protobuf.Timestamp\" }"; + Assert.AreEqual(original, parser.Parse(valueFirstJson)); + } + + [Test] + public void Any_Nested() + { + var registry = TypeRegistry.FromMessages(TestWellKnownTypes.Descriptor, TestAllTypes.Descriptor); + var formatter = new JsonFormatter(new JsonFormatter.Settings(false, registry)); + var parser = new JsonParser(new JsonParser.Settings(10, registry)); + var doubleNestedMessage = new TestAllTypes { SingleInt32 = 20 }; + var nestedMessage = Any.Pack(doubleNestedMessage); + var message = new TestWellKnownTypes { AnyField = Any.Pack(nestedMessage) }; + var json = formatter.Format(message); + // Use the descriptor-based parser just for a change. + Assert.AreEqual(message, parser.Parse(json, TestWellKnownTypes.Descriptor)); + } + + [Test] + public void DataAfterObject() + { + string json = "{} 10"; + Assert.Throws(() => TestAllTypes.Parser.ParseJson(json)); + } + + /// + /// JSON equivalent to + /// + [Test] + public void MaliciousRecursion() + { + string data64 = CodedInputStreamTest.MakeRecursiveMessage(64).ToString(); + string data65 = CodedInputStreamTest.MakeRecursiveMessage(65).ToString(); + + var parser64 = new JsonParser(new JsonParser.Settings(64)); + CodedInputStreamTest.AssertMessageDepth(parser64.Parse(data64), 64); + Assert.Throws(() => parser64.Parse(data65)); + + var parser63 = new JsonParser(new JsonParser.Settings(63)); + Assert.Throws(() => parser63.Parse(data64)); + } + + [Test] + [TestCase("AQI")] + [TestCase("_-==")] + public void Bytes_InvalidBase64(string badBase64) + { + string json = "{ \"singleBytes\": \"" + badBase64 + "\" }"; + Assert.Throws(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + [TestCase("\"FOREIGN_BAR\"", ForeignEnum.ForeignBar)] + [TestCase("5", ForeignEnum.ForeignBar)] + [TestCase("100", (ForeignEnum)100)] + public void EnumValid(string value, ForeignEnum expectedValue) + { + string json = "{ \"singleForeignEnum\": " + value + " }"; + var parsed = TestAllTypes.Parser.ParseJson(json); + Assert.AreEqual(new TestAllTypes { SingleForeignEnum = expectedValue }, parsed); + } + + [Test] + [TestCase("\"NOT_A_VALID_VALUE\"")] + [TestCase("5.5")] + public void Enum_Invalid(string value) + { + string json = "{ \"singleForeignEnum\": " + value + " }"; + Assert.Throws(() => TestAllTypes.Parser.ParseJson(json)); + } + + [Test] + public void OneofDuplicate_Invalid() + { + string json = "{ \"oneofString\": \"x\", \"oneofUint32\": 10 }"; + Assert.Throws(() => TestAllTypes.Parser.ParseJson(json)); + } + + /// + /// Various tests use strings which have quotes round them for parsing or as the result + /// of formatting, but without those quotes being specified in the tests (for the sake of readability). + /// This method simply returns the input, wrapped in double quotes. + /// + internal static string WrapInQuotes(string text) + { + return '"' + text + '"'; + } + } +} \ No newline at end of file diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Reflection/FieldAccessTest.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Reflection/FieldAccessTest.cs new file mode 100644 index 0000000..46cb1af --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/Reflection/FieldAccessTest.cs @@ -0,0 +1,218 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using Google.Protobuf.TestProtos; +using NUnit.Framework; +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Google.Protobuf.Reflection +{ + public class FieldAccessTest + { + [Test] + public void GetValue() + { + var message = SampleMessages.CreateFullTestAllTypes(); + var fields = TestAllTypes.Descriptor.Fields; + Assert.AreEqual(message.SingleBool, fields[TestAllTypes.SingleBoolFieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.SingleBytes, fields[TestAllTypes.SingleBytesFieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.SingleDouble, fields[TestAllTypes.SingleDoubleFieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.SingleFixed32, fields[TestAllTypes.SingleFixed32FieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.SingleFixed64, fields[TestAllTypes.SingleFixed64FieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.SingleFloat, fields[TestAllTypes.SingleFloatFieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.SingleForeignEnum, fields[TestAllTypes.SingleForeignEnumFieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.SingleForeignMessage, fields[TestAllTypes.SingleForeignMessageFieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.SingleImportEnum, fields[TestAllTypes.SingleImportEnumFieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.SingleImportMessage, fields[TestAllTypes.SingleImportMessageFieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.SingleInt32, fields[TestAllTypes.SingleInt32FieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.SingleInt64, fields[TestAllTypes.SingleInt64FieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.SingleNestedEnum, fields[TestAllTypes.SingleNestedEnumFieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.SingleNestedMessage, fields[TestAllTypes.SingleNestedMessageFieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.SinglePublicImportMessage, fields[TestAllTypes.SinglePublicImportMessageFieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.SingleSint32, fields[TestAllTypes.SingleSint32FieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.SingleSint64, fields[TestAllTypes.SingleSint64FieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.SingleString, fields[TestAllTypes.SingleStringFieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.SingleSfixed32, fields[TestAllTypes.SingleSfixed32FieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.SingleSfixed64, fields[TestAllTypes.SingleSfixed64FieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.SingleUint32, fields[TestAllTypes.SingleUint32FieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.SingleUint64, fields[TestAllTypes.SingleUint64FieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.OneofBytes, fields[TestAllTypes.OneofBytesFieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.OneofString, fields[TestAllTypes.OneofStringFieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.OneofNestedMessage, fields[TestAllTypes.OneofNestedMessageFieldNumber].Accessor.GetValue(message)); + Assert.AreEqual(message.OneofUint32, fields[TestAllTypes.OneofUint32FieldNumber].Accessor.GetValue(message)); + + // Just one example for repeated fields - they're all just returning the list + var list = (IList) fields[TestAllTypes.RepeatedInt32FieldNumber].Accessor.GetValue(message); + Assert.AreEqual(message.RepeatedInt32, list); + Assert.AreEqual(message.RepeatedInt32[0], list[0]); // Just in case there was any doubt... + + // Just a single map field, for the same reason + var mapMessage = new TestMap { MapStringString = { { "key1", "value1" }, { "key2", "value2" } } }; + fields = TestMap.Descriptor.Fields; + var dictionary = (IDictionary) fields[TestMap.MapStringStringFieldNumber].Accessor.GetValue(mapMessage); + Assert.AreEqual(mapMessage.MapStringString, dictionary); + Assert.AreEqual("value1", dictionary["key1"]); + } + + [Test] + public void Clear() + { + var message = SampleMessages.CreateFullTestAllTypes(); + var fields = TestAllTypes.Descriptor.Fields; + fields[TestAllTypes.SingleBoolFieldNumber].Accessor.Clear(message); + fields[TestAllTypes.SingleInt32FieldNumber].Accessor.Clear(message); + fields[TestAllTypes.SingleStringFieldNumber].Accessor.Clear(message); + fields[TestAllTypes.SingleBytesFieldNumber].Accessor.Clear(message); + fields[TestAllTypes.SingleForeignEnumFieldNumber].Accessor.Clear(message); + fields[TestAllTypes.SingleForeignMessageFieldNumber].Accessor.Clear(message); + fields[TestAllTypes.RepeatedDoubleFieldNumber].Accessor.Clear(message); + + var expected = new TestAllTypes(SampleMessages.CreateFullTestAllTypes()) + { + SingleBool = false, + SingleInt32 = 0, + SingleString = "", + SingleBytes = ByteString.Empty, + SingleForeignEnum = 0, + SingleForeignMessage = null, + }; + expected.RepeatedDouble.Clear(); + + Assert.AreEqual(expected, message); + + // Separately, maps. + var mapMessage = new TestMap { MapStringString = { { "key1", "value1" }, { "key2", "value2" } } }; + fields = TestMap.Descriptor.Fields; + fields[TestMap.MapStringStringFieldNumber].Accessor.Clear(mapMessage); + Assert.AreEqual(0, mapMessage.MapStringString.Count); + } + + [Test] + public void SetValue_SingleFields() + { + // Just a sample (primitives, messages, enums, strings, byte strings) + var message = SampleMessages.CreateFullTestAllTypes(); + var fields = TestAllTypes.Descriptor.Fields; + fields[TestAllTypes.SingleBoolFieldNumber].Accessor.SetValue(message, false); + fields[TestAllTypes.SingleInt32FieldNumber].Accessor.SetValue(message, 500); + fields[TestAllTypes.SingleStringFieldNumber].Accessor.SetValue(message, "It's a string"); + fields[TestAllTypes.SingleBytesFieldNumber].Accessor.SetValue(message, ByteString.CopyFrom(99, 98, 97)); + fields[TestAllTypes.SingleForeignEnumFieldNumber].Accessor.SetValue(message, ForeignEnum.ForeignFoo); + fields[TestAllTypes.SingleForeignMessageFieldNumber].Accessor.SetValue(message, new ForeignMessage { C = 12345 }); + fields[TestAllTypes.SingleDoubleFieldNumber].Accessor.SetValue(message, 20150701.5); + + var expected = new TestAllTypes(SampleMessages.CreateFullTestAllTypes()) + { + SingleBool = false, + SingleInt32 = 500, + SingleString = "It's a string", + SingleBytes = ByteString.CopyFrom(99, 98, 97), + SingleForeignEnum = ForeignEnum.ForeignFoo, + SingleForeignMessage = new ForeignMessage { C = 12345 }, + SingleDouble = 20150701.5 + }; + + Assert.AreEqual(expected, message); + } + + [Test] + public void SetValue_SingleFields_WrongType() + { + IMessage message = SampleMessages.CreateFullTestAllTypes(); + var fields = message.Descriptor.Fields; + Assert.Throws(() => fields[TestAllTypes.SingleBoolFieldNumber].Accessor.SetValue(message, "This isn't a bool")); + } + + [Test] + public void SetValue_MapFields() + { + IMessage message = new TestMap(); + var fields = message.Descriptor.Fields; + Assert.Throws(() => fields[TestMap.MapStringStringFieldNumber].Accessor.SetValue(message, new Dictionary())); + } + + [Test] + public void SetValue_RepeatedFields() + { + IMessage message = SampleMessages.CreateFullTestAllTypes(); + var fields = message.Descriptor.Fields; + Assert.Throws(() => fields[TestAllTypes.RepeatedDoubleFieldNumber].Accessor.SetValue(message, new double[10])); + } + + [Test] + public void GetValue_IncorrectType() + { + IMessage message = SampleMessages.CreateFullTestAllTypes(); + var fields = message.Descriptor.Fields; + Assert.Throws(() => fields[TestAllTypes.SingleBoolFieldNumber].Accessor.GetValue(new TestMap())); + } + + [Test] + public void Oneof() + { + var message = new TestAllTypes(); + var descriptor = TestAllTypes.Descriptor; + Assert.AreEqual(1, descriptor.Oneofs.Count); + var oneof = descriptor.Oneofs[0]; + Assert.AreEqual("oneof_field", oneof.Name); + Assert.IsNull(oneof.Accessor.GetCaseFieldDescriptor(message)); + + message.OneofString = "foo"; + Assert.AreSame(descriptor.Fields[TestAllTypes.OneofStringFieldNumber], oneof.Accessor.GetCaseFieldDescriptor(message)); + + message.OneofUint32 = 10; + Assert.AreSame(descriptor.Fields[TestAllTypes.OneofUint32FieldNumber], oneof.Accessor.GetCaseFieldDescriptor(message)); + + oneof.Accessor.Clear(message); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase); + } + + [Test] + public void FieldDescriptor_ByName() + { + var descriptor = TestAllTypes.Descriptor; + Assert.AreSame( + descriptor.Fields[TestAllTypes.SingleBoolFieldNumber], + descriptor.Fields["single_bool"]); + } + + [Test] + public void FieldDescriptor_NotFound() + { + var descriptor = TestAllTypes.Descriptor; + Assert.Throws(() => descriptor.Fields[999999].ToString()); + Assert.Throws(() => descriptor.Fields["not found"].ToString()); + } + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/DurationTest.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/DurationTest.cs new file mode 100644 index 0000000..141faf8 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/WellKnownTypes/DurationTest.cs @@ -0,0 +1,132 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using NUnit.Framework; +using System; + +namespace Google.Protobuf.WellKnownTypes +{ + public class DurationTest + { + [Test] + public void ToTimeSpan() + { + Assert.AreEqual(TimeSpan.FromSeconds(1), new Duration { Seconds = 1 }.ToTimeSpan()); + Assert.AreEqual(TimeSpan.FromSeconds(-1), new Duration { Seconds = -1 }.ToTimeSpan()); + Assert.AreEqual(TimeSpan.FromMilliseconds(1), new Duration { Nanos = 1000000 }.ToTimeSpan()); + Assert.AreEqual(TimeSpan.FromMilliseconds(-1), new Duration { Nanos = -1000000 }.ToTimeSpan()); + Assert.AreEqual(TimeSpan.FromTicks(1), new Duration { Nanos = 100 }.ToTimeSpan()); + Assert.AreEqual(TimeSpan.FromTicks(-1), new Duration { Nanos = -100 }.ToTimeSpan()); + + // Rounding is towards 0 + Assert.AreEqual(TimeSpan.FromTicks(2), new Duration { Nanos = 250 }.ToTimeSpan()); + Assert.AreEqual(TimeSpan.FromTicks(-2), new Duration { Nanos = -250 }.ToTimeSpan()); + } + + [Test] + public void Addition() + { + Assert.AreEqual(new Duration { Seconds = 2, Nanos = 100000000 }, + new Duration { Seconds = 1, Nanos = 600000000 } + new Duration { Nanos = 500000000 }); + Assert.AreEqual(new Duration { Seconds = -2, Nanos = -100000000 }, + new Duration { Seconds = -1, Nanos = -600000000 } + new Duration { Nanos = -500000000 }); + Assert.AreEqual(new Duration { Seconds = 1, Nanos = 100000000 }, + new Duration { Seconds = 1, Nanos = 600000000 } + new Duration { Nanos = -500000000 }); + + // Non-normalized durations, or non-normalized intermediate results + Assert.AreEqual(new Duration { Seconds = 1 }, + new Duration { Seconds = 1, Nanos = -500000000 } + new Duration { Nanos = 500000000 }); + + Assert.AreEqual(new Duration { Nanos = -900000000 }, + new Duration { Seconds = -1, Nanos = -100000000 } + new Duration { Nanos = 200000000 }); + Assert.AreEqual(new Duration { Nanos = 900000000 }, + new Duration { Seconds = 1, Nanos = 100000000 } + new Duration { Nanos = -200000000 }); + } + + [Test] + public void Subtraction() + { + Assert.AreEqual(new Duration { Seconds = 1, Nanos = 100000000 }, + new Duration { Seconds = 1, Nanos = 600000000 } - new Duration { Nanos = 500000000 }); + Assert.AreEqual(new Duration { Seconds = -1, Nanos = -100000000 }, + new Duration { Seconds = -1, Nanos = -600000000 } - new Duration { Nanos = -500000000 }); + Assert.AreEqual(new Duration { Seconds = 2, Nanos = 100000000 }, + new Duration { Seconds = 1, Nanos = 600000000 } - new Duration { Nanos = -500000000 }); + + // Non-normalized durations + Assert.AreEqual(new Duration(), + new Duration { Seconds = 1, Nanos = -500000000 } - new Duration { Nanos = 500000000 }); + Assert.AreEqual(new Duration { Seconds = 1 }, + new Duration { Nanos = 2000000000 } - new Duration { Nanos = 1000000000 }); + } + + [Test] + public void FromTimeSpan() + { + Assert.AreEqual(new Duration { Seconds = 1 }, Duration.FromTimeSpan(TimeSpan.FromSeconds(1))); + Assert.AreEqual(new Duration { Nanos = Duration.NanosecondsPerTick }, Duration.FromTimeSpan(TimeSpan.FromTicks(1))); + } + + [Test] + [TestCase(0, Duration.MaxNanoseconds + 1)] + [TestCase(0, Duration.MinNanoseconds - 1)] + [TestCase(Duration.MinSeconds - 1, 0)] + [TestCase(Duration.MaxSeconds + 1, 0)] + [TestCase(1, -1)] + [TestCase(-1, 1)] + public void ToTimeSpan_Invalid(long seconds, int nanoseconds) + { + var duration = new Duration { Seconds = seconds, Nanos = nanoseconds }; + Assert.Throws(() => duration.ToTimeSpan()); + } + + [Test] + [TestCase(0, Duration.MaxNanoseconds)] + [TestCase(0, Duration.MinNanoseconds)] + [TestCase(Duration.MinSeconds, Duration.MinNanoseconds)] + [TestCase(Duration.MaxSeconds, Duration.MaxNanoseconds)] + public void ToTimeSpan_Valid(long seconds, int nanoseconds) + { + // Only testing that these values don't throw, unlike their similar tests in ToTimeSpan_Invalid + var duration = new Duration { Seconds = seconds, Nanos = nanoseconds }; + duration.ToTimeSpan(); + } + + [Test] + public void ToString_NonNormalized() + { + // Just a single example should be sufficient... + var duration = new Duration { Seconds = 1, Nanos = -1 }; + Assert.AreEqual("{ \"@warning\": \"Invalid Duration\", \"seconds\": \"1\", \"nanos\": -1 }", duration.ToString()); + } + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/compatibility_tests/v3.0.0/test.sh b/tools/go-generator/cmd/generator/_protobuf/csharp/compatibility_tests/v3.0.0/test.sh new file mode 100755 index 0000000..459c079 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/compatibility_tests/v3.0.0/test.sh @@ -0,0 +1,80 @@ +#!/bin/bash + +function run_test() { + # Generate test proto files. + $1 -Iprotos/src -I../../../src/ --csharp_out=src/Google.Protobuf.Test \ + --csharp_opt=base_namespace=Google.Protobuf \ + protos/src/google/protobuf/unittest_import_proto3.proto \ + protos/src/google/protobuf/unittest_import_public_proto3.proto \ + protos/src/google/protobuf/unittest_well_known_types.proto + + $1 -Iprotos/csharp --csharp_out=src/Google.Protobuf.Test \ + --csharp_opt=base_namespace=UnitTest.Issues \ + protos/csharp/protos/unittest_issues.proto + + $2 -Iprotos/src --csharp_out=src/Google.Protobuf.Test \ + --csharp_opt=base_namespace=Google.Protobuf \ + protos/src/google/protobuf/unittest_proto3.proto \ + protos/src/google/protobuf/map_unittest_proto3.proto + + # Build and test. + dotnet restore src/Google.Protobuf/Google.Protobuf.csproj + dotnet restore src/Google.Protobuf.Test/Google.Protobuf.Test.csproj + dotnet build -c Release src/Google.Protobuf/Google.Protobuf.csproj + dotnet build -c Release src/Google.Protobuf.Test/Google.Protobuf.Test.csproj + dotnet run -c Release -f netcoreapp3.1 -p src/Google.Protobuf.Test/Google.Protobuf.Test.csproj +} + +set -ex + +# Change to the script's directory. +cd $(dirname $0) + +# Version of the tests (i.e., the version of protobuf from where we extracted +# these tests). +TEST_VERSION=3.0.0 + +# The old version of protobuf that we are testing compatibility against. This +# is usually the same as TEST_VERSION (i.e., we use the tests extracted from +# that version to test compatibility of the newest runtime against it), but it +# is also possible to use this same test set to test the compatibility of the +# latest version against other versions. +OLD_VERSION=$1 +OLD_VERSION_PROTOC=https://repo1.maven.org/maven2/com/google/protobuf/protoc/$OLD_VERSION/protoc-$OLD_VERSION-linux-x86_64.exe + +echo "Running compatibility tests with $OLD_VERSION" + +# Check protoc +[ -f ../../../src/protoc ] || { + echo "[ERROR]: Please build protoc first." + exit 1 +} + +# Download old version protoc compiler (for linux). +wget $OLD_VERSION_PROTOC -O old_protoc +chmod +x old_protoc + +# Test source compatibility. In these tests we recompile everything against +# the new runtime (including old version generated code). +# Copy the new runtime and keys. +cp ../../src/Google.Protobuf src/Google.Protobuf -r +cp ../../keys . -r + +# Test A.1: +# proto set 1: use old version +# proto set 2 which may import protos in set 1: use old version +run_test "./old_protoc" "./old_protoc" + +# Test A.2: +# proto set 1: use new version +# proto set 2 which may import protos in set 1: use old version +run_test "../../../src/protoc" "./old_protoc" + +# Test A.3: +# proto set 1: use old version +# proto set 2 which may import protos in set 1: use new version +run_test "./old_protoc" "../../../src/protoc" + +rm old_protoc +rm keys -r +rm src/Google.Protobuf -r diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/install_dotnet_sdk.ps1 b/tools/go-generator/cmd/generator/_protobuf/csharp/install_dotnet_sdk.ps1 new file mode 100755 index 0000000..f9dc0d9 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/install_dotnet_sdk.ps1 @@ -0,0 +1,20 @@ +#!/usr/bin/env powershell +# Install dotnet SDK using the official dotnet-install.ps1 script + +Set-StrictMode -Version 2 +$ErrorActionPreference = 'Stop' + +# avoid "Unknown error on a send" in Invoke-WebRequest +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + +$InstallScriptUrl = 'https://dot.net/v1/dotnet-install.ps1' +$InstallScriptPath = Join-Path "$env:TEMP" 'dotnet-install.ps1' + +# Download install script +Write-Host "Downloading install script: $InstallScriptUrl => $InstallScriptPath" +Invoke-WebRequest -Uri $InstallScriptUrl -OutFile $InstallScriptPath + +# The SDK versions to install should be kept in sync with versions +# installed by kokoro/linux/dockerfile/test/csharp/Dockerfile +&$InstallScriptPath -Version 3.1.415 +&$InstallScriptPath -Version 6.0.100 diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/keys/Google.Protobuf.public.snk b/tools/go-generator/cmd/generator/_protobuf/csharp/keys/Google.Protobuf.public.snk new file mode 100644 index 0000000000000000000000000000000000000000..59cd36985f2278212095c38e73e7dd7cbbd4a4b0 GIT binary patch literal 160 zcmV;R0AK$ABme*efB*oL000060ssI2Bme+XQ$aBR1ONa50096cfDgR4X&6pAg1RvG1+B->uM*RHQNf6a9 zB~yG#L(V_G7u4X&6pAg1RvG1+B->uM*RHQNf6a9B~yG#L(V_G7uqZStuRi2M9!LIZP=+}i|wUqeZ>hr?q&2<1&KKQ))2kGzqBLt(OXDTiOgUMt!8na>sr4Z=nJtlmqPSLaep$; z+)Uj)pJhDCZC0}poiDf%-7rHI=Cf9MgHY5%RV?=Lye27>-5A1GESH=1Kpgb)!HVQf~R+U5pB3a8MnS?C}ar~Dv` zatMU_QprfZHc}IHCQ&TY=CM}A)WV&N*qRkGWKB>kghE(Tw)r!^+n2G~rrIne-4AJu z-4%yI!5%Y^r4|u0T$u1<<*_O^p%0c4$N&CGole5shaLhYZ$i94x~xLn(}bJ`mM-}_ z?_pAsA7C880a)opwV{MukC!z@;dX5RqldFk|7&=1tUX@T81zG_7gvwRx=v!6*o+H-QK*V104k;P&A8iaH`}^!Gw$fXc iTpayck`$i(7QWQW0BxW7Qw1+r=whpQ@0U;o%l~gdEgn+< literal 0 HcmV?d00001 diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/protos/unittest_import_proto3.proto b/tools/go-generator/cmd/generator/_protobuf/csharp/protos/unittest_import_proto3.proto new file mode 100644 index 0000000..2e66682 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/protos/unittest_import_proto3.proto @@ -0,0 +1,56 @@ +// 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. +// +// A proto file which is imported by unittest_proto3.proto to test importing. + +syntax = "proto3"; + +package protobuf_unittest_import; + +option csharp_namespace = "Google.Protobuf.TestProtos"; + +// Test public import +import public "unittest_import_public_proto3.proto"; + +message ImportMessage { + int32 d = 1; +} + +enum ImportEnum { + IMPORT_ENUM_UNSPECIFIED = 0; + IMPORT_FOO = 7; + IMPORT_BAR = 8; + IMPORT_BAZ = 9; +} + diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Benchmarks/BenchmarkDatasetConfig.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Benchmarks/BenchmarkDatasetConfig.cs new file mode 100644 index 0000000..c075419 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Benchmarks/BenchmarkDatasetConfig.cs @@ -0,0 +1,89 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2019 Google Inc. All rights reserved. +// https://github.com/protocolbuffers/protobuf +// +// 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. +#endregion + +using Benchmarks; +using Google.Protobuf.Reflection; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; + +namespace Google.Protobuf.Benchmarks +{ + /// + /// The configuration for a single serialization test, loaded from a dataset. + /// + public class BenchmarkDatasetConfig + { + private static readonly Dictionary parsersByMessageName = + typeof(GoogleMessageBenchmark).Assembly.GetTypes() + .Where(t => typeof(IMessage).IsAssignableFrom(t)) + .ToDictionary( + t => ((MessageDescriptor) t.GetProperty("Descriptor", BindingFlags.Static | BindingFlags.Public).GetValue(null)).FullName, + t => ((MessageParser) t.GetProperty("Parser", BindingFlags.Static | BindingFlags.Public).GetValue(null))); + + public MessageParser Parser { get; } + public List Payloads { get; } + public string Name { get; } + + public BenchmarkDatasetConfig(string resource, string shortName = null) + { + var data = LoadData(resource); + var dataset = BenchmarkDataset.Parser.ParseFrom(data); + + if (!parsersByMessageName.TryGetValue(dataset.MessageName, out var parser)) + { + throw new ArgumentException($"No parser for message {dataset.MessageName} in this assembly"); + } + Parser = parser; + Payloads = new List(dataset.Payload.Select(p => p.ToByteArray())); + Name = shortName ?? dataset.Name; + } + + private static byte[] LoadData(string resource) + { + using (var stream = typeof(GoogleMessageBenchmark).Assembly.GetManifestResourceStream($"Google.Protobuf.Benchmarks.{resource}")) + { + if (stream == null) + { + throw new ArgumentException($"Unable to load embedded resource {resource}"); + } + var copy = new MemoryStream(); + stream.CopyTo(copy); + return copy.ToArray(); + } + } + + public override string ToString() => Name; + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Benchmarks/WriteRawPrimitivesBenchmark.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Benchmarks/WriteRawPrimitivesBenchmark.cs new file mode 100644 index 0000000..66b6b4a --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Benchmarks/WriteRawPrimitivesBenchmark.cs @@ -0,0 +1,519 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2019 Google Inc. All rights reserved. +// https://github.com/protocolbuffers/protobuf +// +// 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. +#endregion + +using BenchmarkDotNet.Attributes; +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.IO; +using System.Buffers; +using System.Text; + +namespace Google.Protobuf.Benchmarks +{ + /// + /// Benchmarks throughput when writing raw primitives. + /// + [MemoryDiagnoser] + public class WriteRawPrimitivesBenchmark + { + // key is the encodedSize of varint values + Dictionary varint32Values; + Dictionary varint64Values; + + double[] doubleValues; + float[] floatValues; + + // key is the encodedSize of string values + Dictionary stringValues; + + // key is the encodedSize of string values + Dictionary nonAsciiStringValues; + + // key is the encodedSize of string values + Dictionary byteStringValues; + + // the buffer to which all the data will be written + byte[] outputBuffer; + + Random random = new Random(417384220); // random but deterministic seed + + public IEnumerable StringEncodedSizes => new[] { 1, 4, 10, 105, 10080 }; + + public IEnumerable NonAsciiStringEncodedSizes => new[] { 4, 10, 105, 10080 }; + + [GlobalSetup] + public void GlobalSetup() + { + outputBuffer = new byte[BytesToWrite]; + + varint32Values = new Dictionary(); + varint64Values = new Dictionary(); + for (int encodedSize = 1; encodedSize <= 10; encodedSize++) + { + if (encodedSize <= 5) + { + varint32Values.Add(encodedSize, CreateRandomVarints32(random, BytesToWrite / encodedSize, encodedSize)); + } + varint64Values.Add(encodedSize, CreateRandomVarints64(random, BytesToWrite / encodedSize, encodedSize)); + } + + doubleValues = CreateRandomDoubles(random, BytesToWrite / sizeof(double)); + floatValues = CreateRandomFloats(random, BytesToWrite / sizeof(float)); + + stringValues = new Dictionary(); + + byteStringValues = new Dictionary(); + foreach(var encodedSize in StringEncodedSizes) + { + stringValues.Add(encodedSize, CreateStrings(BytesToWrite / encodedSize, encodedSize)); + byteStringValues.Add(encodedSize, CreateByteStrings(BytesToWrite / encodedSize, encodedSize)); + } + + nonAsciiStringValues = new Dictionary(); + foreach(var encodedSize in NonAsciiStringEncodedSizes) + { + nonAsciiStringValues.Add(encodedSize, CreateNonAsciiStrings(BytesToWrite / encodedSize, encodedSize)); + } + } + + // Total number of bytes that each benchmark will write. + // Measuring the time taken to write buffer of given size makes it easier to compare parsing speed for different + // types and makes it easy to calculate the througput (in MB/s) + // 10800 bytes is chosen because it is divisible by all possible encoded sizes for all primitive types {1..10} + [Params(10080)] + public int BytesToWrite { get; set; } + + [Benchmark] + [Arguments(1)] + [Arguments(2)] + [Arguments(3)] + [Arguments(4)] + [Arguments(5)] + public void WriteRawVarint32_CodedOutputStream(int encodedSize) + { + var values = varint32Values[encodedSize]; + var cos = new CodedOutputStream(outputBuffer); + for (int i = 0; i < values.Length; i++) + { + cos.WriteRawVarint32(values[i]); + } + cos.Flush(); + cos.CheckNoSpaceLeft(); + } + + [Benchmark] + [Arguments(1)] + [Arguments(2)] + [Arguments(3)] + [Arguments(4)] + [Arguments(5)] + public void WriteRawVarint32_WriteContext(int encodedSize) + { + var values = varint32Values[encodedSize]; + var span = new Span(outputBuffer); + WriteContext.Initialize(ref span, out WriteContext ctx); + for (int i = 0; i < values.Length; i++) + { + ctx.WriteUInt32(values[i]); + } + ctx.Flush(); + ctx.CheckNoSpaceLeft(); + } + + [Benchmark] + [Arguments(1)] + [Arguments(2)] + [Arguments(3)] + [Arguments(4)] + [Arguments(5)] + [Arguments(6)] + [Arguments(7)] + [Arguments(8)] + [Arguments(9)] + [Arguments(10)] + public void WriteRawVarint64_CodedOutputStream(int encodedSize) + { + var values = varint64Values[encodedSize]; + var cos = new CodedOutputStream(outputBuffer); + for (int i = 0; i < values.Length; i++) + { + cos.WriteRawVarint64(values[i]); + } + cos.Flush(); + cos.CheckNoSpaceLeft(); + } + + [Benchmark] + [Arguments(1)] + [Arguments(2)] + [Arguments(3)] + [Arguments(4)] + [Arguments(5)] + [Arguments(6)] + [Arguments(7)] + [Arguments(8)] + [Arguments(9)] + [Arguments(10)] + public void WriteRawVarint64_WriteContext(int encodedSize) + { + var values = varint64Values[encodedSize]; + var span = new Span(outputBuffer); + WriteContext.Initialize(ref span, out WriteContext ctx); + for (int i = 0; i < values.Length; i++) + { + ctx.WriteUInt64(values[i]); + } + ctx.Flush(); + ctx.CheckNoSpaceLeft(); + } + + [Benchmark] + public void WriteFixed32_CodedOutputStream() + { + const int encodedSize = sizeof(uint); + var cos = new CodedOutputStream(outputBuffer); + for (int i = 0; i < BytesToWrite / encodedSize; i++) + { + cos.WriteFixed32(12345); + } + cos.Flush(); + cos.CheckNoSpaceLeft(); + } + + [Benchmark] + public void WriteFixed32_WriteContext() + { + const int encodedSize = sizeof(uint); + var span = new Span(outputBuffer); + WriteContext.Initialize(ref span, out WriteContext ctx); + for (uint i = 0; i < BytesToWrite / encodedSize; i++) + { + ctx.WriteFixed32(12345); + } + ctx.Flush(); + ctx.CheckNoSpaceLeft(); + } + + [Benchmark] + public void WriteFixed64_CodedOutputStream() + { + const int encodedSize = sizeof(ulong); + var cos = new CodedOutputStream(outputBuffer); + for(int i = 0; i < BytesToWrite / encodedSize; i++) + { + cos.WriteFixed64(123456789); + } + cos.Flush(); + cos.CheckNoSpaceLeft(); + } + + [Benchmark] + public void WriteFixed64_WriteContext() + { + const int encodedSize = sizeof(ulong); + var span = new Span(outputBuffer); + WriteContext.Initialize(ref span, out WriteContext ctx); + for (uint i = 0; i < BytesToWrite / encodedSize; i++) + { + ctx.WriteFixed64(123456789); + } + ctx.Flush(); + ctx.CheckNoSpaceLeft(); + } + + [Benchmark] + public void WriteRawTag_OneByte_WriteContext() + { + const int encodedSize = 1; + var span = new Span(outputBuffer); + WriteContext.Initialize(ref span, out WriteContext ctx); + for (uint i = 0; i < BytesToWrite / encodedSize; i++) + { + ctx.WriteRawTag(16); + } + ctx.Flush(); + ctx.CheckNoSpaceLeft(); + } + + [Benchmark] + public void WriteRawTag_TwoBytes_WriteContext() + { + const int encodedSize = 2; + var span = new Span(outputBuffer); + WriteContext.Initialize(ref span, out WriteContext ctx); + for (uint i = 0; i < BytesToWrite / encodedSize; i++) + { + ctx.WriteRawTag(137, 6); + } + ctx.Flush(); + ctx.CheckNoSpaceLeft(); + } + + [Benchmark] + public void WriteRawTag_ThreeBytes_WriteContext() + { + const int encodedSize = 3; + var span = new Span(outputBuffer); + WriteContext.Initialize(ref span, out WriteContext ctx); + for (uint i = 0; i < BytesToWrite / encodedSize; i++) + { + ctx.WriteRawTag(160, 131, 1); + } + ctx.Flush(); + ctx.CheckNoSpaceLeft(); + } + + [Benchmark] + public void Baseline_WriteContext() + { + var span = new Span(outputBuffer); + WriteContext.Initialize(ref span, out WriteContext ctx); + ctx.state.position = outputBuffer.Length; + ctx.Flush(); + ctx.CheckNoSpaceLeft(); + } + + [Benchmark] + public void WriteRawFloat_CodedOutputStream() + { + var cos = new CodedOutputStream(outputBuffer); + foreach (var value in floatValues) + { + cos.WriteFloat(value); + } + cos.Flush(); + cos.CheckNoSpaceLeft(); + } + + [Benchmark] + public void WriteRawFloat_WriteContext() + { + var span = new Span(outputBuffer); + WriteContext.Initialize(ref span, out WriteContext ctx); + foreach (var value in floatValues) + { + ctx.WriteFloat(value); + } + ctx.Flush(); + ctx.CheckNoSpaceLeft(); + } + + [Benchmark] + public void WriteRawDouble_CodedOutputStream() + { + var cos = new CodedOutputStream(outputBuffer); + foreach (var value in doubleValues) + { + cos.WriteDouble(value); + } + cos.Flush(); + cos.CheckNoSpaceLeft(); + } + + [Benchmark] + public void WriteRawDouble_WriteContext() + { + var span = new Span(outputBuffer); + WriteContext.Initialize(ref span, out WriteContext ctx); + foreach (var value in doubleValues) + { + ctx.WriteDouble(value); + } + ctx.Flush(); + ctx.CheckNoSpaceLeft(); + } + + [Benchmark] + [ArgumentsSource(nameof(StringEncodedSizes))] + public void WriteString_CodedOutputStream(int encodedSize) + { + var values = stringValues[encodedSize]; + var cos = new CodedOutputStream(outputBuffer); + foreach (var value in values) + { + cos.WriteString(value); + } + cos.Flush(); + cos.CheckNoSpaceLeft(); + } + + [Benchmark] + [ArgumentsSource(nameof(StringEncodedSizes))] + public void WriteString_WriteContext(int encodedSize) + { + var values = stringValues[encodedSize]; + var span = new Span(outputBuffer); + WriteContext.Initialize(ref span, out WriteContext ctx); + foreach (var value in values) + { + ctx.WriteString(value); + } + ctx.Flush(); + ctx.CheckNoSpaceLeft(); + } + + [Benchmark] + [ArgumentsSource(nameof(NonAsciiStringEncodedSizes))] + public void WriteNonAsciiString_CodedOutputStream(int encodedSize) + { + var values = nonAsciiStringValues[encodedSize]; + var cos = new CodedOutputStream(outputBuffer); + foreach (var value in values) + { + cos.WriteString(value); + } + cos.Flush(); + cos.CheckNoSpaceLeft(); + } + + [Benchmark] + [ArgumentsSource(nameof(NonAsciiStringEncodedSizes))] + public void WriteNonAsciiString_WriteContext(int encodedSize) + { + var values = nonAsciiStringValues[encodedSize]; + var span = new Span(outputBuffer); + WriteContext.Initialize(ref span, out WriteContext ctx); + foreach (var value in values) + { + ctx.WriteString(value); + } + ctx.Flush(); + ctx.CheckNoSpaceLeft(); + } + + [Benchmark] + [ArgumentsSource(nameof(StringEncodedSizes))] + public void WriteBytes_CodedOutputStream(int encodedSize) + { + var values = byteStringValues[encodedSize]; + var cos = new CodedOutputStream(outputBuffer); + foreach (var value in values) + { + cos.WriteBytes(value); + } + cos.Flush(); + cos.CheckNoSpaceLeft(); + } + + [Benchmark] + [ArgumentsSource(nameof(StringEncodedSizes))] + public void WriteBytes_WriteContext(int encodedSize) + { + var values = byteStringValues[encodedSize]; + var span = new Span(outputBuffer); + WriteContext.Initialize(ref span, out WriteContext ctx); + foreach (var value in values) + { + ctx.WriteBytes(value); + } + ctx.Flush(); + ctx.CheckNoSpaceLeft(); + } + + private static uint[] CreateRandomVarints32(Random random, int valueCount, int encodedSize) + { + var result = new uint[valueCount]; + for (int i = 0; i < valueCount; i++) + { + result[i] = (uint) ParseRawPrimitivesBenchmark.RandomUnsignedVarint(random, encodedSize, true); + } + return result; + } + + private static ulong[] CreateRandomVarints64(Random random, int valueCount, int encodedSize) + { + var result = new ulong[valueCount]; + for (int i = 0; i < valueCount; i++) + { + result[i] = ParseRawPrimitivesBenchmark.RandomUnsignedVarint(random, encodedSize, false); + } + return result; + } + + private static float[] CreateRandomFloats(Random random, int valueCount) + { + var result = new float[valueCount]; + for (int i = 0; i < valueCount; i++) + { + result[i] = (float)random.NextDouble(); + } + return result; + } + + private static double[] CreateRandomDoubles(Random random, int valueCount) + { + var result = new double[valueCount]; + for (int i = 0; i < valueCount; i++) + { + result[i] = random.NextDouble(); + } + return result; + } + + private static string[] CreateStrings(int valueCount, int encodedSize) + { + var str = ParseRawPrimitivesBenchmark.CreateStringWithEncodedSize(encodedSize); + + var result = new string[valueCount]; + for (int i = 0; i < valueCount; i++) + { + result[i] = str; + } + return result; + } + + private static string[] CreateNonAsciiStrings(int valueCount, int encodedSize) + { + var str = ParseRawPrimitivesBenchmark.CreateNonAsciiStringWithEncodedSize(encodedSize); + + var result = new string[valueCount]; + for (int i = 0; i < valueCount; i++) + { + result[i] = str; + } + return result; + } + + private static ByteString[] CreateByteStrings(int valueCount, int encodedSize) + { + var str = ParseRawPrimitivesBenchmark.CreateStringWithEncodedSize(encodedSize); + + var result = new ByteString[valueCount]; + for (int i = 0; i < valueCount; i++) + { + result[i] = ByteString.CopyFrom(Encoding.UTF8.GetBytes(str)); + } + return result; + } + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test.TestProtos/MapUnittestProto3.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test.TestProtos/MapUnittestProto3.cs new file mode 100644 index 0000000..4791b73 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test.TestProtos/MapUnittestProto3.cs @@ -0,0 +1,2277 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: map_unittest_proto3.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Google.Protobuf.TestProtos { + + /// Holder for reflection information generated from map_unittest_proto3.proto + public static partial class MapUnittestProto3Reflection { + + #region Descriptor + /// File descriptor for map_unittest_proto3.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static MapUnittestProto3Reflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "ChltYXBfdW5pdHRlc3RfcHJvdG8zLnByb3RvEhJwcm90b2J1Zl91bml0dGVz", + "dDMaFXVuaXR0ZXN0X3Byb3RvMy5wcm90byKpEgoHVGVzdE1hcBJHCg9tYXBf", + "aW50MzJfaW50MzIYASADKAsyLi5wcm90b2J1Zl91bml0dGVzdDMuVGVzdE1h", + "cC5NYXBJbnQzMkludDMyRW50cnkSRwoPbWFwX2ludDY0X2ludDY0GAIgAygL", + "Mi4ucHJvdG9idWZfdW5pdHRlc3QzLlRlc3RNYXAuTWFwSW50NjRJbnQ2NEVu", + "dHJ5EksKEW1hcF91aW50MzJfdWludDMyGAMgAygLMjAucHJvdG9idWZfdW5p", + "dHRlc3QzLlRlc3RNYXAuTWFwVWludDMyVWludDMyRW50cnkSSwoRbWFwX3Vp", + "bnQ2NF91aW50NjQYBCADKAsyMC5wcm90b2J1Zl91bml0dGVzdDMuVGVzdE1h", + "cC5NYXBVaW50NjRVaW50NjRFbnRyeRJLChFtYXBfc2ludDMyX3NpbnQzMhgF", + "IAMoCzIwLnByb3RvYnVmX3VuaXR0ZXN0My5UZXN0TWFwLk1hcFNpbnQzMlNp", + "bnQzMkVudHJ5EksKEW1hcF9zaW50NjRfc2ludDY0GAYgAygLMjAucHJvdG9i", + "dWZfdW5pdHRlc3QzLlRlc3RNYXAuTWFwU2ludDY0U2ludDY0RW50cnkSTwoT", + "bWFwX2ZpeGVkMzJfZml4ZWQzMhgHIAMoCzIyLnByb3RvYnVmX3VuaXR0ZXN0", + "My5UZXN0TWFwLk1hcEZpeGVkMzJGaXhlZDMyRW50cnkSTwoTbWFwX2ZpeGVk", + "NjRfZml4ZWQ2NBgIIAMoCzIyLnByb3RvYnVmX3VuaXR0ZXN0My5UZXN0TWFw", + "Lk1hcEZpeGVkNjRGaXhlZDY0RW50cnkSUwoVbWFwX3NmaXhlZDMyX3NmaXhl", + "ZDMyGAkgAygLMjQucHJvdG9idWZfdW5pdHRlc3QzLlRlc3RNYXAuTWFwU2Zp", + "eGVkMzJTZml4ZWQzMkVudHJ5ElMKFW1hcF9zZml4ZWQ2NF9zZml4ZWQ2NBgK", + "IAMoCzI0LnByb3RvYnVmX3VuaXR0ZXN0My5UZXN0TWFwLk1hcFNmaXhlZDY0", + "U2ZpeGVkNjRFbnRyeRJHCg9tYXBfaW50MzJfZmxvYXQYCyADKAsyLi5wcm90", + "b2J1Zl91bml0dGVzdDMuVGVzdE1hcC5NYXBJbnQzMkZsb2F0RW50cnkSSQoQ", + "bWFwX2ludDMyX2RvdWJsZRgMIAMoCzIvLnByb3RvYnVmX3VuaXR0ZXN0My5U", + "ZXN0TWFwLk1hcEludDMyRG91YmxlRW50cnkSQwoNbWFwX2Jvb2xfYm9vbBgN", + "IAMoCzIsLnByb3RvYnVmX3VuaXR0ZXN0My5UZXN0TWFwLk1hcEJvb2xCb29s", + "RW50cnkSSwoRbWFwX3N0cmluZ19zdHJpbmcYDiADKAsyMC5wcm90b2J1Zl91", + "bml0dGVzdDMuVGVzdE1hcC5NYXBTdHJpbmdTdHJpbmdFbnRyeRJHCg9tYXBf", + "aW50MzJfYnl0ZXMYDyADKAsyLi5wcm90b2J1Zl91bml0dGVzdDMuVGVzdE1h", + "cC5NYXBJbnQzMkJ5dGVzRW50cnkSRQoObWFwX2ludDMyX2VudW0YECADKAsy", + "LS5wcm90b2J1Zl91bml0dGVzdDMuVGVzdE1hcC5NYXBJbnQzMkVudW1FbnRy", + "eRJaChltYXBfaW50MzJfZm9yZWlnbl9tZXNzYWdlGBEgAygLMjcucHJvdG9i", + "dWZfdW5pdHRlc3QzLlRlc3RNYXAuTWFwSW50MzJGb3JlaWduTWVzc2FnZUVu", + "dHJ5GjQKEk1hcEludDMySW50MzJFbnRyeRILCgNrZXkYASABKAUSDQoFdmFs", + "dWUYAiABKAU6AjgBGjQKEk1hcEludDY0SW50NjRFbnRyeRILCgNrZXkYASAB", + "KAMSDQoFdmFsdWUYAiABKAM6AjgBGjYKFE1hcFVpbnQzMlVpbnQzMkVudHJ5", + "EgsKA2tleRgBIAEoDRINCgV2YWx1ZRgCIAEoDToCOAEaNgoUTWFwVWludDY0", + "VWludDY0RW50cnkSCwoDa2V5GAEgASgEEg0KBXZhbHVlGAIgASgEOgI4ARo2", + "ChRNYXBTaW50MzJTaW50MzJFbnRyeRILCgNrZXkYASABKBESDQoFdmFsdWUY", + "AiABKBE6AjgBGjYKFE1hcFNpbnQ2NFNpbnQ2NEVudHJ5EgsKA2tleRgBIAEo", + "EhINCgV2YWx1ZRgCIAEoEjoCOAEaOAoWTWFwRml4ZWQzMkZpeGVkMzJFbnRy", + "eRILCgNrZXkYASABKAcSDQoFdmFsdWUYAiABKAc6AjgBGjgKFk1hcEZpeGVk", + "NjRGaXhlZDY0RW50cnkSCwoDa2V5GAEgASgGEg0KBXZhbHVlGAIgASgGOgI4", + "ARo6ChhNYXBTZml4ZWQzMlNmaXhlZDMyRW50cnkSCwoDa2V5GAEgASgPEg0K", + "BXZhbHVlGAIgASgPOgI4ARo6ChhNYXBTZml4ZWQ2NFNmaXhlZDY0RW50cnkS", + "CwoDa2V5GAEgASgQEg0KBXZhbHVlGAIgASgQOgI4ARo0ChJNYXBJbnQzMkZs", + "b2F0RW50cnkSCwoDa2V5GAEgASgFEg0KBXZhbHVlGAIgASgCOgI4ARo1ChNN", + "YXBJbnQzMkRvdWJsZUVudHJ5EgsKA2tleRgBIAEoBRINCgV2YWx1ZRgCIAEo", + "AToCOAEaMgoQTWFwQm9vbEJvb2xFbnRyeRILCgNrZXkYASABKAgSDQoFdmFs", + "dWUYAiABKAg6AjgBGjYKFE1hcFN0cmluZ1N0cmluZ0VudHJ5EgsKA2tleRgB", + "IAEoCRINCgV2YWx1ZRgCIAEoCToCOAEaNAoSTWFwSW50MzJCeXRlc0VudHJ5", + "EgsKA2tleRgBIAEoBRINCgV2YWx1ZRgCIAEoDDoCOAEaUAoRTWFwSW50MzJF", + "bnVtRW50cnkSCwoDa2V5GAEgASgFEioKBXZhbHVlGAIgASgOMhsucHJvdG9i", + "dWZfdW5pdHRlc3QzLk1hcEVudW06AjgBGmEKG01hcEludDMyRm9yZWlnbk1l", + "c3NhZ2VFbnRyeRILCgNrZXkYASABKAUSMQoFdmFsdWUYAiABKAsyIi5wcm90", + "b2J1Zl91bml0dGVzdDMuRm9yZWlnbk1lc3NhZ2U6AjgBIkIKEVRlc3RNYXBT", + "dWJtZXNzYWdlEi0KCHRlc3RfbWFwGAEgASgLMhsucHJvdG9idWZfdW5pdHRl", + "c3QzLlRlc3RNYXAivgEKDlRlc3RNZXNzYWdlTWFwElIKEW1hcF9pbnQzMl9t", + "ZXNzYWdlGAEgAygLMjcucHJvdG9idWZfdW5pdHRlc3QzLlRlc3RNZXNzYWdl", + "TWFwLk1hcEludDMyTWVzc2FnZUVudHJ5GlgKFE1hcEludDMyTWVzc2FnZUVu", + "dHJ5EgsKA2tleRgBIAEoBRIvCgV2YWx1ZRgCIAEoCzIgLnByb3RvYnVmX3Vu", + "aXR0ZXN0My5UZXN0QWxsVHlwZXM6AjgBIuUBCg9UZXN0U2FtZVR5cGVNYXAS", + "OwoEbWFwMRgBIAMoCzItLnByb3RvYnVmX3VuaXR0ZXN0My5UZXN0U2FtZVR5", + "cGVNYXAuTWFwMUVudHJ5EjsKBG1hcDIYAiADKAsyLS5wcm90b2J1Zl91bml0", + "dGVzdDMuVGVzdFNhbWVUeXBlTWFwLk1hcDJFbnRyeRorCglNYXAxRW50cnkS", + "CwoDa2V5GAEgASgFEg0KBXZhbHVlGAIgASgFOgI4ARorCglNYXAyRW50cnkS", + "CwoDa2V5GAEgASgFEg0KBXZhbHVlGAIgASgFOgI4ASL1EAoMVGVzdEFyZW5h", + "TWFwEkwKD21hcF9pbnQzMl9pbnQzMhgBIAMoCzIzLnByb3RvYnVmX3VuaXR0", + "ZXN0My5UZXN0QXJlbmFNYXAuTWFwSW50MzJJbnQzMkVudHJ5EkwKD21hcF9p", + "bnQ2NF9pbnQ2NBgCIAMoCzIzLnByb3RvYnVmX3VuaXR0ZXN0My5UZXN0QXJl", + "bmFNYXAuTWFwSW50NjRJbnQ2NEVudHJ5ElAKEW1hcF91aW50MzJfdWludDMy", + "GAMgAygLMjUucHJvdG9idWZfdW5pdHRlc3QzLlRlc3RBcmVuYU1hcC5NYXBV", + "aW50MzJVaW50MzJFbnRyeRJQChFtYXBfdWludDY0X3VpbnQ2NBgEIAMoCzI1", + "LnByb3RvYnVmX3VuaXR0ZXN0My5UZXN0QXJlbmFNYXAuTWFwVWludDY0VWlu", + "dDY0RW50cnkSUAoRbWFwX3NpbnQzMl9zaW50MzIYBSADKAsyNS5wcm90b2J1", + "Zl91bml0dGVzdDMuVGVzdEFyZW5hTWFwLk1hcFNpbnQzMlNpbnQzMkVudHJ5", + "ElAKEW1hcF9zaW50NjRfc2ludDY0GAYgAygLMjUucHJvdG9idWZfdW5pdHRl", + "c3QzLlRlc3RBcmVuYU1hcC5NYXBTaW50NjRTaW50NjRFbnRyeRJUChNtYXBf", + "Zml4ZWQzMl9maXhlZDMyGAcgAygLMjcucHJvdG9idWZfdW5pdHRlc3QzLlRl", + "c3RBcmVuYU1hcC5NYXBGaXhlZDMyRml4ZWQzMkVudHJ5ElQKE21hcF9maXhl", + "ZDY0X2ZpeGVkNjQYCCADKAsyNy5wcm90b2J1Zl91bml0dGVzdDMuVGVzdEFy", + "ZW5hTWFwLk1hcEZpeGVkNjRGaXhlZDY0RW50cnkSWAoVbWFwX3NmaXhlZDMy", + "X3NmaXhlZDMyGAkgAygLMjkucHJvdG9idWZfdW5pdHRlc3QzLlRlc3RBcmVu", + "YU1hcC5NYXBTZml4ZWQzMlNmaXhlZDMyRW50cnkSWAoVbWFwX3NmaXhlZDY0", + "X3NmaXhlZDY0GAogAygLMjkucHJvdG9idWZfdW5pdHRlc3QzLlRlc3RBcmVu", + "YU1hcC5NYXBTZml4ZWQ2NFNmaXhlZDY0RW50cnkSTAoPbWFwX2ludDMyX2Zs", + "b2F0GAsgAygLMjMucHJvdG9idWZfdW5pdHRlc3QzLlRlc3RBcmVuYU1hcC5N", + "YXBJbnQzMkZsb2F0RW50cnkSTgoQbWFwX2ludDMyX2RvdWJsZRgMIAMoCzI0", + "LnByb3RvYnVmX3VuaXR0ZXN0My5UZXN0QXJlbmFNYXAuTWFwSW50MzJEb3Vi", + "bGVFbnRyeRJICg1tYXBfYm9vbF9ib29sGA0gAygLMjEucHJvdG9idWZfdW5p", + "dHRlc3QzLlRlc3RBcmVuYU1hcC5NYXBCb29sQm9vbEVudHJ5EkoKDm1hcF9p", + "bnQzMl9lbnVtGA4gAygLMjIucHJvdG9idWZfdW5pdHRlc3QzLlRlc3RBcmVu", + "YU1hcC5NYXBJbnQzMkVudW1FbnRyeRJfChltYXBfaW50MzJfZm9yZWlnbl9t", + "ZXNzYWdlGA8gAygLMjwucHJvdG9idWZfdW5pdHRlc3QzLlRlc3RBcmVuYU1h", + "cC5NYXBJbnQzMkZvcmVpZ25NZXNzYWdlRW50cnkaNAoSTWFwSW50MzJJbnQz", + "MkVudHJ5EgsKA2tleRgBIAEoBRINCgV2YWx1ZRgCIAEoBToCOAEaNAoSTWFw", + "SW50NjRJbnQ2NEVudHJ5EgsKA2tleRgBIAEoAxINCgV2YWx1ZRgCIAEoAzoC", + "OAEaNgoUTWFwVWludDMyVWludDMyRW50cnkSCwoDa2V5GAEgASgNEg0KBXZh", + "bHVlGAIgASgNOgI4ARo2ChRNYXBVaW50NjRVaW50NjRFbnRyeRILCgNrZXkY", + "ASABKAQSDQoFdmFsdWUYAiABKAQ6AjgBGjYKFE1hcFNpbnQzMlNpbnQzMkVu", + "dHJ5EgsKA2tleRgBIAEoERINCgV2YWx1ZRgCIAEoEToCOAEaNgoUTWFwU2lu", + "dDY0U2ludDY0RW50cnkSCwoDa2V5GAEgASgSEg0KBXZhbHVlGAIgASgSOgI4", + "ARo4ChZNYXBGaXhlZDMyRml4ZWQzMkVudHJ5EgsKA2tleRgBIAEoBxINCgV2", + "YWx1ZRgCIAEoBzoCOAEaOAoWTWFwRml4ZWQ2NEZpeGVkNjRFbnRyeRILCgNr", + "ZXkYASABKAYSDQoFdmFsdWUYAiABKAY6AjgBGjoKGE1hcFNmaXhlZDMyU2Zp", + "eGVkMzJFbnRyeRILCgNrZXkYASABKA8SDQoFdmFsdWUYAiABKA86AjgBGjoK", + "GE1hcFNmaXhlZDY0U2ZpeGVkNjRFbnRyeRILCgNrZXkYASABKBASDQoFdmFs", + "dWUYAiABKBA6AjgBGjQKEk1hcEludDMyRmxvYXRFbnRyeRILCgNrZXkYASAB", + "KAUSDQoFdmFsdWUYAiABKAI6AjgBGjUKE01hcEludDMyRG91YmxlRW50cnkS", + "CwoDa2V5GAEgASgFEg0KBXZhbHVlGAIgASgBOgI4ARoyChBNYXBCb29sQm9v", + "bEVudHJ5EgsKA2tleRgBIAEoCBINCgV2YWx1ZRgCIAEoCDoCOAEaUAoRTWFw", + "SW50MzJFbnVtRW50cnkSCwoDa2V5GAEgASgFEioKBXZhbHVlGAIgASgOMhsu", + "cHJvdG9idWZfdW5pdHRlc3QzLk1hcEVudW06AjgBGmEKG01hcEludDMyRm9y", + "ZWlnbk1lc3NhZ2VFbnRyeRILCgNrZXkYASABKAUSMQoFdmFsdWUYAiABKAsy", + "Ii5wcm90b2J1Zl91bml0dGVzdDMuRm9yZWlnbk1lc3NhZ2U6AjgBIuYBCh9N", + "ZXNzYWdlQ29udGFpbmluZ0VudW1DYWxsZWRUeXBlEksKBHR5cGUYASADKAsy", + "PS5wcm90b2J1Zl91bml0dGVzdDMuTWVzc2FnZUNvbnRhaW5pbmdFbnVtQ2Fs", + "bGVkVHlwZS5UeXBlRW50cnkaYAoJVHlwZUVudHJ5EgsKA2tleRgBIAEoBRJC", + "CgV2YWx1ZRgCIAEoCzIzLnByb3RvYnVmX3VuaXR0ZXN0My5NZXNzYWdlQ29u", + "dGFpbmluZ0VudW1DYWxsZWRUeXBlOgI4ASIUCgRUeXBlEgwKCFRZUEVfRk9P", + "EAAingEKH01lc3NhZ2VDb250YWluaW5nTWFwQ2FsbGVkRW50cnkSTQoFZW50", + "cnkYASADKAsyPi5wcm90b2J1Zl91bml0dGVzdDMuTWVzc2FnZUNvbnRhaW5p", + "bmdNYXBDYWxsZWRFbnRyeS5FbnRyeUVudHJ5GiwKCkVudHJ5RW50cnkSCwoD", + "a2V5GAEgASgFEg0KBXZhbHVlGAIgASgFOgI4ASo/CgdNYXBFbnVtEhAKDE1B", + "UF9FTlVNX0ZPTxAAEhAKDE1BUF9FTlVNX0JBUhABEhAKDE1BUF9FTlVNX0JB", + "WhACQh2qAhpHb29nbGUuUHJvdG9idWYuVGVzdFByb3Rvc2IGcHJvdG8z")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { global::Google.Protobuf.TestProtos.UnittestProto3Reflection.Descriptor, }, + new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Google.Protobuf.TestProtos.MapEnum), }, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestMap), global::Google.Protobuf.TestProtos.TestMap.Parser, new[]{ "MapInt32Int32", "MapInt64Int64", "MapUint32Uint32", "MapUint64Uint64", "MapSint32Sint32", "MapSint64Sint64", "MapFixed32Fixed32", "MapFixed64Fixed64", "MapSfixed32Sfixed32", "MapSfixed64Sfixed64", "MapInt32Float", "MapInt32Double", "MapBoolBool", "MapStringString", "MapInt32Bytes", "MapInt32Enum", "MapInt32ForeignMessage" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, }), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestMapSubmessage), global::Google.Protobuf.TestProtos.TestMapSubmessage.Parser, new[]{ "TestMap" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestMessageMap), global::Google.Protobuf.TestProtos.TestMessageMap.Parser, new[]{ "MapInt32Message" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { null, }), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestSameTypeMap), global::Google.Protobuf.TestProtos.TestSameTypeMap.Parser, new[]{ "Map1", "Map2" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { null, null, }), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.TestArenaMap), global::Google.Protobuf.TestProtos.TestArenaMap.Parser, new[]{ "MapInt32Int32", "MapInt64Int64", "MapUint32Uint32", "MapUint64Uint64", "MapSint32Sint32", "MapSint64Sint64", "MapFixed32Fixed32", "MapFixed64Fixed64", "MapSfixed32Sfixed32", "MapSfixed64Sfixed64", "MapInt32Float", "MapInt32Double", "MapBoolBool", "MapInt32Enum", "MapInt32ForeignMessage" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, }), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.MessageContainingEnumCalledType), global::Google.Protobuf.TestProtos.MessageContainingEnumCalledType.Parser, new[]{ "Type" }, null, new[]{ typeof(global::Google.Protobuf.TestProtos.MessageContainingEnumCalledType.Types.Type) }, null, new pbr::GeneratedClrTypeInfo[] { null, }), + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.MessageContainingMapCalledEntry), global::Google.Protobuf.TestProtos.MessageContainingMapCalledEntry.Parser, new[]{ "Entry" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { null, }) + })); + } + #endregion + + } + #region Enums + public enum MapEnum { + [pbr::OriginalName("MAP_ENUM_FOO")] Foo = 0, + [pbr::OriginalName("MAP_ENUM_BAR")] Bar = 1, + [pbr::OriginalName("MAP_ENUM_BAZ")] Baz = 2, + } + + #endregion + + #region Messages + /// + /// Tests maps. + /// + public sealed partial class TestMap : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestMap()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.MapUnittestProto3Reflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestMap() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestMap(TestMap other) : this() { + mapInt32Int32_ = other.mapInt32Int32_.Clone(); + mapInt64Int64_ = other.mapInt64Int64_.Clone(); + mapUint32Uint32_ = other.mapUint32Uint32_.Clone(); + mapUint64Uint64_ = other.mapUint64Uint64_.Clone(); + mapSint32Sint32_ = other.mapSint32Sint32_.Clone(); + mapSint64Sint64_ = other.mapSint64Sint64_.Clone(); + mapFixed32Fixed32_ = other.mapFixed32Fixed32_.Clone(); + mapFixed64Fixed64_ = other.mapFixed64Fixed64_.Clone(); + mapSfixed32Sfixed32_ = other.mapSfixed32Sfixed32_.Clone(); + mapSfixed64Sfixed64_ = other.mapSfixed64Sfixed64_.Clone(); + mapInt32Float_ = other.mapInt32Float_.Clone(); + mapInt32Double_ = other.mapInt32Double_.Clone(); + mapBoolBool_ = other.mapBoolBool_.Clone(); + mapStringString_ = other.mapStringString_.Clone(); + mapInt32Bytes_ = other.mapInt32Bytes_.Clone(); + mapInt32Enum_ = other.mapInt32Enum_.Clone(); + mapInt32ForeignMessage_ = other.mapInt32ForeignMessage_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestMap Clone() { + return new TestMap(this); + } + + /// Field number for the "map_int32_int32" field. + public const int MapInt32Int32FieldNumber = 1; + private static readonly pbc::MapField.Codec _map_mapInt32Int32_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForInt32(8, 0), pb::FieldCodec.ForInt32(16, 0), 10); + private readonly pbc::MapField mapInt32Int32_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapInt32Int32 { + get { return mapInt32Int32_; } + } + + /// Field number for the "map_int64_int64" field. + public const int MapInt64Int64FieldNumber = 2; + private static readonly pbc::MapField.Codec _map_mapInt64Int64_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForInt64(8, 0L), pb::FieldCodec.ForInt64(16, 0L), 18); + private readonly pbc::MapField mapInt64Int64_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapInt64Int64 { + get { return mapInt64Int64_; } + } + + /// Field number for the "map_uint32_uint32" field. + public const int MapUint32Uint32FieldNumber = 3; + private static readonly pbc::MapField.Codec _map_mapUint32Uint32_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForUInt32(8, 0), pb::FieldCodec.ForUInt32(16, 0), 26); + private readonly pbc::MapField mapUint32Uint32_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapUint32Uint32 { + get { return mapUint32Uint32_; } + } + + /// Field number for the "map_uint64_uint64" field. + public const int MapUint64Uint64FieldNumber = 4; + private static readonly pbc::MapField.Codec _map_mapUint64Uint64_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForUInt64(8, 0UL), pb::FieldCodec.ForUInt64(16, 0UL), 34); + private readonly pbc::MapField mapUint64Uint64_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapUint64Uint64 { + get { return mapUint64Uint64_; } + } + + /// Field number for the "map_sint32_sint32" field. + public const int MapSint32Sint32FieldNumber = 5; + private static readonly pbc::MapField.Codec _map_mapSint32Sint32_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForSInt32(8, 0), pb::FieldCodec.ForSInt32(16, 0), 42); + private readonly pbc::MapField mapSint32Sint32_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapSint32Sint32 { + get { return mapSint32Sint32_; } + } + + /// Field number for the "map_sint64_sint64" field. + public const int MapSint64Sint64FieldNumber = 6; + private static readonly pbc::MapField.Codec _map_mapSint64Sint64_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForSInt64(8, 0L), pb::FieldCodec.ForSInt64(16, 0L), 50); + private readonly pbc::MapField mapSint64Sint64_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapSint64Sint64 { + get { return mapSint64Sint64_; } + } + + /// Field number for the "map_fixed32_fixed32" field. + public const int MapFixed32Fixed32FieldNumber = 7; + private static readonly pbc::MapField.Codec _map_mapFixed32Fixed32_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForFixed32(13, 0), pb::FieldCodec.ForFixed32(21, 0), 58); + private readonly pbc::MapField mapFixed32Fixed32_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapFixed32Fixed32 { + get { return mapFixed32Fixed32_; } + } + + /// Field number for the "map_fixed64_fixed64" field. + public const int MapFixed64Fixed64FieldNumber = 8; + private static readonly pbc::MapField.Codec _map_mapFixed64Fixed64_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForFixed64(9, 0UL), pb::FieldCodec.ForFixed64(17, 0UL), 66); + private readonly pbc::MapField mapFixed64Fixed64_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapFixed64Fixed64 { + get { return mapFixed64Fixed64_; } + } + + /// Field number for the "map_sfixed32_sfixed32" field. + public const int MapSfixed32Sfixed32FieldNumber = 9; + private static readonly pbc::MapField.Codec _map_mapSfixed32Sfixed32_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForSFixed32(13, 0), pb::FieldCodec.ForSFixed32(21, 0), 74); + private readonly pbc::MapField mapSfixed32Sfixed32_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapSfixed32Sfixed32 { + get { return mapSfixed32Sfixed32_; } + } + + /// Field number for the "map_sfixed64_sfixed64" field. + public const int MapSfixed64Sfixed64FieldNumber = 10; + private static readonly pbc::MapField.Codec _map_mapSfixed64Sfixed64_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForSFixed64(9, 0L), pb::FieldCodec.ForSFixed64(17, 0L), 82); + private readonly pbc::MapField mapSfixed64Sfixed64_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapSfixed64Sfixed64 { + get { return mapSfixed64Sfixed64_; } + } + + /// Field number for the "map_int32_float" field. + public const int MapInt32FloatFieldNumber = 11; + private static readonly pbc::MapField.Codec _map_mapInt32Float_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForInt32(8, 0), pb::FieldCodec.ForFloat(21, 0F), 90); + private readonly pbc::MapField mapInt32Float_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapInt32Float { + get { return mapInt32Float_; } + } + + /// Field number for the "map_int32_double" field. + public const int MapInt32DoubleFieldNumber = 12; + private static readonly pbc::MapField.Codec _map_mapInt32Double_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForInt32(8, 0), pb::FieldCodec.ForDouble(17, 0D), 98); + private readonly pbc::MapField mapInt32Double_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapInt32Double { + get { return mapInt32Double_; } + } + + /// Field number for the "map_bool_bool" field. + public const int MapBoolBoolFieldNumber = 13; + private static readonly pbc::MapField.Codec _map_mapBoolBool_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForBool(8, false), pb::FieldCodec.ForBool(16, false), 106); + private readonly pbc::MapField mapBoolBool_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapBoolBool { + get { return mapBoolBool_; } + } + + /// Field number for the "map_string_string" field. + public const int MapStringStringFieldNumber = 14; + private static readonly pbc::MapField.Codec _map_mapStringString_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForString(10, ""), pb::FieldCodec.ForString(18, ""), 114); + private readonly pbc::MapField mapStringString_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapStringString { + get { return mapStringString_; } + } + + /// Field number for the "map_int32_bytes" field. + public const int MapInt32BytesFieldNumber = 15; + private static readonly pbc::MapField.Codec _map_mapInt32Bytes_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForInt32(8, 0), pb::FieldCodec.ForBytes(18, pb::ByteString.Empty), 122); + private readonly pbc::MapField mapInt32Bytes_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapInt32Bytes { + get { return mapInt32Bytes_; } + } + + /// Field number for the "map_int32_enum" field. + public const int MapInt32EnumFieldNumber = 16; + private static readonly pbc::MapField.Codec _map_mapInt32Enum_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForInt32(8, 0), pb::FieldCodec.ForEnum(16, x => (int) x, x => (global::Google.Protobuf.TestProtos.MapEnum) x, global::Google.Protobuf.TestProtos.MapEnum.Foo), 130); + private readonly pbc::MapField mapInt32Enum_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapInt32Enum { + get { return mapInt32Enum_; } + } + + /// Field number for the "map_int32_foreign_message" field. + public const int MapInt32ForeignMessageFieldNumber = 17; + private static readonly pbc::MapField.Codec _map_mapInt32ForeignMessage_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForInt32(8, 0), pb::FieldCodec.ForMessage(18, global::Google.Protobuf.TestProtos.ForeignMessage.Parser), 138); + private readonly pbc::MapField mapInt32ForeignMessage_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapInt32ForeignMessage { + get { return mapInt32ForeignMessage_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestMap); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestMap other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!MapInt32Int32.Equals(other.MapInt32Int32)) return false; + if (!MapInt64Int64.Equals(other.MapInt64Int64)) return false; + if (!MapUint32Uint32.Equals(other.MapUint32Uint32)) return false; + if (!MapUint64Uint64.Equals(other.MapUint64Uint64)) return false; + if (!MapSint32Sint32.Equals(other.MapSint32Sint32)) return false; + if (!MapSint64Sint64.Equals(other.MapSint64Sint64)) return false; + if (!MapFixed32Fixed32.Equals(other.MapFixed32Fixed32)) return false; + if (!MapFixed64Fixed64.Equals(other.MapFixed64Fixed64)) return false; + if (!MapSfixed32Sfixed32.Equals(other.MapSfixed32Sfixed32)) return false; + if (!MapSfixed64Sfixed64.Equals(other.MapSfixed64Sfixed64)) return false; + if (!MapInt32Float.Equals(other.MapInt32Float)) return false; + if (!MapInt32Double.Equals(other.MapInt32Double)) return false; + if (!MapBoolBool.Equals(other.MapBoolBool)) return false; + if (!MapStringString.Equals(other.MapStringString)) return false; + if (!MapInt32Bytes.Equals(other.MapInt32Bytes)) return false; + if (!MapInt32Enum.Equals(other.MapInt32Enum)) return false; + if (!MapInt32ForeignMessage.Equals(other.MapInt32ForeignMessage)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + hash ^= MapInt32Int32.GetHashCode(); + hash ^= MapInt64Int64.GetHashCode(); + hash ^= MapUint32Uint32.GetHashCode(); + hash ^= MapUint64Uint64.GetHashCode(); + hash ^= MapSint32Sint32.GetHashCode(); + hash ^= MapSint64Sint64.GetHashCode(); + hash ^= MapFixed32Fixed32.GetHashCode(); + hash ^= MapFixed64Fixed64.GetHashCode(); + hash ^= MapSfixed32Sfixed32.GetHashCode(); + hash ^= MapSfixed64Sfixed64.GetHashCode(); + hash ^= MapInt32Float.GetHashCode(); + hash ^= MapInt32Double.GetHashCode(); + hash ^= MapBoolBool.GetHashCode(); + hash ^= MapStringString.GetHashCode(); + hash ^= MapInt32Bytes.GetHashCode(); + hash ^= MapInt32Enum.GetHashCode(); + hash ^= MapInt32ForeignMessage.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + mapInt32Int32_.WriteTo(output, _map_mapInt32Int32_codec); + mapInt64Int64_.WriteTo(output, _map_mapInt64Int64_codec); + mapUint32Uint32_.WriteTo(output, _map_mapUint32Uint32_codec); + mapUint64Uint64_.WriteTo(output, _map_mapUint64Uint64_codec); + mapSint32Sint32_.WriteTo(output, _map_mapSint32Sint32_codec); + mapSint64Sint64_.WriteTo(output, _map_mapSint64Sint64_codec); + mapFixed32Fixed32_.WriteTo(output, _map_mapFixed32Fixed32_codec); + mapFixed64Fixed64_.WriteTo(output, _map_mapFixed64Fixed64_codec); + mapSfixed32Sfixed32_.WriteTo(output, _map_mapSfixed32Sfixed32_codec); + mapSfixed64Sfixed64_.WriteTo(output, _map_mapSfixed64Sfixed64_codec); + mapInt32Float_.WriteTo(output, _map_mapInt32Float_codec); + mapInt32Double_.WriteTo(output, _map_mapInt32Double_codec); + mapBoolBool_.WriteTo(output, _map_mapBoolBool_codec); + mapStringString_.WriteTo(output, _map_mapStringString_codec); + mapInt32Bytes_.WriteTo(output, _map_mapInt32Bytes_codec); + mapInt32Enum_.WriteTo(output, _map_mapInt32Enum_codec); + mapInt32ForeignMessage_.WriteTo(output, _map_mapInt32ForeignMessage_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + mapInt32Int32_.WriteTo(ref output, _map_mapInt32Int32_codec); + mapInt64Int64_.WriteTo(ref output, _map_mapInt64Int64_codec); + mapUint32Uint32_.WriteTo(ref output, _map_mapUint32Uint32_codec); + mapUint64Uint64_.WriteTo(ref output, _map_mapUint64Uint64_codec); + mapSint32Sint32_.WriteTo(ref output, _map_mapSint32Sint32_codec); + mapSint64Sint64_.WriteTo(ref output, _map_mapSint64Sint64_codec); + mapFixed32Fixed32_.WriteTo(ref output, _map_mapFixed32Fixed32_codec); + mapFixed64Fixed64_.WriteTo(ref output, _map_mapFixed64Fixed64_codec); + mapSfixed32Sfixed32_.WriteTo(ref output, _map_mapSfixed32Sfixed32_codec); + mapSfixed64Sfixed64_.WriteTo(ref output, _map_mapSfixed64Sfixed64_codec); + mapInt32Float_.WriteTo(ref output, _map_mapInt32Float_codec); + mapInt32Double_.WriteTo(ref output, _map_mapInt32Double_codec); + mapBoolBool_.WriteTo(ref output, _map_mapBoolBool_codec); + mapStringString_.WriteTo(ref output, _map_mapStringString_codec); + mapInt32Bytes_.WriteTo(ref output, _map_mapInt32Bytes_codec); + mapInt32Enum_.WriteTo(ref output, _map_mapInt32Enum_codec); + mapInt32ForeignMessage_.WriteTo(ref output, _map_mapInt32ForeignMessage_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + size += mapInt32Int32_.CalculateSize(_map_mapInt32Int32_codec); + size += mapInt64Int64_.CalculateSize(_map_mapInt64Int64_codec); + size += mapUint32Uint32_.CalculateSize(_map_mapUint32Uint32_codec); + size += mapUint64Uint64_.CalculateSize(_map_mapUint64Uint64_codec); + size += mapSint32Sint32_.CalculateSize(_map_mapSint32Sint32_codec); + size += mapSint64Sint64_.CalculateSize(_map_mapSint64Sint64_codec); + size += mapFixed32Fixed32_.CalculateSize(_map_mapFixed32Fixed32_codec); + size += mapFixed64Fixed64_.CalculateSize(_map_mapFixed64Fixed64_codec); + size += mapSfixed32Sfixed32_.CalculateSize(_map_mapSfixed32Sfixed32_codec); + size += mapSfixed64Sfixed64_.CalculateSize(_map_mapSfixed64Sfixed64_codec); + size += mapInt32Float_.CalculateSize(_map_mapInt32Float_codec); + size += mapInt32Double_.CalculateSize(_map_mapInt32Double_codec); + size += mapBoolBool_.CalculateSize(_map_mapBoolBool_codec); + size += mapStringString_.CalculateSize(_map_mapStringString_codec); + size += mapInt32Bytes_.CalculateSize(_map_mapInt32Bytes_codec); + size += mapInt32Enum_.CalculateSize(_map_mapInt32Enum_codec); + size += mapInt32ForeignMessage_.CalculateSize(_map_mapInt32ForeignMessage_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestMap other) { + if (other == null) { + return; + } + mapInt32Int32_.Add(other.mapInt32Int32_); + mapInt64Int64_.Add(other.mapInt64Int64_); + mapUint32Uint32_.Add(other.mapUint32Uint32_); + mapUint64Uint64_.Add(other.mapUint64Uint64_); + mapSint32Sint32_.Add(other.mapSint32Sint32_); + mapSint64Sint64_.Add(other.mapSint64Sint64_); + mapFixed32Fixed32_.Add(other.mapFixed32Fixed32_); + mapFixed64Fixed64_.Add(other.mapFixed64Fixed64_); + mapSfixed32Sfixed32_.Add(other.mapSfixed32Sfixed32_); + mapSfixed64Sfixed64_.Add(other.mapSfixed64Sfixed64_); + mapInt32Float_.Add(other.mapInt32Float_); + mapInt32Double_.Add(other.mapInt32Double_); + mapBoolBool_.Add(other.mapBoolBool_); + mapStringString_.Add(other.mapStringString_); + mapInt32Bytes_.Add(other.mapInt32Bytes_); + mapInt32Enum_.Add(other.mapInt32Enum_); + mapInt32ForeignMessage_.Add(other.mapInt32ForeignMessage_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + mapInt32Int32_.AddEntriesFrom(input, _map_mapInt32Int32_codec); + break; + } + case 18: { + mapInt64Int64_.AddEntriesFrom(input, _map_mapInt64Int64_codec); + break; + } + case 26: { + mapUint32Uint32_.AddEntriesFrom(input, _map_mapUint32Uint32_codec); + break; + } + case 34: { + mapUint64Uint64_.AddEntriesFrom(input, _map_mapUint64Uint64_codec); + break; + } + case 42: { + mapSint32Sint32_.AddEntriesFrom(input, _map_mapSint32Sint32_codec); + break; + } + case 50: { + mapSint64Sint64_.AddEntriesFrom(input, _map_mapSint64Sint64_codec); + break; + } + case 58: { + mapFixed32Fixed32_.AddEntriesFrom(input, _map_mapFixed32Fixed32_codec); + break; + } + case 66: { + mapFixed64Fixed64_.AddEntriesFrom(input, _map_mapFixed64Fixed64_codec); + break; + } + case 74: { + mapSfixed32Sfixed32_.AddEntriesFrom(input, _map_mapSfixed32Sfixed32_codec); + break; + } + case 82: { + mapSfixed64Sfixed64_.AddEntriesFrom(input, _map_mapSfixed64Sfixed64_codec); + break; + } + case 90: { + mapInt32Float_.AddEntriesFrom(input, _map_mapInt32Float_codec); + break; + } + case 98: { + mapInt32Double_.AddEntriesFrom(input, _map_mapInt32Double_codec); + break; + } + case 106: { + mapBoolBool_.AddEntriesFrom(input, _map_mapBoolBool_codec); + break; + } + case 114: { + mapStringString_.AddEntriesFrom(input, _map_mapStringString_codec); + break; + } + case 122: { + mapInt32Bytes_.AddEntriesFrom(input, _map_mapInt32Bytes_codec); + break; + } + case 130: { + mapInt32Enum_.AddEntriesFrom(input, _map_mapInt32Enum_codec); + break; + } + case 138: { + mapInt32ForeignMessage_.AddEntriesFrom(input, _map_mapInt32ForeignMessage_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + mapInt32Int32_.AddEntriesFrom(ref input, _map_mapInt32Int32_codec); + break; + } + case 18: { + mapInt64Int64_.AddEntriesFrom(ref input, _map_mapInt64Int64_codec); + break; + } + case 26: { + mapUint32Uint32_.AddEntriesFrom(ref input, _map_mapUint32Uint32_codec); + break; + } + case 34: { + mapUint64Uint64_.AddEntriesFrom(ref input, _map_mapUint64Uint64_codec); + break; + } + case 42: { + mapSint32Sint32_.AddEntriesFrom(ref input, _map_mapSint32Sint32_codec); + break; + } + case 50: { + mapSint64Sint64_.AddEntriesFrom(ref input, _map_mapSint64Sint64_codec); + break; + } + case 58: { + mapFixed32Fixed32_.AddEntriesFrom(ref input, _map_mapFixed32Fixed32_codec); + break; + } + case 66: { + mapFixed64Fixed64_.AddEntriesFrom(ref input, _map_mapFixed64Fixed64_codec); + break; + } + case 74: { + mapSfixed32Sfixed32_.AddEntriesFrom(ref input, _map_mapSfixed32Sfixed32_codec); + break; + } + case 82: { + mapSfixed64Sfixed64_.AddEntriesFrom(ref input, _map_mapSfixed64Sfixed64_codec); + break; + } + case 90: { + mapInt32Float_.AddEntriesFrom(ref input, _map_mapInt32Float_codec); + break; + } + case 98: { + mapInt32Double_.AddEntriesFrom(ref input, _map_mapInt32Double_codec); + break; + } + case 106: { + mapBoolBool_.AddEntriesFrom(ref input, _map_mapBoolBool_codec); + break; + } + case 114: { + mapStringString_.AddEntriesFrom(ref input, _map_mapStringString_codec); + break; + } + case 122: { + mapInt32Bytes_.AddEntriesFrom(ref input, _map_mapInt32Bytes_codec); + break; + } + case 130: { + mapInt32Enum_.AddEntriesFrom(ref input, _map_mapInt32Enum_codec); + break; + } + case 138: { + mapInt32ForeignMessage_.AddEntriesFrom(ref input, _map_mapInt32ForeignMessage_codec); + break; + } + } + } + } + #endif + + } + + public sealed partial class TestMapSubmessage : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestMapSubmessage()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.MapUnittestProto3Reflection.Descriptor.MessageTypes[1]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestMapSubmessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestMapSubmessage(TestMapSubmessage other) : this() { + testMap_ = other.testMap_ != null ? other.testMap_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestMapSubmessage Clone() { + return new TestMapSubmessage(this); + } + + /// Field number for the "test_map" field. + public const int TestMapFieldNumber = 1; + private global::Google.Protobuf.TestProtos.TestMap testMap_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.TestProtos.TestMap TestMap { + get { return testMap_; } + set { + testMap_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestMapSubmessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestMapSubmessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(TestMap, other.TestMap)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (testMap_ != null) hash ^= TestMap.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (testMap_ != null) { + output.WriteRawTag(10); + output.WriteMessage(TestMap); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (testMap_ != null) { + output.WriteRawTag(10); + output.WriteMessage(TestMap); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (testMap_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(TestMap); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestMapSubmessage other) { + if (other == null) { + return; + } + if (other.testMap_ != null) { + if (testMap_ == null) { + TestMap = new global::Google.Protobuf.TestProtos.TestMap(); + } + TestMap.MergeFrom(other.TestMap); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + if (testMap_ == null) { + TestMap = new global::Google.Protobuf.TestProtos.TestMap(); + } + input.ReadMessage(TestMap); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + if (testMap_ == null) { + TestMap = new global::Google.Protobuf.TestProtos.TestMap(); + } + input.ReadMessage(TestMap); + break; + } + } + } + } + #endif + + } + + public sealed partial class TestMessageMap : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestMessageMap()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.MapUnittestProto3Reflection.Descriptor.MessageTypes[2]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestMessageMap() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestMessageMap(TestMessageMap other) : this() { + mapInt32Message_ = other.mapInt32Message_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestMessageMap Clone() { + return new TestMessageMap(this); + } + + /// Field number for the "map_int32_message" field. + public const int MapInt32MessageFieldNumber = 1; + private static readonly pbc::MapField.Codec _map_mapInt32Message_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForInt32(8, 0), pb::FieldCodec.ForMessage(18, global::Google.Protobuf.TestProtos.TestAllTypes.Parser), 10); + private readonly pbc::MapField mapInt32Message_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapInt32Message { + get { return mapInt32Message_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestMessageMap); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestMessageMap other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!MapInt32Message.Equals(other.MapInt32Message)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + hash ^= MapInt32Message.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + mapInt32Message_.WriteTo(output, _map_mapInt32Message_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + mapInt32Message_.WriteTo(ref output, _map_mapInt32Message_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + size += mapInt32Message_.CalculateSize(_map_mapInt32Message_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestMessageMap other) { + if (other == null) { + return; + } + mapInt32Message_.Add(other.mapInt32Message_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + mapInt32Message_.AddEntriesFrom(input, _map_mapInt32Message_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + mapInt32Message_.AddEntriesFrom(ref input, _map_mapInt32Message_codec); + break; + } + } + } + } + #endif + + } + + /// + /// Two map fields share the same entry default instance. + /// + public sealed partial class TestSameTypeMap : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestSameTypeMap()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.MapUnittestProto3Reflection.Descriptor.MessageTypes[3]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestSameTypeMap() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestSameTypeMap(TestSameTypeMap other) : this() { + map1_ = other.map1_.Clone(); + map2_ = other.map2_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestSameTypeMap Clone() { + return new TestSameTypeMap(this); + } + + /// Field number for the "map1" field. + public const int Map1FieldNumber = 1; + private static readonly pbc::MapField.Codec _map_map1_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForInt32(8, 0), pb::FieldCodec.ForInt32(16, 0), 10); + private readonly pbc::MapField map1_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField Map1 { + get { return map1_; } + } + + /// Field number for the "map2" field. + public const int Map2FieldNumber = 2; + private static readonly pbc::MapField.Codec _map_map2_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForInt32(8, 0), pb::FieldCodec.ForInt32(16, 0), 18); + private readonly pbc::MapField map2_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField Map2 { + get { return map2_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestSameTypeMap); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestSameTypeMap other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!Map1.Equals(other.Map1)) return false; + if (!Map2.Equals(other.Map2)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + hash ^= Map1.GetHashCode(); + hash ^= Map2.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + map1_.WriteTo(output, _map_map1_codec); + map2_.WriteTo(output, _map_map2_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + map1_.WriteTo(ref output, _map_map1_codec); + map2_.WriteTo(ref output, _map_map2_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + size += map1_.CalculateSize(_map_map1_codec); + size += map2_.CalculateSize(_map_map2_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestSameTypeMap other) { + if (other == null) { + return; + } + map1_.Add(other.map1_); + map2_.Add(other.map2_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + map1_.AddEntriesFrom(input, _map_map1_codec); + break; + } + case 18: { + map2_.AddEntriesFrom(input, _map_map2_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + map1_.AddEntriesFrom(ref input, _map_map1_codec); + break; + } + case 18: { + map2_.AddEntriesFrom(ref input, _map_map2_codec); + break; + } + } + } + } + #endif + + } + + public sealed partial class TestArenaMap : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestArenaMap()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.MapUnittestProto3Reflection.Descriptor.MessageTypes[4]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestArenaMap() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestArenaMap(TestArenaMap other) : this() { + mapInt32Int32_ = other.mapInt32Int32_.Clone(); + mapInt64Int64_ = other.mapInt64Int64_.Clone(); + mapUint32Uint32_ = other.mapUint32Uint32_.Clone(); + mapUint64Uint64_ = other.mapUint64Uint64_.Clone(); + mapSint32Sint32_ = other.mapSint32Sint32_.Clone(); + mapSint64Sint64_ = other.mapSint64Sint64_.Clone(); + mapFixed32Fixed32_ = other.mapFixed32Fixed32_.Clone(); + mapFixed64Fixed64_ = other.mapFixed64Fixed64_.Clone(); + mapSfixed32Sfixed32_ = other.mapSfixed32Sfixed32_.Clone(); + mapSfixed64Sfixed64_ = other.mapSfixed64Sfixed64_.Clone(); + mapInt32Float_ = other.mapInt32Float_.Clone(); + mapInt32Double_ = other.mapInt32Double_.Clone(); + mapBoolBool_ = other.mapBoolBool_.Clone(); + mapInt32Enum_ = other.mapInt32Enum_.Clone(); + mapInt32ForeignMessage_ = other.mapInt32ForeignMessage_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestArenaMap Clone() { + return new TestArenaMap(this); + } + + /// Field number for the "map_int32_int32" field. + public const int MapInt32Int32FieldNumber = 1; + private static readonly pbc::MapField.Codec _map_mapInt32Int32_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForInt32(8, 0), pb::FieldCodec.ForInt32(16, 0), 10); + private readonly pbc::MapField mapInt32Int32_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapInt32Int32 { + get { return mapInt32Int32_; } + } + + /// Field number for the "map_int64_int64" field. + public const int MapInt64Int64FieldNumber = 2; + private static readonly pbc::MapField.Codec _map_mapInt64Int64_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForInt64(8, 0L), pb::FieldCodec.ForInt64(16, 0L), 18); + private readonly pbc::MapField mapInt64Int64_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapInt64Int64 { + get { return mapInt64Int64_; } + } + + /// Field number for the "map_uint32_uint32" field. + public const int MapUint32Uint32FieldNumber = 3; + private static readonly pbc::MapField.Codec _map_mapUint32Uint32_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForUInt32(8, 0), pb::FieldCodec.ForUInt32(16, 0), 26); + private readonly pbc::MapField mapUint32Uint32_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapUint32Uint32 { + get { return mapUint32Uint32_; } + } + + /// Field number for the "map_uint64_uint64" field. + public const int MapUint64Uint64FieldNumber = 4; + private static readonly pbc::MapField.Codec _map_mapUint64Uint64_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForUInt64(8, 0UL), pb::FieldCodec.ForUInt64(16, 0UL), 34); + private readonly pbc::MapField mapUint64Uint64_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapUint64Uint64 { + get { return mapUint64Uint64_; } + } + + /// Field number for the "map_sint32_sint32" field. + public const int MapSint32Sint32FieldNumber = 5; + private static readonly pbc::MapField.Codec _map_mapSint32Sint32_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForSInt32(8, 0), pb::FieldCodec.ForSInt32(16, 0), 42); + private readonly pbc::MapField mapSint32Sint32_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapSint32Sint32 { + get { return mapSint32Sint32_; } + } + + /// Field number for the "map_sint64_sint64" field. + public const int MapSint64Sint64FieldNumber = 6; + private static readonly pbc::MapField.Codec _map_mapSint64Sint64_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForSInt64(8, 0L), pb::FieldCodec.ForSInt64(16, 0L), 50); + private readonly pbc::MapField mapSint64Sint64_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapSint64Sint64 { + get { return mapSint64Sint64_; } + } + + /// Field number for the "map_fixed32_fixed32" field. + public const int MapFixed32Fixed32FieldNumber = 7; + private static readonly pbc::MapField.Codec _map_mapFixed32Fixed32_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForFixed32(13, 0), pb::FieldCodec.ForFixed32(21, 0), 58); + private readonly pbc::MapField mapFixed32Fixed32_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapFixed32Fixed32 { + get { return mapFixed32Fixed32_; } + } + + /// Field number for the "map_fixed64_fixed64" field. + public const int MapFixed64Fixed64FieldNumber = 8; + private static readonly pbc::MapField.Codec _map_mapFixed64Fixed64_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForFixed64(9, 0UL), pb::FieldCodec.ForFixed64(17, 0UL), 66); + private readonly pbc::MapField mapFixed64Fixed64_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapFixed64Fixed64 { + get { return mapFixed64Fixed64_; } + } + + /// Field number for the "map_sfixed32_sfixed32" field. + public const int MapSfixed32Sfixed32FieldNumber = 9; + private static readonly pbc::MapField.Codec _map_mapSfixed32Sfixed32_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForSFixed32(13, 0), pb::FieldCodec.ForSFixed32(21, 0), 74); + private readonly pbc::MapField mapSfixed32Sfixed32_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapSfixed32Sfixed32 { + get { return mapSfixed32Sfixed32_; } + } + + /// Field number for the "map_sfixed64_sfixed64" field. + public const int MapSfixed64Sfixed64FieldNumber = 10; + private static readonly pbc::MapField.Codec _map_mapSfixed64Sfixed64_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForSFixed64(9, 0L), pb::FieldCodec.ForSFixed64(17, 0L), 82); + private readonly pbc::MapField mapSfixed64Sfixed64_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapSfixed64Sfixed64 { + get { return mapSfixed64Sfixed64_; } + } + + /// Field number for the "map_int32_float" field. + public const int MapInt32FloatFieldNumber = 11; + private static readonly pbc::MapField.Codec _map_mapInt32Float_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForInt32(8, 0), pb::FieldCodec.ForFloat(21, 0F), 90); + private readonly pbc::MapField mapInt32Float_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapInt32Float { + get { return mapInt32Float_; } + } + + /// Field number for the "map_int32_double" field. + public const int MapInt32DoubleFieldNumber = 12; + private static readonly pbc::MapField.Codec _map_mapInt32Double_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForInt32(8, 0), pb::FieldCodec.ForDouble(17, 0D), 98); + private readonly pbc::MapField mapInt32Double_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapInt32Double { + get { return mapInt32Double_; } + } + + /// Field number for the "map_bool_bool" field. + public const int MapBoolBoolFieldNumber = 13; + private static readonly pbc::MapField.Codec _map_mapBoolBool_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForBool(8, false), pb::FieldCodec.ForBool(16, false), 106); + private readonly pbc::MapField mapBoolBool_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapBoolBool { + get { return mapBoolBool_; } + } + + /// Field number for the "map_int32_enum" field. + public const int MapInt32EnumFieldNumber = 14; + private static readonly pbc::MapField.Codec _map_mapInt32Enum_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForInt32(8, 0), pb::FieldCodec.ForEnum(16, x => (int) x, x => (global::Google.Protobuf.TestProtos.MapEnum) x, global::Google.Protobuf.TestProtos.MapEnum.Foo), 114); + private readonly pbc::MapField mapInt32Enum_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapInt32Enum { + get { return mapInt32Enum_; } + } + + /// Field number for the "map_int32_foreign_message" field. + public const int MapInt32ForeignMessageFieldNumber = 15; + private static readonly pbc::MapField.Codec _map_mapInt32ForeignMessage_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForInt32(8, 0), pb::FieldCodec.ForMessage(18, global::Google.Protobuf.TestProtos.ForeignMessage.Parser), 122); + private readonly pbc::MapField mapInt32ForeignMessage_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField MapInt32ForeignMessage { + get { return mapInt32ForeignMessage_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestArenaMap); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestArenaMap other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!MapInt32Int32.Equals(other.MapInt32Int32)) return false; + if (!MapInt64Int64.Equals(other.MapInt64Int64)) return false; + if (!MapUint32Uint32.Equals(other.MapUint32Uint32)) return false; + if (!MapUint64Uint64.Equals(other.MapUint64Uint64)) return false; + if (!MapSint32Sint32.Equals(other.MapSint32Sint32)) return false; + if (!MapSint64Sint64.Equals(other.MapSint64Sint64)) return false; + if (!MapFixed32Fixed32.Equals(other.MapFixed32Fixed32)) return false; + if (!MapFixed64Fixed64.Equals(other.MapFixed64Fixed64)) return false; + if (!MapSfixed32Sfixed32.Equals(other.MapSfixed32Sfixed32)) return false; + if (!MapSfixed64Sfixed64.Equals(other.MapSfixed64Sfixed64)) return false; + if (!MapInt32Float.Equals(other.MapInt32Float)) return false; + if (!MapInt32Double.Equals(other.MapInt32Double)) return false; + if (!MapBoolBool.Equals(other.MapBoolBool)) return false; + if (!MapInt32Enum.Equals(other.MapInt32Enum)) return false; + if (!MapInt32ForeignMessage.Equals(other.MapInt32ForeignMessage)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + hash ^= MapInt32Int32.GetHashCode(); + hash ^= MapInt64Int64.GetHashCode(); + hash ^= MapUint32Uint32.GetHashCode(); + hash ^= MapUint64Uint64.GetHashCode(); + hash ^= MapSint32Sint32.GetHashCode(); + hash ^= MapSint64Sint64.GetHashCode(); + hash ^= MapFixed32Fixed32.GetHashCode(); + hash ^= MapFixed64Fixed64.GetHashCode(); + hash ^= MapSfixed32Sfixed32.GetHashCode(); + hash ^= MapSfixed64Sfixed64.GetHashCode(); + hash ^= MapInt32Float.GetHashCode(); + hash ^= MapInt32Double.GetHashCode(); + hash ^= MapBoolBool.GetHashCode(); + hash ^= MapInt32Enum.GetHashCode(); + hash ^= MapInt32ForeignMessage.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + mapInt32Int32_.WriteTo(output, _map_mapInt32Int32_codec); + mapInt64Int64_.WriteTo(output, _map_mapInt64Int64_codec); + mapUint32Uint32_.WriteTo(output, _map_mapUint32Uint32_codec); + mapUint64Uint64_.WriteTo(output, _map_mapUint64Uint64_codec); + mapSint32Sint32_.WriteTo(output, _map_mapSint32Sint32_codec); + mapSint64Sint64_.WriteTo(output, _map_mapSint64Sint64_codec); + mapFixed32Fixed32_.WriteTo(output, _map_mapFixed32Fixed32_codec); + mapFixed64Fixed64_.WriteTo(output, _map_mapFixed64Fixed64_codec); + mapSfixed32Sfixed32_.WriteTo(output, _map_mapSfixed32Sfixed32_codec); + mapSfixed64Sfixed64_.WriteTo(output, _map_mapSfixed64Sfixed64_codec); + mapInt32Float_.WriteTo(output, _map_mapInt32Float_codec); + mapInt32Double_.WriteTo(output, _map_mapInt32Double_codec); + mapBoolBool_.WriteTo(output, _map_mapBoolBool_codec); + mapInt32Enum_.WriteTo(output, _map_mapInt32Enum_codec); + mapInt32ForeignMessage_.WriteTo(output, _map_mapInt32ForeignMessage_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + mapInt32Int32_.WriteTo(ref output, _map_mapInt32Int32_codec); + mapInt64Int64_.WriteTo(ref output, _map_mapInt64Int64_codec); + mapUint32Uint32_.WriteTo(ref output, _map_mapUint32Uint32_codec); + mapUint64Uint64_.WriteTo(ref output, _map_mapUint64Uint64_codec); + mapSint32Sint32_.WriteTo(ref output, _map_mapSint32Sint32_codec); + mapSint64Sint64_.WriteTo(ref output, _map_mapSint64Sint64_codec); + mapFixed32Fixed32_.WriteTo(ref output, _map_mapFixed32Fixed32_codec); + mapFixed64Fixed64_.WriteTo(ref output, _map_mapFixed64Fixed64_codec); + mapSfixed32Sfixed32_.WriteTo(ref output, _map_mapSfixed32Sfixed32_codec); + mapSfixed64Sfixed64_.WriteTo(ref output, _map_mapSfixed64Sfixed64_codec); + mapInt32Float_.WriteTo(ref output, _map_mapInt32Float_codec); + mapInt32Double_.WriteTo(ref output, _map_mapInt32Double_codec); + mapBoolBool_.WriteTo(ref output, _map_mapBoolBool_codec); + mapInt32Enum_.WriteTo(ref output, _map_mapInt32Enum_codec); + mapInt32ForeignMessage_.WriteTo(ref output, _map_mapInt32ForeignMessage_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + size += mapInt32Int32_.CalculateSize(_map_mapInt32Int32_codec); + size += mapInt64Int64_.CalculateSize(_map_mapInt64Int64_codec); + size += mapUint32Uint32_.CalculateSize(_map_mapUint32Uint32_codec); + size += mapUint64Uint64_.CalculateSize(_map_mapUint64Uint64_codec); + size += mapSint32Sint32_.CalculateSize(_map_mapSint32Sint32_codec); + size += mapSint64Sint64_.CalculateSize(_map_mapSint64Sint64_codec); + size += mapFixed32Fixed32_.CalculateSize(_map_mapFixed32Fixed32_codec); + size += mapFixed64Fixed64_.CalculateSize(_map_mapFixed64Fixed64_codec); + size += mapSfixed32Sfixed32_.CalculateSize(_map_mapSfixed32Sfixed32_codec); + size += mapSfixed64Sfixed64_.CalculateSize(_map_mapSfixed64Sfixed64_codec); + size += mapInt32Float_.CalculateSize(_map_mapInt32Float_codec); + size += mapInt32Double_.CalculateSize(_map_mapInt32Double_codec); + size += mapBoolBool_.CalculateSize(_map_mapBoolBool_codec); + size += mapInt32Enum_.CalculateSize(_map_mapInt32Enum_codec); + size += mapInt32ForeignMessage_.CalculateSize(_map_mapInt32ForeignMessage_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestArenaMap other) { + if (other == null) { + return; + } + mapInt32Int32_.Add(other.mapInt32Int32_); + mapInt64Int64_.Add(other.mapInt64Int64_); + mapUint32Uint32_.Add(other.mapUint32Uint32_); + mapUint64Uint64_.Add(other.mapUint64Uint64_); + mapSint32Sint32_.Add(other.mapSint32Sint32_); + mapSint64Sint64_.Add(other.mapSint64Sint64_); + mapFixed32Fixed32_.Add(other.mapFixed32Fixed32_); + mapFixed64Fixed64_.Add(other.mapFixed64Fixed64_); + mapSfixed32Sfixed32_.Add(other.mapSfixed32Sfixed32_); + mapSfixed64Sfixed64_.Add(other.mapSfixed64Sfixed64_); + mapInt32Float_.Add(other.mapInt32Float_); + mapInt32Double_.Add(other.mapInt32Double_); + mapBoolBool_.Add(other.mapBoolBool_); + mapInt32Enum_.Add(other.mapInt32Enum_); + mapInt32ForeignMessage_.Add(other.mapInt32ForeignMessage_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + mapInt32Int32_.AddEntriesFrom(input, _map_mapInt32Int32_codec); + break; + } + case 18: { + mapInt64Int64_.AddEntriesFrom(input, _map_mapInt64Int64_codec); + break; + } + case 26: { + mapUint32Uint32_.AddEntriesFrom(input, _map_mapUint32Uint32_codec); + break; + } + case 34: { + mapUint64Uint64_.AddEntriesFrom(input, _map_mapUint64Uint64_codec); + break; + } + case 42: { + mapSint32Sint32_.AddEntriesFrom(input, _map_mapSint32Sint32_codec); + break; + } + case 50: { + mapSint64Sint64_.AddEntriesFrom(input, _map_mapSint64Sint64_codec); + break; + } + case 58: { + mapFixed32Fixed32_.AddEntriesFrom(input, _map_mapFixed32Fixed32_codec); + break; + } + case 66: { + mapFixed64Fixed64_.AddEntriesFrom(input, _map_mapFixed64Fixed64_codec); + break; + } + case 74: { + mapSfixed32Sfixed32_.AddEntriesFrom(input, _map_mapSfixed32Sfixed32_codec); + break; + } + case 82: { + mapSfixed64Sfixed64_.AddEntriesFrom(input, _map_mapSfixed64Sfixed64_codec); + break; + } + case 90: { + mapInt32Float_.AddEntriesFrom(input, _map_mapInt32Float_codec); + break; + } + case 98: { + mapInt32Double_.AddEntriesFrom(input, _map_mapInt32Double_codec); + break; + } + case 106: { + mapBoolBool_.AddEntriesFrom(input, _map_mapBoolBool_codec); + break; + } + case 114: { + mapInt32Enum_.AddEntriesFrom(input, _map_mapInt32Enum_codec); + break; + } + case 122: { + mapInt32ForeignMessage_.AddEntriesFrom(input, _map_mapInt32ForeignMessage_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + mapInt32Int32_.AddEntriesFrom(ref input, _map_mapInt32Int32_codec); + break; + } + case 18: { + mapInt64Int64_.AddEntriesFrom(ref input, _map_mapInt64Int64_codec); + break; + } + case 26: { + mapUint32Uint32_.AddEntriesFrom(ref input, _map_mapUint32Uint32_codec); + break; + } + case 34: { + mapUint64Uint64_.AddEntriesFrom(ref input, _map_mapUint64Uint64_codec); + break; + } + case 42: { + mapSint32Sint32_.AddEntriesFrom(ref input, _map_mapSint32Sint32_codec); + break; + } + case 50: { + mapSint64Sint64_.AddEntriesFrom(ref input, _map_mapSint64Sint64_codec); + break; + } + case 58: { + mapFixed32Fixed32_.AddEntriesFrom(ref input, _map_mapFixed32Fixed32_codec); + break; + } + case 66: { + mapFixed64Fixed64_.AddEntriesFrom(ref input, _map_mapFixed64Fixed64_codec); + break; + } + case 74: { + mapSfixed32Sfixed32_.AddEntriesFrom(ref input, _map_mapSfixed32Sfixed32_codec); + break; + } + case 82: { + mapSfixed64Sfixed64_.AddEntriesFrom(ref input, _map_mapSfixed64Sfixed64_codec); + break; + } + case 90: { + mapInt32Float_.AddEntriesFrom(ref input, _map_mapInt32Float_codec); + break; + } + case 98: { + mapInt32Double_.AddEntriesFrom(ref input, _map_mapInt32Double_codec); + break; + } + case 106: { + mapBoolBool_.AddEntriesFrom(ref input, _map_mapBoolBool_codec); + break; + } + case 114: { + mapInt32Enum_.AddEntriesFrom(ref input, _map_mapInt32Enum_codec); + break; + } + case 122: { + mapInt32ForeignMessage_.AddEntriesFrom(ref input, _map_mapInt32ForeignMessage_codec); + break; + } + } + } + } + #endif + + } + + /// + /// Previously, message containing enum called Type cannot be used as value of + /// map field. + /// + public sealed partial class MessageContainingEnumCalledType : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new MessageContainingEnumCalledType()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.MapUnittestProto3Reflection.Descriptor.MessageTypes[5]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MessageContainingEnumCalledType() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MessageContainingEnumCalledType(MessageContainingEnumCalledType other) : this() { + type_ = other.type_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MessageContainingEnumCalledType Clone() { + return new MessageContainingEnumCalledType(this); + } + + /// Field number for the "type" field. + public const int TypeFieldNumber = 1; + private static readonly pbc::MapField.Codec _map_type_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForInt32(8, 0), pb::FieldCodec.ForMessage(18, global::Google.Protobuf.TestProtos.MessageContainingEnumCalledType.Parser), 10); + private readonly pbc::MapField type_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField Type { + get { return type_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as MessageContainingEnumCalledType); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(MessageContainingEnumCalledType other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!Type.Equals(other.Type)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + hash ^= Type.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + type_.WriteTo(output, _map_type_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + type_.WriteTo(ref output, _map_type_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + size += type_.CalculateSize(_map_type_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(MessageContainingEnumCalledType other) { + if (other == null) { + return; + } + type_.Add(other.type_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + type_.AddEntriesFrom(input, _map_type_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + type_.AddEntriesFrom(ref input, _map_type_codec); + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the MessageContainingEnumCalledType message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public enum Type { + [pbr::OriginalName("TYPE_FOO")] Foo = 0, + } + + } + #endregion + + } + + /// + /// Previously, message cannot contain map field called "entry". + /// + public sealed partial class MessageContainingMapCalledEntry : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new MessageContainingMapCalledEntry()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.MapUnittestProto3Reflection.Descriptor.MessageTypes[6]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MessageContainingMapCalledEntry() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MessageContainingMapCalledEntry(MessageContainingMapCalledEntry other) : this() { + entry_ = other.entry_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MessageContainingMapCalledEntry Clone() { + return new MessageContainingMapCalledEntry(this); + } + + /// Field number for the "entry" field. + public const int EntryFieldNumber = 1; + private static readonly pbc::MapField.Codec _map_entry_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForInt32(8, 0), pb::FieldCodec.ForInt32(16, 0), 10); + private readonly pbc::MapField entry_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::MapField Entry { + get { return entry_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as MessageContainingMapCalledEntry); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(MessageContainingMapCalledEntry other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!Entry.Equals(other.Entry)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + hash ^= Entry.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + entry_.WriteTo(output, _map_entry_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + entry_.WriteTo(ref output, _map_entry_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + size += entry_.CalculateSize(_map_entry_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(MessageContainingMapCalledEntry other) { + if (other == null) { + return; + } + entry_.Add(other.entry_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + entry_.AddEntriesFrom(input, _map_entry_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + entry_.AddEntriesFrom(ref input, _map_entry_codec); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test.TestProtos/OldExtensions1.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test.TestProtos/OldExtensions1.cs new file mode 100644 index 0000000..3824f4c --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test.TestProtos/OldExtensions1.cs @@ -0,0 +1,148 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: old_extensions1.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Google.Protobuf.TestProtos.OldGenerator { + + /// Holder for reflection information generated from old_extensions1.proto + public static partial class OldExtensions1Reflection { + + #region Descriptor + /// File descriptor for old_extensions1.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static OldExtensions1Reflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "ChVvbGRfZXh0ZW5zaW9uczEucHJvdG8aFW9sZF9leHRlbnNpb25zMi5wcm90", + "byINCgtUZXN0TWVzc2FnZUIqqgInR29vZ2xlLlByb3RvYnVmLlRlc3RQcm90", + "b3MuT2xkR2VuZXJhdG9yYgZwcm90bzM=")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { global::Google.Protobuf.TestProtos.OldGenerator.OldExtensions2Reflection.Descriptor, }, + new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.TestProtos.OldGenerator.TestMessage), global::Google.Protobuf.TestProtos.OldGenerator.TestMessage.Parser, null, null, null, null) + })); + } + #endregion + + } + #region Messages + /// + /// We don't use this message other than to get its descriptor. + /// + public sealed partial class TestMessage : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestMessage()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.TestProtos.OldGenerator.OldExtensions1Reflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public TestMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public TestMessage(TestMessage other) : this() { + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public TestMessage Clone() { + return new TestMessage(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as TestMessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(TestMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(TestMessage other) { + if (other == null) { + return; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + } + } + } + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssue6936C.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssue6936C.cs new file mode 100644 index 0000000..d7789b8 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssue6936C.cs @@ -0,0 +1,244 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: unittest_issue6936_c.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace UnitTest.Issues.TestProtos { + + /// Holder for reflection information generated from unittest_issue6936_c.proto + public static partial class UnittestIssue6936CReflection { + + #region Descriptor + /// File descriptor for unittest_issue6936_c.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static UnittestIssue6936CReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Chp1bml0dGVzdF9pc3N1ZTY5MzZfYy5wcm90bxIPdW5pdHRlc3RfaXNzdWVz", + "Ghp1bml0dGVzdF9pc3N1ZTY5MzZfYS5wcm90bxoadW5pdHRlc3RfaXNzdWU2", + "OTM2X2IucHJvdG8iMQoDQmFyEiEKA2ZvbxgBIAEoCzIULnVuaXR0ZXN0X2lz", + "c3Vlcy5Gb286B4K1GANiYXJCHaoCGlVuaXRUZXN0Lklzc3Vlcy5UZXN0UHJv", + "dG9zYgZwcm90bzM=")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { global::UnitTest.Issues.TestProtos.UnittestIssue6936AReflection.Descriptor, global::UnitTest.Issues.TestProtos.UnittestIssue6936BReflection.Descriptor, }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.Bar), global::UnitTest.Issues.TestProtos.Bar.Parser, new[]{ "Foo" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + public sealed partial class Bar : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Bar()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::UnitTest.Issues.TestProtos.UnittestIssue6936CReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Bar() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Bar(Bar other) : this() { + foo_ = other.foo_ != null ? other.foo_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Bar Clone() { + return new Bar(this); + } + + /// Field number for the "foo" field. + public const int FooFieldNumber = 1; + private global::UnitTest.Issues.TestProtos.Foo foo_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::UnitTest.Issues.TestProtos.Foo Foo { + get { return foo_; } + set { + foo_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as Bar); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(Bar other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(Foo, other.Foo)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (foo_ != null) hash ^= Foo.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (foo_ != null) { + output.WriteRawTag(10); + output.WriteMessage(Foo); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (foo_ != null) { + output.WriteRawTag(10); + output.WriteMessage(Foo); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (foo_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Foo); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(Bar other) { + if (other == null) { + return; + } + if (other.foo_ != null) { + if (foo_ == null) { + Foo = new global::UnitTest.Issues.TestProtos.Foo(); + } + Foo.MergeFrom(other.Foo); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + if (foo_ == null) { + Foo = new global::UnitTest.Issues.TestProtos.Foo(); + } + input.ReadMessage(Foo); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + if (foo_ == null) { + Foo = new global::UnitTest.Issues.TestProtos.Foo(); + } + input.ReadMessage(Foo); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssues.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssues.cs new file mode 100644 index 0000000..ec4c07b --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssues.cs @@ -0,0 +1,3832 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: unittest_issues.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace UnitTest.Issues.TestProtos { + + /// Holder for reflection information generated from unittest_issues.proto + public static partial class UnittestIssuesReflection { + + #region Descriptor + /// File descriptor for unittest_issues.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static UnittestIssuesReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "ChV1bml0dGVzdF9pc3N1ZXMucHJvdG8SD3VuaXR0ZXN0X2lzc3VlcxocZ29v", + "Z2xlL3Byb3RvYnVmL3N0cnVjdC5wcm90byInCghJc3N1ZTMwNxobCgpOZXN0", + "ZWRPbmNlGg0KC05lc3RlZFR3aWNlIrABChNOZWdhdGl2ZUVudW1NZXNzYWdl", + "EiwKBXZhbHVlGAEgASgOMh0udW5pdHRlc3RfaXNzdWVzLk5lZ2F0aXZlRW51", + "bRIxCgZ2YWx1ZXMYAiADKA4yHS51bml0dGVzdF9pc3N1ZXMuTmVnYXRpdmVF", + "bnVtQgIQABI4Cg1wYWNrZWRfdmFsdWVzGAMgAygOMh0udW5pdHRlc3RfaXNz", + "dWVzLk5lZ2F0aXZlRW51bUICEAEiEQoPRGVwcmVjYXRlZENoaWxkIrkCChdE", + "ZXByZWNhdGVkRmllbGRzTWVzc2FnZRIaCg5QcmltaXRpdmVWYWx1ZRgBIAEo", + "BUICGAESGgoOUHJpbWl0aXZlQXJyYXkYAiADKAVCAhgBEjoKDE1lc3NhZ2VW", + "YWx1ZRgDIAEoCzIgLnVuaXR0ZXN0X2lzc3Vlcy5EZXByZWNhdGVkQ2hpbGRC", + "AhgBEjoKDE1lc3NhZ2VBcnJheRgEIAMoCzIgLnVuaXR0ZXN0X2lzc3Vlcy5E", + "ZXByZWNhdGVkQ2hpbGRCAhgBEjYKCUVudW1WYWx1ZRgFIAEoDjIfLnVuaXR0", + "ZXN0X2lzc3Vlcy5EZXByZWNhdGVkRW51bUICGAESNgoJRW51bUFycmF5GAYg", + "AygOMh8udW5pdHRlc3RfaXNzdWVzLkRlcHJlY2F0ZWRFbnVtQgIYASIZCglJ", + "dGVtRmllbGQSDAoEaXRlbRgBIAEoBSJECg1SZXNlcnZlZE5hbWVzEg0KBXR5", + "cGVzGAEgASgFEhIKCmRlc2NyaXB0b3IYAiABKAUaEAoOU29tZU5lc3RlZFR5", + "cGUioAEKFVRlc3RKc29uRmllbGRPcmRlcmluZxITCgtwbGFpbl9pbnQzMhgE", + "IAEoBRITCglvMV9zdHJpbmcYAiABKAlIABISCghvMV9pbnQzMhgFIAEoBUgA", + "EhQKDHBsYWluX3N0cmluZxgBIAEoCRISCghvMl9pbnQzMhgGIAEoBUgBEhMK", + "CW8yX3N0cmluZxgDIAEoCUgBQgQKAm8xQgQKAm8yIksKDFRlc3RKc29uTmFt", + "ZRIMCgRuYW1lGAEgASgJEhkKC2Rlc2NyaXB0aW9uGAIgASgJUgRkZXNjEhIK", + "BGd1aWQYAyABKAlSBGV4aWQifwoMT25lb2ZNZXJnaW5nEg4KBHRleHQYASAB", + "KAlIABI2CgZuZXN0ZWQYAiABKAsyJC51bml0dGVzdF9pc3N1ZXMuT25lb2ZN", + "ZXJnaW5nLk5lc3RlZEgAGh4KBk5lc3RlZBIJCgF4GAEgASgFEgkKAXkYAiAB", + "KAVCBwoFdmFsdWUiawoWTnVsbFZhbHVlT3V0c2lkZVN0cnVjdBIWCgxzdHJp", + "bmdfdmFsdWUYASABKAlIABIwCgpudWxsX3ZhbHVlGAIgASgOMhouZ29vZ2xl", + "LnByb3RvYnVmLk51bGxWYWx1ZUgAQgcKBXZhbHVlIkUKE051bGxWYWx1ZU5v", + "dEluT25lb2YSLgoKbnVsbF92YWx1ZRgCIAEoDjIaLmdvb2dsZS5wcm90b2J1", + "Zi5OdWxsVmFsdWUiYAoXTWl4ZWRSZWd1bGFyQW5kT3B0aW9uYWwSFQoNcmVn", + "dWxhcl9maWVsZBgBIAEoCRIbCg5vcHRpb25hbF9maWVsZBgCIAEoCUgAiAEB", + "QhEKD19vcHRpb25hbF9maWVsZCpVCgxOZWdhdGl2ZUVudW0SFgoSTkVHQVRJ", + "VkVfRU5VTV9aRVJPEAASFgoJRml2ZUJlbG93EPv//////////wESFQoITWlu", + "dXNPbmUQ////////////ASouCg5EZXByZWNhdGVkRW51bRITCg9ERVBSRUNB", + "VEVEX1pFUk8QABIHCgNvbmUQAUIdqgIaVW5pdFRlc3QuSXNzdWVzLlRlc3RQ", + "cm90b3NiBnByb3RvMw==")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.StructReflection.Descriptor, }, + new pbr::GeneratedClrTypeInfo(new[] {typeof(global::UnitTest.Issues.TestProtos.NegativeEnum), typeof(global::UnitTest.Issues.TestProtos.DeprecatedEnum), }, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.Issue307), global::UnitTest.Issues.TestProtos.Issue307.Parser, null, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.Issue307.Types.NestedOnce), global::UnitTest.Issues.TestProtos.Issue307.Types.NestedOnce.Parser, null, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.Issue307.Types.NestedOnce.Types.NestedTwice), global::UnitTest.Issues.TestProtos.Issue307.Types.NestedOnce.Types.NestedTwice.Parser, null, null, null, null, null)})}), + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.NegativeEnumMessage), global::UnitTest.Issues.TestProtos.NegativeEnumMessage.Parser, new[]{ "Value", "Values", "PackedValues" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.DeprecatedChild), global::UnitTest.Issues.TestProtos.DeprecatedChild.Parser, null, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.DeprecatedFieldsMessage), global::UnitTest.Issues.TestProtos.DeprecatedFieldsMessage.Parser, new[]{ "PrimitiveValue", "PrimitiveArray", "MessageValue", "MessageArray", "EnumValue", "EnumArray" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.ItemField), global::UnitTest.Issues.TestProtos.ItemField.Parser, new[]{ "Item" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.ReservedNames), global::UnitTest.Issues.TestProtos.ReservedNames.Parser, new[]{ "Types_", "Descriptor_" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.ReservedNames.Types.SomeNestedType), global::UnitTest.Issues.TestProtos.ReservedNames.Types.SomeNestedType.Parser, null, null, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.TestJsonFieldOrdering), global::UnitTest.Issues.TestProtos.TestJsonFieldOrdering.Parser, new[]{ "PlainInt32", "O1String", "O1Int32", "PlainString", "O2Int32", "O2String" }, new[]{ "O1", "O2" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.TestJsonName), global::UnitTest.Issues.TestProtos.TestJsonName.Parser, new[]{ "Name", "Description", "Guid" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.OneofMerging), global::UnitTest.Issues.TestProtos.OneofMerging.Parser, new[]{ "Text", "Nested" }, new[]{ "Value" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.OneofMerging.Types.Nested), global::UnitTest.Issues.TestProtos.OneofMerging.Types.Nested.Parser, new[]{ "X", "Y" }, null, null, null, null)}), + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.NullValueOutsideStruct), global::UnitTest.Issues.TestProtos.NullValueOutsideStruct.Parser, new[]{ "StringValue", "NullValue" }, new[]{ "Value" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.NullValueNotInOneof), global::UnitTest.Issues.TestProtos.NullValueNotInOneof.Parser, new[]{ "NullValue" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.MixedRegularAndOptional), global::UnitTest.Issues.TestProtos.MixedRegularAndOptional.Parser, new[]{ "RegularField", "OptionalField" }, new[]{ "OptionalField" }, null, null, null) + })); + } + #endregion + + } + #region Enums + public enum NegativeEnum { + [pbr::OriginalName("NEGATIVE_ENUM_ZERO")] Zero = 0, + [pbr::OriginalName("FiveBelow")] FiveBelow = -5, + [pbr::OriginalName("MinusOne")] MinusOne = -1, + } + + public enum DeprecatedEnum { + [pbr::OriginalName("DEPRECATED_ZERO")] DeprecatedZero = 0, + [pbr::OriginalName("one")] One = 1, + } + + #endregion + + #region Messages + /// + /// Issue 307: when generating doubly-nested types, any references + /// should be of the form A.Types.B.Types.C. + /// + public sealed partial class Issue307 : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Issue307()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Issue307() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Issue307(Issue307 other) : this() { + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Issue307 Clone() { + return new Issue307(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as Issue307); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(Issue307 other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(Issue307 other) { + if (other == null) { + return; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the Issue307 message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public sealed partial class NestedOnce : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new NestedOnce()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::UnitTest.Issues.TestProtos.Issue307.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedOnce() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedOnce(NestedOnce other) : this() { + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedOnce Clone() { + return new NestedOnce(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as NestedOnce); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(NestedOnce other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(NestedOnce other) { + if (other == null) { + return; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the NestedOnce message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public sealed partial class NestedTwice : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new NestedTwice()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::UnitTest.Issues.TestProtos.Issue307.Types.NestedOnce.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedTwice() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedTwice(NestedTwice other) : this() { + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NestedTwice Clone() { + return new NestedTwice(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as NestedTwice); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(NestedTwice other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(NestedTwice other) { + if (other == null) { + return; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + } + } + } + #endif + + } + + } + #endregion + + } + + } + #endregion + + } + + public sealed partial class NegativeEnumMessage : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new NegativeEnumMessage()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[1]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NegativeEnumMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NegativeEnumMessage(NegativeEnumMessage other) : this() { + value_ = other.value_; + values_ = other.values_.Clone(); + packedValues_ = other.packedValues_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NegativeEnumMessage Clone() { + return new NegativeEnumMessage(this); + } + + /// Field number for the "value" field. + public const int ValueFieldNumber = 1; + private global::UnitTest.Issues.TestProtos.NegativeEnum value_ = global::UnitTest.Issues.TestProtos.NegativeEnum.Zero; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::UnitTest.Issues.TestProtos.NegativeEnum Value { + get { return value_; } + set { + value_ = value; + } + } + + /// Field number for the "values" field. + public const int ValuesFieldNumber = 2; + private static readonly pb::FieldCodec _repeated_values_codec + = pb::FieldCodec.ForEnum(16, x => (int) x, x => (global::UnitTest.Issues.TestProtos.NegativeEnum) x); + private readonly pbc::RepeatedField values_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField Values { + get { return values_; } + } + + /// Field number for the "packed_values" field. + public const int PackedValuesFieldNumber = 3; + private static readonly pb::FieldCodec _repeated_packedValues_codec + = pb::FieldCodec.ForEnum(26, x => (int) x, x => (global::UnitTest.Issues.TestProtos.NegativeEnum) x); + private readonly pbc::RepeatedField packedValues_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField PackedValues { + get { return packedValues_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as NegativeEnumMessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(NegativeEnumMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Value != other.Value) return false; + if(!values_.Equals(other.values_)) return false; + if(!packedValues_.Equals(other.packedValues_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (Value != global::UnitTest.Issues.TestProtos.NegativeEnum.Zero) hash ^= Value.GetHashCode(); + hash ^= values_.GetHashCode(); + hash ^= packedValues_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Value != global::UnitTest.Issues.TestProtos.NegativeEnum.Zero) { + output.WriteRawTag(8); + output.WriteEnum((int) Value); + } + values_.WriteTo(output, _repeated_values_codec); + packedValues_.WriteTo(output, _repeated_packedValues_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Value != global::UnitTest.Issues.TestProtos.NegativeEnum.Zero) { + output.WriteRawTag(8); + output.WriteEnum((int) Value); + } + values_.WriteTo(ref output, _repeated_values_codec); + packedValues_.WriteTo(ref output, _repeated_packedValues_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (Value != global::UnitTest.Issues.TestProtos.NegativeEnum.Zero) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Value); + } + size += values_.CalculateSize(_repeated_values_codec); + size += packedValues_.CalculateSize(_repeated_packedValues_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(NegativeEnumMessage other) { + if (other == null) { + return; + } + if (other.Value != global::UnitTest.Issues.TestProtos.NegativeEnum.Zero) { + Value = other.Value; + } + values_.Add(other.values_); + packedValues_.Add(other.packedValues_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Value = (global::UnitTest.Issues.TestProtos.NegativeEnum) input.ReadEnum(); + break; + } + case 18: + case 16: { + values_.AddEntriesFrom(input, _repeated_values_codec); + break; + } + case 26: + case 24: { + packedValues_.AddEntriesFrom(input, _repeated_packedValues_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Value = (global::UnitTest.Issues.TestProtos.NegativeEnum) input.ReadEnum(); + break; + } + case 18: + case 16: { + values_.AddEntriesFrom(ref input, _repeated_values_codec); + break; + } + case 26: + case 24: { + packedValues_.AddEntriesFrom(ref input, _repeated_packedValues_codec); + break; + } + } + } + } + #endif + + } + + public sealed partial class DeprecatedChild : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new DeprecatedChild()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[2]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public DeprecatedChild() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public DeprecatedChild(DeprecatedChild other) : this() { + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public DeprecatedChild Clone() { + return new DeprecatedChild(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as DeprecatedChild); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(DeprecatedChild other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(DeprecatedChild other) { + if (other == null) { + return; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + } + } + } + #endif + + } + + public sealed partial class DeprecatedFieldsMessage : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new DeprecatedFieldsMessage()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[3]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public DeprecatedFieldsMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public DeprecatedFieldsMessage(DeprecatedFieldsMessage other) : this() { + primitiveValue_ = other.primitiveValue_; + primitiveArray_ = other.primitiveArray_.Clone(); + messageValue_ = other.messageValue_ != null ? other.messageValue_.Clone() : null; + messageArray_ = other.messageArray_.Clone(); + enumValue_ = other.enumValue_; + enumArray_ = other.enumArray_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public DeprecatedFieldsMessage Clone() { + return new DeprecatedFieldsMessage(this); + } + + /// Field number for the "PrimitiveValue" field. + public const int PrimitiveValueFieldNumber = 1; + private int primitiveValue_; + [global::System.ObsoleteAttribute] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int PrimitiveValue { + get { return primitiveValue_; } + set { + primitiveValue_ = value; + } + } + + /// Field number for the "PrimitiveArray" field. + public const int PrimitiveArrayFieldNumber = 2; + private static readonly pb::FieldCodec _repeated_primitiveArray_codec + = pb::FieldCodec.ForInt32(18); + private readonly pbc::RepeatedField primitiveArray_ = new pbc::RepeatedField(); + [global::System.ObsoleteAttribute] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField PrimitiveArray { + get { return primitiveArray_; } + } + + /// Field number for the "MessageValue" field. + public const int MessageValueFieldNumber = 3; + private global::UnitTest.Issues.TestProtos.DeprecatedChild messageValue_; + [global::System.ObsoleteAttribute] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::UnitTest.Issues.TestProtos.DeprecatedChild MessageValue { + get { return messageValue_; } + set { + messageValue_ = value; + } + } + + /// Field number for the "MessageArray" field. + public const int MessageArrayFieldNumber = 4; + private static readonly pb::FieldCodec _repeated_messageArray_codec + = pb::FieldCodec.ForMessage(34, global::UnitTest.Issues.TestProtos.DeprecatedChild.Parser); + private readonly pbc::RepeatedField messageArray_ = new pbc::RepeatedField(); + [global::System.ObsoleteAttribute] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField MessageArray { + get { return messageArray_; } + } + + /// Field number for the "EnumValue" field. + public const int EnumValueFieldNumber = 5; + private global::UnitTest.Issues.TestProtos.DeprecatedEnum enumValue_ = global::UnitTest.Issues.TestProtos.DeprecatedEnum.DeprecatedZero; + [global::System.ObsoleteAttribute] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::UnitTest.Issues.TestProtos.DeprecatedEnum EnumValue { + get { return enumValue_; } + set { + enumValue_ = value; + } + } + + /// Field number for the "EnumArray" field. + public const int EnumArrayFieldNumber = 6; + private static readonly pb::FieldCodec _repeated_enumArray_codec + = pb::FieldCodec.ForEnum(50, x => (int) x, x => (global::UnitTest.Issues.TestProtos.DeprecatedEnum) x); + private readonly pbc::RepeatedField enumArray_ = new pbc::RepeatedField(); + [global::System.ObsoleteAttribute] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public pbc::RepeatedField EnumArray { + get { return enumArray_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as DeprecatedFieldsMessage); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(DeprecatedFieldsMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (PrimitiveValue != other.PrimitiveValue) return false; + if(!primitiveArray_.Equals(other.primitiveArray_)) return false; + if (!object.Equals(MessageValue, other.MessageValue)) return false; + if(!messageArray_.Equals(other.messageArray_)) return false; + if (EnumValue != other.EnumValue) return false; + if(!enumArray_.Equals(other.enumArray_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (PrimitiveValue != 0) hash ^= PrimitiveValue.GetHashCode(); + hash ^= primitiveArray_.GetHashCode(); + if (messageValue_ != null) hash ^= MessageValue.GetHashCode(); + hash ^= messageArray_.GetHashCode(); + if (EnumValue != global::UnitTest.Issues.TestProtos.DeprecatedEnum.DeprecatedZero) hash ^= EnumValue.GetHashCode(); + hash ^= enumArray_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (PrimitiveValue != 0) { + output.WriteRawTag(8); + output.WriteInt32(PrimitiveValue); + } + primitiveArray_.WriteTo(output, _repeated_primitiveArray_codec); + if (messageValue_ != null) { + output.WriteRawTag(26); + output.WriteMessage(MessageValue); + } + messageArray_.WriteTo(output, _repeated_messageArray_codec); + if (EnumValue != global::UnitTest.Issues.TestProtos.DeprecatedEnum.DeprecatedZero) { + output.WriteRawTag(40); + output.WriteEnum((int) EnumValue); + } + enumArray_.WriteTo(output, _repeated_enumArray_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (PrimitiveValue != 0) { + output.WriteRawTag(8); + output.WriteInt32(PrimitiveValue); + } + primitiveArray_.WriteTo(ref output, _repeated_primitiveArray_codec); + if (messageValue_ != null) { + output.WriteRawTag(26); + output.WriteMessage(MessageValue); + } + messageArray_.WriteTo(ref output, _repeated_messageArray_codec); + if (EnumValue != global::UnitTest.Issues.TestProtos.DeprecatedEnum.DeprecatedZero) { + output.WriteRawTag(40); + output.WriteEnum((int) EnumValue); + } + enumArray_.WriteTo(ref output, _repeated_enumArray_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (PrimitiveValue != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(PrimitiveValue); + } + size += primitiveArray_.CalculateSize(_repeated_primitiveArray_codec); + if (messageValue_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(MessageValue); + } + size += messageArray_.CalculateSize(_repeated_messageArray_codec); + if (EnumValue != global::UnitTest.Issues.TestProtos.DeprecatedEnum.DeprecatedZero) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) EnumValue); + } + size += enumArray_.CalculateSize(_repeated_enumArray_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(DeprecatedFieldsMessage other) { + if (other == null) { + return; + } + if (other.PrimitiveValue != 0) { + PrimitiveValue = other.PrimitiveValue; + } + primitiveArray_.Add(other.primitiveArray_); + if (other.messageValue_ != null) { + if (messageValue_ == null) { + MessageValue = new global::UnitTest.Issues.TestProtos.DeprecatedChild(); + } + MessageValue.MergeFrom(other.MessageValue); + } + messageArray_.Add(other.messageArray_); + if (other.EnumValue != global::UnitTest.Issues.TestProtos.DeprecatedEnum.DeprecatedZero) { + EnumValue = other.EnumValue; + } + enumArray_.Add(other.enumArray_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + PrimitiveValue = input.ReadInt32(); + break; + } + case 18: + case 16: { + primitiveArray_.AddEntriesFrom(input, _repeated_primitiveArray_codec); + break; + } + case 26: { + if (messageValue_ == null) { + MessageValue = new global::UnitTest.Issues.TestProtos.DeprecatedChild(); + } + input.ReadMessage(MessageValue); + break; + } + case 34: { + messageArray_.AddEntriesFrom(input, _repeated_messageArray_codec); + break; + } + case 40: { + EnumValue = (global::UnitTest.Issues.TestProtos.DeprecatedEnum) input.ReadEnum(); + break; + } + case 50: + case 48: { + enumArray_.AddEntriesFrom(input, _repeated_enumArray_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + PrimitiveValue = input.ReadInt32(); + break; + } + case 18: + case 16: { + primitiveArray_.AddEntriesFrom(ref input, _repeated_primitiveArray_codec); + break; + } + case 26: { + if (messageValue_ == null) { + MessageValue = new global::UnitTest.Issues.TestProtos.DeprecatedChild(); + } + input.ReadMessage(MessageValue); + break; + } + case 34: { + messageArray_.AddEntriesFrom(ref input, _repeated_messageArray_codec); + break; + } + case 40: { + EnumValue = (global::UnitTest.Issues.TestProtos.DeprecatedEnum) input.ReadEnum(); + break; + } + case 50: + case 48: { + enumArray_.AddEntriesFrom(ref input, _repeated_enumArray_codec); + break; + } + } + } + } + #endif + + } + + /// + /// Issue 45: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=45 + /// + public sealed partial class ItemField : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ItemField()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[4]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ItemField() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ItemField(ItemField other) : this() { + item_ = other.item_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ItemField Clone() { + return new ItemField(this); + } + + /// Field number for the "item" field. + public const int ItemFieldNumber = 1; + private int item_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Item { + get { return item_; } + set { + item_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as ItemField); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(ItemField other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Item != other.Item) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (Item != 0) hash ^= Item.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Item != 0) { + output.WriteRawTag(8); + output.WriteInt32(Item); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Item != 0) { + output.WriteRawTag(8); + output.WriteInt32(Item); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (Item != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Item); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(ItemField other) { + if (other == null) { + return; + } + if (other.Item != 0) { + Item = other.Item; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Item = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Item = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + public sealed partial class ReservedNames : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ReservedNames()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[5]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ReservedNames() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ReservedNames(ReservedNames other) : this() { + types_ = other.types_; + descriptor_ = other.descriptor_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ReservedNames Clone() { + return new ReservedNames(this); + } + + /// Field number for the "types" field. + public const int Types_FieldNumber = 1; + private int types_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Types_ { + get { return types_; } + set { + types_ = value; + } + } + + /// Field number for the "descriptor" field. + public const int Descriptor_FieldNumber = 2; + private int descriptor_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Descriptor_ { + get { return descriptor_; } + set { + descriptor_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as ReservedNames); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(ReservedNames other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Types_ != other.Types_) return false; + if (Descriptor_ != other.Descriptor_) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (Types_ != 0) hash ^= Types_.GetHashCode(); + if (Descriptor_ != 0) hash ^= Descriptor_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Types_ != 0) { + output.WriteRawTag(8); + output.WriteInt32(Types_); + } + if (Descriptor_ != 0) { + output.WriteRawTag(16); + output.WriteInt32(Descriptor_); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Types_ != 0) { + output.WriteRawTag(8); + output.WriteInt32(Types_); + } + if (Descriptor_ != 0) { + output.WriteRawTag(16); + output.WriteInt32(Descriptor_); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (Types_ != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Types_); + } + if (Descriptor_ != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Descriptor_); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(ReservedNames other) { + if (other == null) { + return; + } + if (other.Types_ != 0) { + Types_ = other.Types_; + } + if (other.Descriptor_ != 0) { + Descriptor_ = other.Descriptor_; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Types_ = input.ReadInt32(); + break; + } + case 16: { + Descriptor_ = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Types_ = input.ReadInt32(); + break; + } + case 16: { + Descriptor_ = input.ReadInt32(); + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the ReservedNames message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + /// + /// Force a nested type called Types + /// + public sealed partial class SomeNestedType : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new SomeNestedType()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::UnitTest.Issues.TestProtos.ReservedNames.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public SomeNestedType() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public SomeNestedType(SomeNestedType other) : this() { + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public SomeNestedType Clone() { + return new SomeNestedType(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as SomeNestedType); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(SomeNestedType other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(SomeNestedType other) { + if (other == null) { + return; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + } + } + } + #endif + + } + + } + #endregion + + } + + /// + /// These fields are deliberately not declared in numeric + /// order, and the oneof fields aren't contiguous either. + /// This allows for reasonably robust tests of JSON output + /// ordering. + /// TestFieldOrderings in unittest_proto3.proto is similar, + /// but doesn't include oneofs. + /// TODO: Consider adding oneofs to TestFieldOrderings, although + /// that will require fixing other tests in multiple platforms. + /// Alternatively, consider just adding this to + /// unittest_proto3.proto if multiple platforms want it. + /// + public sealed partial class TestJsonFieldOrdering : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestJsonFieldOrdering()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[6]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestJsonFieldOrdering() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestJsonFieldOrdering(TestJsonFieldOrdering other) : this() { + plainInt32_ = other.plainInt32_; + plainString_ = other.plainString_; + switch (other.O1Case) { + case O1OneofCase.O1String: + O1String = other.O1String; + break; + case O1OneofCase.O1Int32: + O1Int32 = other.O1Int32; + break; + } + + switch (other.O2Case) { + case O2OneofCase.O2Int32: + O2Int32 = other.O2Int32; + break; + case O2OneofCase.O2String: + O2String = other.O2String; + break; + } + + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestJsonFieldOrdering Clone() { + return new TestJsonFieldOrdering(this); + } + + /// Field number for the "plain_int32" field. + public const int PlainInt32FieldNumber = 4; + private int plainInt32_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int PlainInt32 { + get { return plainInt32_; } + set { + plainInt32_ = value; + } + } + + /// Field number for the "o1_string" field. + public const int O1StringFieldNumber = 2; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string O1String { + get { return o1Case_ == O1OneofCase.O1String ? (string) o1_ : ""; } + set { + o1_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + o1Case_ = O1OneofCase.O1String; + } + } + + /// Field number for the "o1_int32" field. + public const int O1Int32FieldNumber = 5; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int O1Int32 { + get { return o1Case_ == O1OneofCase.O1Int32 ? (int) o1_ : 0; } + set { + o1_ = value; + o1Case_ = O1OneofCase.O1Int32; + } + } + + /// Field number for the "plain_string" field. + public const int PlainStringFieldNumber = 1; + private string plainString_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string PlainString { + get { return plainString_; } + set { + plainString_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "o2_int32" field. + public const int O2Int32FieldNumber = 6; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int O2Int32 { + get { return o2Case_ == O2OneofCase.O2Int32 ? (int) o2_ : 0; } + set { + o2_ = value; + o2Case_ = O2OneofCase.O2Int32; + } + } + + /// Field number for the "o2_string" field. + public const int O2StringFieldNumber = 3; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string O2String { + get { return o2Case_ == O2OneofCase.O2String ? (string) o2_ : ""; } + set { + o2_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + o2Case_ = O2OneofCase.O2String; + } + } + + private object o1_; + /// Enum of possible cases for the "o1" oneof. + public enum O1OneofCase { + None = 0, + O1String = 2, + O1Int32 = 5, + } + private O1OneofCase o1Case_ = O1OneofCase.None; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public O1OneofCase O1Case { + get { return o1Case_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearO1() { + o1Case_ = O1OneofCase.None; + o1_ = null; + } + + private object o2_; + /// Enum of possible cases for the "o2" oneof. + public enum O2OneofCase { + None = 0, + O2Int32 = 6, + O2String = 3, + } + private O2OneofCase o2Case_ = O2OneofCase.None; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public O2OneofCase O2Case { + get { return o2Case_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearO2() { + o2Case_ = O2OneofCase.None; + o2_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestJsonFieldOrdering); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestJsonFieldOrdering other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (PlainInt32 != other.PlainInt32) return false; + if (O1String != other.O1String) return false; + if (O1Int32 != other.O1Int32) return false; + if (PlainString != other.PlainString) return false; + if (O2Int32 != other.O2Int32) return false; + if (O2String != other.O2String) return false; + if (O1Case != other.O1Case) return false; + if (O2Case != other.O2Case) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (PlainInt32 != 0) hash ^= PlainInt32.GetHashCode(); + if (o1Case_ == O1OneofCase.O1String) hash ^= O1String.GetHashCode(); + if (o1Case_ == O1OneofCase.O1Int32) hash ^= O1Int32.GetHashCode(); + if (PlainString.Length != 0) hash ^= PlainString.GetHashCode(); + if (o2Case_ == O2OneofCase.O2Int32) hash ^= O2Int32.GetHashCode(); + if (o2Case_ == O2OneofCase.O2String) hash ^= O2String.GetHashCode(); + hash ^= (int) o1Case_; + hash ^= (int) o2Case_; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (PlainString.Length != 0) { + output.WriteRawTag(10); + output.WriteString(PlainString); + } + if (o1Case_ == O1OneofCase.O1String) { + output.WriteRawTag(18); + output.WriteString(O1String); + } + if (o2Case_ == O2OneofCase.O2String) { + output.WriteRawTag(26); + output.WriteString(O2String); + } + if (PlainInt32 != 0) { + output.WriteRawTag(32); + output.WriteInt32(PlainInt32); + } + if (o1Case_ == O1OneofCase.O1Int32) { + output.WriteRawTag(40); + output.WriteInt32(O1Int32); + } + if (o2Case_ == O2OneofCase.O2Int32) { + output.WriteRawTag(48); + output.WriteInt32(O2Int32); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (PlainString.Length != 0) { + output.WriteRawTag(10); + output.WriteString(PlainString); + } + if (o1Case_ == O1OneofCase.O1String) { + output.WriteRawTag(18); + output.WriteString(O1String); + } + if (o2Case_ == O2OneofCase.O2String) { + output.WriteRawTag(26); + output.WriteString(O2String); + } + if (PlainInt32 != 0) { + output.WriteRawTag(32); + output.WriteInt32(PlainInt32); + } + if (o1Case_ == O1OneofCase.O1Int32) { + output.WriteRawTag(40); + output.WriteInt32(O1Int32); + } + if (o2Case_ == O2OneofCase.O2Int32) { + output.WriteRawTag(48); + output.WriteInt32(O2Int32); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (PlainInt32 != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(PlainInt32); + } + if (o1Case_ == O1OneofCase.O1String) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(O1String); + } + if (o1Case_ == O1OneofCase.O1Int32) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(O1Int32); + } + if (PlainString.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(PlainString); + } + if (o2Case_ == O2OneofCase.O2Int32) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(O2Int32); + } + if (o2Case_ == O2OneofCase.O2String) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(O2String); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestJsonFieldOrdering other) { + if (other == null) { + return; + } + if (other.PlainInt32 != 0) { + PlainInt32 = other.PlainInt32; + } + if (other.PlainString.Length != 0) { + PlainString = other.PlainString; + } + switch (other.O1Case) { + case O1OneofCase.O1String: + O1String = other.O1String; + break; + case O1OneofCase.O1Int32: + O1Int32 = other.O1Int32; + break; + } + + switch (other.O2Case) { + case O2OneofCase.O2Int32: + O2Int32 = other.O2Int32; + break; + case O2OneofCase.O2String: + O2String = other.O2String; + break; + } + + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + PlainString = input.ReadString(); + break; + } + case 18: { + O1String = input.ReadString(); + break; + } + case 26: { + O2String = input.ReadString(); + break; + } + case 32: { + PlainInt32 = input.ReadInt32(); + break; + } + case 40: { + O1Int32 = input.ReadInt32(); + break; + } + case 48: { + O2Int32 = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + PlainString = input.ReadString(); + break; + } + case 18: { + O1String = input.ReadString(); + break; + } + case 26: { + O2String = input.ReadString(); + break; + } + case 32: { + PlainInt32 = input.ReadInt32(); + break; + } + case 40: { + O1Int32 = input.ReadInt32(); + break; + } + case 48: { + O2Int32 = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + public sealed partial class TestJsonName : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestJsonName()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[7]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestJsonName() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestJsonName(TestJsonName other) : this() { + name_ = other.name_; + description_ = other.description_; + guid_ = other.guid_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestJsonName Clone() { + return new TestJsonName(this); + } + + /// Field number for the "name" field. + public const int NameFieldNumber = 1; + private string name_ = ""; + /// + /// Message for testing the effects for of the json_name option + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string Name { + get { return name_; } + set { + name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "description" field. + public const int DescriptionFieldNumber = 2; + private string description_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string Description { + get { return description_; } + set { + description_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "guid" field. + public const int GuidFieldNumber = 3; + private string guid_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string Guid { + get { return guid_; } + set { + guid_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as TestJsonName); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(TestJsonName other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + if (Description != other.Description) return false; + if (Guid != other.Guid) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (Name.Length != 0) hash ^= Name.GetHashCode(); + if (Description.Length != 0) hash ^= Description.GetHashCode(); + if (Guid.Length != 0) hash ^= Guid.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Name.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (Description.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Description); + } + if (Guid.Length != 0) { + output.WriteRawTag(26); + output.WriteString(Guid); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Name.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (Description.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Description); + } + if (Guid.Length != 0) { + output.WriteRawTag(26); + output.WriteString(Guid); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (Name.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + if (Description.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Description); + } + if (Guid.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Guid); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(TestJsonName other) { + if (other == null) { + return; + } + if (other.Name.Length != 0) { + Name = other.Name; + } + if (other.Description.Length != 0) { + Description = other.Description; + } + if (other.Guid.Length != 0) { + Guid = other.Guid; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + Description = input.ReadString(); + break; + } + case 26: { + Guid = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + Description = input.ReadString(); + break; + } + case 26: { + Guid = input.ReadString(); + break; + } + } + } + } + #endif + + } + + /// + /// Issue 3200: When merging two messages which use the same + /// oneof case, which is itself a message type, the submessages should + /// be merged. + /// + public sealed partial class OneofMerging : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new OneofMerging()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[8]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneofMerging() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneofMerging(OneofMerging other) : this() { + switch (other.ValueCase) { + case ValueOneofCase.Text: + Text = other.Text; + break; + case ValueOneofCase.Nested: + Nested = other.Nested.Clone(); + break; + } + + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneofMerging Clone() { + return new OneofMerging(this); + } + + /// Field number for the "text" field. + public const int TextFieldNumber = 1; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string Text { + get { return valueCase_ == ValueOneofCase.Text ? (string) value_ : ""; } + set { + value_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + valueCase_ = ValueOneofCase.Text; + } + } + + /// Field number for the "nested" field. + public const int NestedFieldNumber = 2; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::UnitTest.Issues.TestProtos.OneofMerging.Types.Nested Nested { + get { return valueCase_ == ValueOneofCase.Nested ? (global::UnitTest.Issues.TestProtos.OneofMerging.Types.Nested) value_ : null; } + set { + value_ = value; + valueCase_ = value == null ? ValueOneofCase.None : ValueOneofCase.Nested; + } + } + + private object value_; + /// Enum of possible cases for the "value" oneof. + public enum ValueOneofCase { + None = 0, + Text = 1, + Nested = 2, + } + private ValueOneofCase valueCase_ = ValueOneofCase.None; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ValueOneofCase ValueCase { + get { return valueCase_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearValue() { + valueCase_ = ValueOneofCase.None; + value_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as OneofMerging); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(OneofMerging other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Text != other.Text) return false; + if (!object.Equals(Nested, other.Nested)) return false; + if (ValueCase != other.ValueCase) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (valueCase_ == ValueOneofCase.Text) hash ^= Text.GetHashCode(); + if (valueCase_ == ValueOneofCase.Nested) hash ^= Nested.GetHashCode(); + hash ^= (int) valueCase_; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (valueCase_ == ValueOneofCase.Text) { + output.WriteRawTag(10); + output.WriteString(Text); + } + if (valueCase_ == ValueOneofCase.Nested) { + output.WriteRawTag(18); + output.WriteMessage(Nested); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (valueCase_ == ValueOneofCase.Text) { + output.WriteRawTag(10); + output.WriteString(Text); + } + if (valueCase_ == ValueOneofCase.Nested) { + output.WriteRawTag(18); + output.WriteMessage(Nested); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (valueCase_ == ValueOneofCase.Text) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Text); + } + if (valueCase_ == ValueOneofCase.Nested) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Nested); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(OneofMerging other) { + if (other == null) { + return; + } + switch (other.ValueCase) { + case ValueOneofCase.Text: + Text = other.Text; + break; + case ValueOneofCase.Nested: + if (Nested == null) { + Nested = new global::UnitTest.Issues.TestProtos.OneofMerging.Types.Nested(); + } + Nested.MergeFrom(other.Nested); + break; + } + + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Text = input.ReadString(); + break; + } + case 18: { + global::UnitTest.Issues.TestProtos.OneofMerging.Types.Nested subBuilder = new global::UnitTest.Issues.TestProtos.OneofMerging.Types.Nested(); + if (valueCase_ == ValueOneofCase.Nested) { + subBuilder.MergeFrom(Nested); + } + input.ReadMessage(subBuilder); + Nested = subBuilder; + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Text = input.ReadString(); + break; + } + case 18: { + global::UnitTest.Issues.TestProtos.OneofMerging.Types.Nested subBuilder = new global::UnitTest.Issues.TestProtos.OneofMerging.Types.Nested(); + if (valueCase_ == ValueOneofCase.Nested) { + subBuilder.MergeFrom(Nested); + } + input.ReadMessage(subBuilder); + Nested = subBuilder; + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the OneofMerging message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static partial class Types { + public sealed partial class Nested : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Nested()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::UnitTest.Issues.TestProtos.OneofMerging.Descriptor.NestedTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Nested() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Nested(Nested other) : this() { + x_ = other.x_; + y_ = other.y_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Nested Clone() { + return new Nested(this); + } + + /// Field number for the "x" field. + public const int XFieldNumber = 1; + private int x_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int X { + get { return x_; } + set { + x_ = value; + } + } + + /// Field number for the "y" field. + public const int YFieldNumber = 2; + private int y_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Y { + get { return y_; } + set { + y_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as Nested); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(Nested other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (X != other.X) return false; + if (Y != other.Y) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (X != 0) hash ^= X.GetHashCode(); + if (Y != 0) hash ^= Y.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (X != 0) { + output.WriteRawTag(8); + output.WriteInt32(X); + } + if (Y != 0) { + output.WriteRawTag(16); + output.WriteInt32(Y); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (X != 0) { + output.WriteRawTag(8); + output.WriteInt32(X); + } + if (Y != 0) { + output.WriteRawTag(16); + output.WriteInt32(Y); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (X != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(X); + } + if (Y != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Y); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(Nested other) { + if (other == null) { + return; + } + if (other.X != 0) { + X = other.X; + } + if (other.Y != 0) { + Y = other.Y; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + X = input.ReadInt32(); + break; + } + case 16: { + Y = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + X = input.ReadInt32(); + break; + } + case 16: { + Y = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + } + #endregion + + } + + public sealed partial class NullValueOutsideStruct : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new NullValueOutsideStruct()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[9]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NullValueOutsideStruct() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NullValueOutsideStruct(NullValueOutsideStruct other) : this() { + switch (other.ValueCase) { + case ValueOneofCase.StringValue: + StringValue = other.StringValue; + break; + case ValueOneofCase.NullValue: + NullValue = other.NullValue; + break; + } + + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NullValueOutsideStruct Clone() { + return new NullValueOutsideStruct(this); + } + + /// Field number for the "string_value" field. + public const int StringValueFieldNumber = 1; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string StringValue { + get { return valueCase_ == ValueOneofCase.StringValue ? (string) value_ : ""; } + set { + value_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + valueCase_ = ValueOneofCase.StringValue; + } + } + + /// Field number for the "null_value" field. + public const int NullValueFieldNumber = 2; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.WellKnownTypes.NullValue NullValue { + get { return valueCase_ == ValueOneofCase.NullValue ? (global::Google.Protobuf.WellKnownTypes.NullValue) value_ : global::Google.Protobuf.WellKnownTypes.NullValue.NullValue; } + set { + value_ = value; + valueCase_ = ValueOneofCase.NullValue; + } + } + + private object value_; + /// Enum of possible cases for the "value" oneof. + public enum ValueOneofCase { + None = 0, + StringValue = 1, + NullValue = 2, + } + private ValueOneofCase valueCase_ = ValueOneofCase.None; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public ValueOneofCase ValueCase { + get { return valueCase_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearValue() { + valueCase_ = ValueOneofCase.None; + value_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as NullValueOutsideStruct); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(NullValueOutsideStruct other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (StringValue != other.StringValue) return false; + if (NullValue != other.NullValue) return false; + if (ValueCase != other.ValueCase) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (valueCase_ == ValueOneofCase.StringValue) hash ^= StringValue.GetHashCode(); + if (valueCase_ == ValueOneofCase.NullValue) hash ^= NullValue.GetHashCode(); + hash ^= (int) valueCase_; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (valueCase_ == ValueOneofCase.StringValue) { + output.WriteRawTag(10); + output.WriteString(StringValue); + } + if (valueCase_ == ValueOneofCase.NullValue) { + output.WriteRawTag(16); + output.WriteEnum((int) NullValue); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (valueCase_ == ValueOneofCase.StringValue) { + output.WriteRawTag(10); + output.WriteString(StringValue); + } + if (valueCase_ == ValueOneofCase.NullValue) { + output.WriteRawTag(16); + output.WriteEnum((int) NullValue); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (valueCase_ == ValueOneofCase.StringValue) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(StringValue); + } + if (valueCase_ == ValueOneofCase.NullValue) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) NullValue); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(NullValueOutsideStruct other) { + if (other == null) { + return; + } + switch (other.ValueCase) { + case ValueOneofCase.StringValue: + StringValue = other.StringValue; + break; + case ValueOneofCase.NullValue: + NullValue = other.NullValue; + break; + } + + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + StringValue = input.ReadString(); + break; + } + case 16: { + value_ = input.ReadEnum(); + valueCase_ = ValueOneofCase.NullValue; + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + StringValue = input.ReadString(); + break; + } + case 16: { + value_ = input.ReadEnum(); + valueCase_ = ValueOneofCase.NullValue; + break; + } + } + } + } + #endif + + } + + public sealed partial class NullValueNotInOneof : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new NullValueNotInOneof()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[10]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NullValueNotInOneof() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NullValueNotInOneof(NullValueNotInOneof other) : this() { + nullValue_ = other.nullValue_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NullValueNotInOneof Clone() { + return new NullValueNotInOneof(this); + } + + /// Field number for the "null_value" field. + public const int NullValueFieldNumber = 2; + private global::Google.Protobuf.WellKnownTypes.NullValue nullValue_ = global::Google.Protobuf.WellKnownTypes.NullValue.NullValue; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public global::Google.Protobuf.WellKnownTypes.NullValue NullValue { + get { return nullValue_; } + set { + nullValue_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as NullValueNotInOneof); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(NullValueNotInOneof other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (NullValue != other.NullValue) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (NullValue != global::Google.Protobuf.WellKnownTypes.NullValue.NullValue) hash ^= NullValue.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (NullValue != global::Google.Protobuf.WellKnownTypes.NullValue.NullValue) { + output.WriteRawTag(16); + output.WriteEnum((int) NullValue); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (NullValue != global::Google.Protobuf.WellKnownTypes.NullValue.NullValue) { + output.WriteRawTag(16); + output.WriteEnum((int) NullValue); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (NullValue != global::Google.Protobuf.WellKnownTypes.NullValue.NullValue) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) NullValue); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(NullValueNotInOneof other) { + if (other == null) { + return; + } + if (other.NullValue != global::Google.Protobuf.WellKnownTypes.NullValue.NullValue) { + NullValue = other.NullValue; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 16: { + NullValue = (global::Google.Protobuf.WellKnownTypes.NullValue) input.ReadEnum(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 16: { + NullValue = (global::Google.Protobuf.WellKnownTypes.NullValue) input.ReadEnum(); + break; + } + } + } + } + #endif + + } + + public sealed partial class MixedRegularAndOptional : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new MixedRegularAndOptional()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[11]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MixedRegularAndOptional() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MixedRegularAndOptional(MixedRegularAndOptional other) : this() { + regularField_ = other.regularField_; + optionalField_ = other.optionalField_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public MixedRegularAndOptional Clone() { + return new MixedRegularAndOptional(this); + } + + /// Field number for the "regular_field" field. + public const int RegularFieldFieldNumber = 1; + private string regularField_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string RegularField { + get { return regularField_; } + set { + regularField_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "optional_field" field. + public const int OptionalFieldFieldNumber = 2; + private string optionalField_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string OptionalField { + get { return optionalField_ ?? ""; } + set { + optionalField_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + /// Gets whether the "optional_field" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasOptionalField { + get { return optionalField_ != null; } + } + /// Clears the value of the "optional_field" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearOptionalField() { + optionalField_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as MixedRegularAndOptional); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(MixedRegularAndOptional other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (RegularField != other.RegularField) return false; + if (OptionalField != other.OptionalField) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (RegularField.Length != 0) hash ^= RegularField.GetHashCode(); + if (HasOptionalField) hash ^= OptionalField.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (RegularField.Length != 0) { + output.WriteRawTag(10); + output.WriteString(RegularField); + } + if (HasOptionalField) { + output.WriteRawTag(18); + output.WriteString(OptionalField); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (RegularField.Length != 0) { + output.WriteRawTag(10); + output.WriteString(RegularField); + } + if (HasOptionalField) { + output.WriteRawTag(18); + output.WriteString(OptionalField); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (RegularField.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(RegularField); + } + if (HasOptionalField) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(OptionalField); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(MixedRegularAndOptional other) { + if (other == null) { + return; + } + if (other.RegularField.Length != 0) { + RegularField = other.RegularField; + } + if (other.HasOptionalField) { + OptionalField = other.OptionalField; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + RegularField = input.ReadString(); + break; + } + case 18: { + OptionalField = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + RegularField = input.ReadString(); + break; + } + case 18: { + OptionalField = input.ReadString(); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test.TestProtos/UnittestSelfreferentialOptions.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test.TestProtos/UnittestSelfreferentialOptions.cs new file mode 100644 index 0000000..7a8f72d --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test.TestProtos/UnittestSelfreferentialOptions.cs @@ -0,0 +1,379 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: unittest_selfreferential_options.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace UnitTest.Issues.TestProtos.SelfreferentialOptions { + + /// Holder for reflection information generated from unittest_selfreferential_options.proto + public static partial class UnittestSelfreferentialOptionsReflection { + + #region Descriptor + /// File descriptor for unittest_selfreferential_options.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static UnittestSelfreferentialOptionsReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "CiZ1bml0dGVzdF9zZWxmcmVmZXJlbnRpYWxfb3B0aW9ucy5wcm90bxIpcHJv", + "dG9idWZfdW5pdHRlc3Rfc2VsZnJlZmVyZW50aWFsX29wdGlvbnMaIGdvb2ds", + "ZS9wcm90b2J1Zi9kZXNjcmlwdG9yLnByb3RvIkwKCkZvb09wdGlvbnMSHgoH", + "aW50X29wdBgBIAEoBUINyj4KCAHAPgLKPgIIAxITCgNmb28YAiABKAVCBso+", + "AxDSCSoJCOgHEICAgIACOjkKC2Jhcl9vcHRpb25zEh0uZ29vZ2xlLnByb3Rv", + "YnVmLkZpZWxkT3B0aW9ucxjoByABKAVCBMA+0gk6agoLZm9vX29wdGlvbnMS", + "HS5nb29nbGUucHJvdG9idWYuRmllbGRPcHRpb25zGOkHIAEoCzI1LnByb3Rv", + "YnVmX3VuaXR0ZXN0X3NlbGZyZWZlcmVudGlhbF9vcHRpb25zLkZvb09wdGlv", + "bnM6SwoLZm9vX2ludF9vcHQSNS5wcm90b2J1Zl91bml0dGVzdF9zZWxmcmVm", + "ZXJlbnRpYWxfb3B0aW9ucy5Gb29PcHRpb25zGOgHIAEoBTqCAQoLZm9vX2Zv", + "b19vcHQSNS5wcm90b2J1Zl91bml0dGVzdF9zZWxmcmVmZXJlbnRpYWxfb3B0", + "aW9ucy5Gb29PcHRpb25zGOkHIAEoCzI1LnByb3RvYnVmX3VuaXR0ZXN0X3Nl", + "bGZyZWZlcmVudGlhbF9vcHRpb25zLkZvb09wdGlvbnNCNKoCMVVuaXRUZXN0", + "Lklzc3Vlcy5UZXN0UHJvdG9zLlNlbGZyZWZlcmVudGlhbE9wdGlvbnM=")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor, }, + new pbr::GeneratedClrTypeInfo(null, new pb::Extension[] { UnittestSelfreferentialOptionsExtensions.BarOptions, UnittestSelfreferentialOptionsExtensions.FooOptions, UnittestSelfreferentialOptionsExtensions.FooIntOpt, UnittestSelfreferentialOptionsExtensions.FooFooOpt }, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.SelfreferentialOptions.FooOptions), global::UnitTest.Issues.TestProtos.SelfreferentialOptions.FooOptions.Parser, new[]{ "IntOpt", "Foo" }, null, null, null, null) + })); + } + #endregion + + } + /// Holder for extension identifiers generated from the top level of unittest_selfreferential_options.proto + public static partial class UnittestSelfreferentialOptionsExtensions { + /// + /// Custom field option used on the definition of that field option. + /// + public static readonly pb::Extension BarOptions = + new pb::Extension(1000, pb::FieldCodec.ForInt32(8000, 0)); + public static readonly pb::Extension FooOptions = + new pb::Extension(1001, pb::FieldCodec.ForMessage(8010, global::UnitTest.Issues.TestProtos.SelfreferentialOptions.FooOptions.Parser)); + public static readonly pb::Extension FooIntOpt = + new pb::Extension(1000, pb::FieldCodec.ForInt32(8000, 0)); + public static readonly pb::Extension FooFooOpt = + new pb::Extension(1001, pb::FieldCodec.ForMessage(8010, global::UnitTest.Issues.TestProtos.SelfreferentialOptions.FooOptions.Parser)); + } + + #region Messages + public sealed partial class FooOptions : pb::IExtendableMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new FooOptions()); + private pb::UnknownFieldSet _unknownFields; + private pb::ExtensionSet _extensions; + private pb::ExtensionSet _Extensions { get { return _extensions; } } + private int _hasBits0; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::UnitTest.Issues.TestProtos.SelfreferentialOptions.UnittestSelfreferentialOptionsReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooOptions() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooOptions(FooOptions other) : this() { + _hasBits0 = other._hasBits0; + intOpt_ = other.intOpt_; + foo_ = other.foo_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + _extensions = pb::ExtensionSet.Clone(other._extensions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public FooOptions Clone() { + return new FooOptions(this); + } + + /// Field number for the "int_opt" field. + public const int IntOptFieldNumber = 1; + private readonly static int IntOptDefaultValue = 0; + + private int intOpt_; + /// + /// Custom field option used in definition of the extension message. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int IntOpt { + get { if ((_hasBits0 & 1) != 0) { return intOpt_; } else { return IntOptDefaultValue; } } + set { + _hasBits0 |= 1; + intOpt_ = value; + } + } + /// Gets whether the "int_opt" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasIntOpt { + get { return (_hasBits0 & 1) != 0; } + } + /// Clears the value of the "int_opt" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearIntOpt() { + _hasBits0 &= ~1; + } + + /// Field number for the "foo" field. + public const int FooFieldNumber = 2; + private readonly static int FooDefaultValue = 0; + + private int foo_; + /// + /// Custom field option used in definition of the custom option's message. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Foo { + get { if ((_hasBits0 & 2) != 0) { return foo_; } else { return FooDefaultValue; } } + set { + _hasBits0 |= 2; + foo_ = value; + } + } + /// Gets whether the "foo" field is set + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool HasFoo { + get { return (_hasBits0 & 2) != 0; } + } + /// Clears the value of the "foo" field + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearFoo() { + _hasBits0 &= ~2; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as FooOptions); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(FooOptions other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (IntOpt != other.IntOpt) return false; + if (Foo != other.Foo) return false; + if (!Equals(_extensions, other._extensions)) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (HasIntOpt) hash ^= IntOpt.GetHashCode(); + if (HasFoo) hash ^= Foo.GetHashCode(); + if (_extensions != null) { + hash ^= _extensions.GetHashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (HasIntOpt) { + output.WriteRawTag(8); + output.WriteInt32(IntOpt); + } + if (HasFoo) { + output.WriteRawTag(16); + output.WriteInt32(Foo); + } + if (_extensions != null) { + _extensions.WriteTo(output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (HasIntOpt) { + output.WriteRawTag(8); + output.WriteInt32(IntOpt); + } + if (HasFoo) { + output.WriteRawTag(16); + output.WriteInt32(Foo); + } + if (_extensions != null) { + _extensions.WriteTo(ref output); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (HasIntOpt) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(IntOpt); + } + if (HasFoo) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Foo); + } + if (_extensions != null) { + size += _extensions.CalculateSize(); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(FooOptions other) { + if (other == null) { + return; + } + if (other.HasIntOpt) { + IntOpt = other.IntOpt; + } + if (other.HasFoo) { + Foo = other.Foo; + } + pb::ExtensionSet.MergeFrom(ref _extensions, other._extensions); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + } + break; + case 8: { + IntOpt = input.ReadInt32(); + break; + } + case 16: { + Foo = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + if (!pb::ExtensionSet.TryMergeFieldFrom(ref _extensions, ref input)) { + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + } + break; + case 8: { + IntOpt = input.ReadInt32(); + break; + } + case 16: { + Foo = input.ReadInt32(); + break; + } + } + } + } + #endif + + public TValue GetExtension(pb::Extension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.Get(ref _extensions, extension); + } + public pbc::RepeatedField GetOrInitializeExtension(pb::RepeatedExtension extension) { + return pb::ExtensionSet.GetOrInitialize(ref _extensions, extension); + } + public void SetExtension(pb::Extension extension, TValue value) { + pb::ExtensionSet.Set(ref _extensions, extension, value); + } + public bool HasExtension(pb::Extension extension) { + return pb::ExtensionSet.Has(ref _extensions, extension); + } + public void ClearExtension(pb::Extension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + public void ClearExtension(pb::RepeatedExtension extension) { + pb::ExtensionSet.Clear(ref _extensions, extension); + } + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/ByteStringTest.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/ByteStringTest.cs new file mode 100644 index 0000000..04d68b5 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/ByteStringTest.cs @@ -0,0 +1,439 @@ +#region Copyright notice and license +// 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. +#endregion + +using System; +using System.Text; +using NUnit.Framework; +using System.IO; +using System.Collections.Generic; +using System.Collections; +using System.Linq; +using System.Buffers; +using System.Runtime.InteropServices; +using System.Threading; +using System.Runtime.CompilerServices; +#if !NET35 +using System.Threading.Tasks; +#endif + +namespace Google.Protobuf +{ + public class ByteStringTest + { + [Test] + public void Equality() + { + ByteString b1 = ByteString.CopyFrom(1, 2, 3); + ByteString b2 = ByteString.CopyFrom(1, 2, 3); + ByteString b3 = ByteString.CopyFrom(1, 2, 4); + ByteString b4 = ByteString.CopyFrom(1, 2, 3, 4); + EqualityTester.AssertEquality(b1, b1); + EqualityTester.AssertEquality(b1, b2); + EqualityTester.AssertInequality(b1, b3); + EqualityTester.AssertInequality(b1, b4); + EqualityTester.AssertInequality(b1, null); + EqualityTester.AssertEquality(ByteString.Empty, ByteString.Empty); +#pragma warning disable 1718 // Deliberately calling ==(b1, b1) and !=(b1, b1) + Assert.IsTrue(b1 == b1); + Assert.IsTrue(b1 == b2); + Assert.IsFalse(b1 == b3); + Assert.IsFalse(b1 == b4); + Assert.IsFalse(b1 == null); + Assert.IsTrue((ByteString) null == null); + Assert.IsFalse(b1 != b1); + Assert.IsFalse(b1 != b2); + Assert.IsTrue(ByteString.Empty == ByteString.Empty); +#pragma warning disable 1718 + Assert.IsTrue(b1 != b3); + Assert.IsTrue(b1 != b4); + Assert.IsTrue(b1 != null); + Assert.IsFalse((ByteString) null != null); + } + + [Test] + public void EmptyByteStringHasZeroSize() + { + Assert.AreEqual(0, ByteString.Empty.Length); + } + + [Test] + public void CopyFromStringWithExplicitEncoding() + { + ByteString bs = ByteString.CopyFrom("AB", Encoding.Unicode); + Assert.AreEqual(4, bs.Length); + Assert.AreEqual(65, bs[0]); + Assert.AreEqual(0, bs[1]); + Assert.AreEqual(66, bs[2]); + Assert.AreEqual(0, bs[3]); + } + + [Test] + public void IsEmptyWhenEmpty() + { + Assert.IsTrue(ByteString.CopyFromUtf8("").IsEmpty); + } + + [Test] + public void IsEmptyWhenNotEmpty() + { + Assert.IsFalse(ByteString.CopyFromUtf8("X").IsEmpty); + } + + [Test] + public void CopyFromByteArrayCopiesContents() + { + byte[] data = new byte[1]; + data[0] = 10; + ByteString bs = ByteString.CopyFrom(data); + Assert.AreEqual(10, bs[0]); + data[0] = 5; + Assert.AreEqual(10, bs[0]); + } + + [Test] + public void CopyFromReadOnlySpanCopiesContents() + { + byte[] data = new byte[1]; + data[0] = 10; + ReadOnlySpan byteSpan = data; + var bs = ByteString.CopyFrom(byteSpan); + Assert.AreEqual(10, bs[0]); + data[0] = 5; + Assert.AreEqual(10, bs[0]); + } + + [Test] + public void ToByteArrayCopiesContents() + { + ByteString bs = ByteString.CopyFromUtf8("Hello"); + byte[] data = bs.ToByteArray(); + Assert.AreEqual((byte)'H', data[0]); + Assert.AreEqual((byte)'H', bs[0]); + data[0] = 0; + Assert.AreEqual(0, data[0]); + Assert.AreEqual((byte)'H', bs[0]); + } + + [Test] + public void CopyFromUtf8UsesUtf8() + { + ByteString bs = ByteString.CopyFromUtf8("\u20ac"); + Assert.AreEqual(3, bs.Length); + Assert.AreEqual(0xe2, bs[0]); + Assert.AreEqual(0x82, bs[1]); + Assert.AreEqual(0xac, bs[2]); + } + + [Test] + public void CopyFromPortion() + { + byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6}; + ByteString bs = ByteString.CopyFrom(data, 2, 3); + Assert.AreEqual(3, bs.Length); + Assert.AreEqual(2, bs[0]); + Assert.AreEqual(3, bs[1]); + } + + [Test] + public void CopyTo() + { + byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; + ByteString bs = ByteString.CopyFrom(data); + + byte[] dest = new byte[data.Length]; + bs.CopyTo(dest, 0); + + CollectionAssert.AreEqual(data, dest); + } + + [Test] + public void GetEnumerator() + { + byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; + ByteString bs = ByteString.CopyFrom(data); + + IEnumerator genericEnumerator = bs.GetEnumerator(); + Assert.IsTrue(genericEnumerator.MoveNext()); + Assert.AreEqual(0, genericEnumerator.Current); + + IEnumerator enumerator = ((IEnumerable)bs).GetEnumerator(); + Assert.IsTrue(enumerator.MoveNext()); + Assert.AreEqual(0, enumerator.Current); + + // Call via LINQ + CollectionAssert.AreEqual(bs.Span.ToArray(), bs.ToArray()); + } + + [Test] + public void UnsafeWrap() + { + byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; + ByteString bs = UnsafeByteOperations.UnsafeWrap(data.AsMemory(2, 3)); + ReadOnlySpan s = bs.Span; + + Assert.AreEqual(3, s.Length); + Assert.AreEqual(2, s[0]); + Assert.AreEqual(3, s[1]); + Assert.AreEqual(4, s[2]); + + // Check that the value is not a copy + data[2] = byte.MaxValue; + Assert.AreEqual(byte.MaxValue, s[0]); + } + + [Test] + public void CreateCodedInput_FromArraySegment() + { + byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; + ByteString bs = UnsafeByteOperations.UnsafeWrap(data.AsMemory(2, 3)); + CodedInputStream codedInputStream = bs.CreateCodedInput(); + + byte[] bytes = codedInputStream.ReadRawBytes(3); + + Assert.AreEqual(3, bytes.Length); + Assert.AreEqual(2, bytes[0]); + Assert.AreEqual(3, bytes[1]); + Assert.AreEqual(4, bytes[2]); + Assert.IsTrue(codedInputStream.IsAtEnd); + } + + [Test] + public void WriteToStream() + { + byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; + ByteString bs = ByteString.CopyFrom(data); + + MemoryStream ms = new MemoryStream(); + bs.WriteTo(ms); + + CollectionAssert.AreEqual(data, ms.ToArray()); + } + + [Test] + public void WriteToStream_Stackalloc() + { + byte[] data = Encoding.UTF8.GetBytes("Hello world"); + Span s = stackalloc byte[data.Length]; + data.CopyTo(s); + + MemoryStream ms = new MemoryStream(); + + using (UnmanagedMemoryManager manager = new UnmanagedMemoryManager(s)) + { + ByteString bs = ByteString.AttachBytes(manager.Memory); + + bs.WriteTo(ms); + } + + CollectionAssert.AreEqual(data, ms.ToArray()); + } + + [Test] + public void ToStringUtf8() + { + ByteString bs = ByteString.CopyFromUtf8("\u20ac"); + Assert.AreEqual("\u20ac", bs.ToStringUtf8()); + } + + [Test] + public void ToStringWithExplicitEncoding() + { + ByteString bs = ByteString.CopyFrom("\u20ac", Encoding.Unicode); + Assert.AreEqual("\u20ac", bs.ToString(Encoding.Unicode)); + } + + [Test] + public void ToString_Stackalloc() + { + byte[] data = Encoding.UTF8.GetBytes("Hello world"); + Span s = stackalloc byte[data.Length]; + data.CopyTo(s); + + using (UnmanagedMemoryManager manager = new UnmanagedMemoryManager(s)) + { + ByteString bs = ByteString.AttachBytes(manager.Memory); + + Assert.AreEqual("Hello world", bs.ToString(Encoding.UTF8)); + } + } + + [Test] + public void FromBase64_WithText() + { + byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6}; + string base64 = Convert.ToBase64String(data); + ByteString bs = ByteString.FromBase64(base64); + Assert.AreEqual(data, bs.ToByteArray()); + } + + [Test] + public void FromBase64_Empty() + { + // Optimization which also fixes issue 61. + Assert.AreSame(ByteString.Empty, ByteString.FromBase64("")); + } + + [Test] + public void ToBase64_Array() + { + ByteString bs = ByteString.CopyFrom(Encoding.UTF8.GetBytes("Hello world")); + + Assert.AreEqual("SGVsbG8gd29ybGQ=", bs.ToBase64()); + } + + [Test] + public void ToBase64_Stackalloc() + { + byte[] data = Encoding.UTF8.GetBytes("Hello world"); + Span s = stackalloc byte[data.Length]; + data.CopyTo(s); + + using (UnmanagedMemoryManager manager = new UnmanagedMemoryManager(s)) + { + ByteString bs = ByteString.AttachBytes(manager.Memory); + + Assert.AreEqual("SGVsbG8gd29ybGQ=", bs.ToBase64()); + } + } + + [Test] + public void FromStream_Seekable() + { + var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 }); + // Consume the first byte, just to test that it's "from current position" + stream.ReadByte(); + var actual = ByteString.FromStream(stream); + ByteString expected = ByteString.CopyFrom(2, 3, 4, 5); + Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}"); + } + + [Test] + public void FromStream_NotSeekable() + { + var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 }); + // Consume the first byte, just to test that it's "from current position" + stream.ReadByte(); + // Wrap the original stream in LimitedInputStream, which has CanSeek=false + var limitedStream = new LimitedInputStream(stream, 3); + var actual = ByteString.FromStream(limitedStream); + ByteString expected = ByteString.CopyFrom(2, 3, 4); + Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}"); + } + +#if !NET35 + [Test] + public async Task FromStreamAsync_Seekable() + { + var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 }); + // Consume the first byte, just to test that it's "from current position" + stream.ReadByte(); + var actual = await ByteString.FromStreamAsync(stream); + ByteString expected = ByteString.CopyFrom(2, 3, 4, 5); + Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}"); + } + + [Test] + public async Task FromStreamAsync_NotSeekable() + { + var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 }); + // Consume the first byte, just to test that it's "from current position" + stream.ReadByte(); + // Wrap the original stream in LimitedInputStream, which has CanSeek=false + var limitedStream = new LimitedInputStream(stream, 3); + var actual = await ByteString.FromStreamAsync(limitedStream); + ByteString expected = ByteString.CopyFrom(2, 3, 4); + Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}"); + } +#endif + + [Test] + public void GetHashCode_Regression() + { + // We used to have an awful hash algorithm where only the last four + // bytes were relevant. This is a regression test for + // https://github.com/protocolbuffers/protobuf/issues/2511 + + ByteString b1 = ByteString.CopyFrom(100, 1, 2, 3, 4); + ByteString b2 = ByteString.CopyFrom(200, 1, 2, 3, 4); + Assert.AreNotEqual(b1.GetHashCode(), b2.GetHashCode()); + } + + [Test] + public void GetContentsAsReadOnlySpan() + { + var byteString = ByteString.CopyFrom(1, 2, 3, 4, 5); + var copied = byteString.Span.ToArray(); + CollectionAssert.AreEqual(byteString, copied); + } + + [Test] + public void GetContentsAsReadOnlyMemory() + { + var byteString = ByteString.CopyFrom(1, 2, 3, 4, 5); + var copied = byteString.Memory.ToArray(); + CollectionAssert.AreEqual(byteString, copied); + } + + // Create Memory from non-array source. + // Use by ByteString tests that have optimized path for array backed Memory. + private sealed unsafe class UnmanagedMemoryManager : MemoryManager where T : unmanaged + { + private readonly T* _pointer; + private readonly int _length; + + public UnmanagedMemoryManager(Span span) + { + fixed (T* ptr = &MemoryMarshal.GetReference(span)) + { + _pointer = ptr; + _length = span.Length; + } + } + + public override Span GetSpan() => new Span(_pointer, _length); + + public override MemoryHandle Pin(int elementIndex = 0) + { + if (elementIndex < 0 || elementIndex >= _length) + { + throw new ArgumentOutOfRangeException(nameof(elementIndex)); + } + + return new MemoryHandle(_pointer + elementIndex); + } + + public override void Unpin() { } + + protected override void Dispose(bool disposing) { } + } + } +} \ No newline at end of file diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/DeprecatedMemberTest.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/DeprecatedMemberTest.cs new file mode 100644 index 0000000..34d5b9f --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/DeprecatedMemberTest.cs @@ -0,0 +1,55 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; +using System.Reflection; +using Google.Protobuf.TestProtos; +using NUnit.Framework; + +namespace Google.Protobuf +{ + public class DeprecatedMemberTest + { + private static void AssertIsDeprecated(MemberInfo member) + { + Assert.NotNull(member); + Assert.IsTrue(member.IsDefined(typeof(ObsoleteAttribute), false), "Member not obsolete: " + member); + } + + [Test] + public void TestDepreatedPrimitiveValue() + { + AssertIsDeprecated(typeof(TestDeprecatedFields).GetProperty("DeprecatedInt32")); + } + + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/FieldMaskTreeTest.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/FieldMaskTreeTest.cs new file mode 100644 index 0000000..f71744a --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/FieldMaskTreeTest.cs @@ -0,0 +1,436 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System.Collections.Generic; +using Google.Protobuf.Collections; +using Google.Protobuf.TestProtos; +using NUnit.Framework; +using Google.Protobuf.WellKnownTypes; + +namespace Google.Protobuf +{ + public class FieldMaskTreeTest + { + [Test] + public void AddFieldPath() + { + FieldMaskTree tree = new FieldMaskTree(); + RepeatedField paths = tree.ToFieldMask().Paths; + Assert.AreEqual(0, paths.Count); + + tree.AddFieldPath(""); + paths = tree.ToFieldMask().Paths; + Assert.AreEqual(1, paths.Count); + Assert.Contains("", paths); + + // New branch. + tree.AddFieldPath("foo"); + paths = tree.ToFieldMask().Paths; + Assert.AreEqual(2, paths.Count); + Assert.Contains("foo", paths); + + // Redundant path. + tree.AddFieldPath("foo"); + paths = tree.ToFieldMask().Paths; + Assert.AreEqual(2, paths.Count); + + // New branch. + tree.AddFieldPath("bar.baz"); + paths = tree.ToFieldMask().Paths; + Assert.AreEqual(3, paths.Count); + Assert.Contains("bar.baz", paths); + + // Redundant sub-path. + tree.AddFieldPath("foo.bar"); + paths = tree.ToFieldMask().Paths; + Assert.AreEqual(3, paths.Count); + + // New branch from a non-root node. + tree.AddFieldPath("bar.quz"); + paths = tree.ToFieldMask().Paths; + Assert.AreEqual(4, paths.Count); + Assert.Contains("bar.quz", paths); + + // A path that matches several existing sub-paths. + tree.AddFieldPath("bar"); + paths = tree.ToFieldMask().Paths; + Assert.AreEqual(3, paths.Count); + Assert.Contains("foo", paths); + Assert.Contains("bar", paths); + } + + [Test] + public void MergeFromFieldMask() + { + FieldMaskTree tree = new FieldMaskTree(); + tree.MergeFromFieldMask(new FieldMask + { + Paths = {"foo", "bar.baz", "bar.quz"} + }); + RepeatedField paths = tree.ToFieldMask().Paths; + Assert.AreEqual(3, paths.Count); + Assert.Contains("foo", paths); + Assert.Contains("bar.baz", paths); + Assert.Contains("bar.quz", paths); + + tree.MergeFromFieldMask(new FieldMask + { + Paths = {"foo.bar", "bar"} + }); + paths = tree.ToFieldMask().Paths; + Assert.AreEqual(2, paths.Count); + Assert.Contains("foo", paths); + Assert.Contains("bar", paths); + } + + [Test] + public void IntersectFieldPath() + { + FieldMaskTree tree = new FieldMaskTree(); + FieldMaskTree result = new FieldMaskTree(); + tree.MergeFromFieldMask(new FieldMask + { + Paths = {"foo", "bar.baz", "bar.quz"} + }); + + // Empty path. + tree.IntersectFieldPath("", result); + RepeatedField paths = result.ToFieldMask().Paths; + Assert.AreEqual(0, paths.Count); + + // Non-exist path. + tree.IntersectFieldPath("quz", result); + paths = result.ToFieldMask().Paths; + Assert.AreEqual(0, paths.Count); + + // Sub-path of an existing leaf. + tree.IntersectFieldPath("foo.bar", result); + paths = result.ToFieldMask().Paths; + Assert.AreEqual(1, paths.Count); + Assert.Contains("foo.bar", paths); + + // Match an existing leaf node. + tree.IntersectFieldPath("foo", result); + paths = result.ToFieldMask().Paths; + Assert.AreEqual(1, paths.Count); + Assert.Contains("foo", paths); + + // Non-exist path. + tree.IntersectFieldPath("bar.foo", result); + paths = result.ToFieldMask().Paths; + Assert.AreEqual(1, paths.Count); + Assert.Contains("foo", paths); + + // Match a non-leaf node. + tree.IntersectFieldPath("bar", result); + paths = result.ToFieldMask().Paths; + Assert.AreEqual(3, paths.Count); + Assert.Contains("foo", paths); + Assert.Contains("bar.baz", paths); + Assert.Contains("bar.quz", paths); + } + + private void Merge(FieldMaskTree tree, IMessage source, IMessage destination, FieldMask.MergeOptions options, bool useDynamicMessage) + { + if (useDynamicMessage) + { + var newSource = source.Descriptor.Parser.CreateTemplate(); + newSource.MergeFrom(source.ToByteString()); + + var newDestination = source.Descriptor.Parser.CreateTemplate(); + newDestination.MergeFrom(destination.ToByteString()); + + tree.Merge(newSource, newDestination, options); + + // Clear before merging: + foreach (var fieldDescriptor in destination.Descriptor.Fields.InFieldNumberOrder()) + { + fieldDescriptor.Accessor.Clear(destination); + } + destination.MergeFrom(newDestination.ToByteString()); + } + else + { + tree.Merge(source, destination, options); + } + } + + [Test] + [TestCase(true)] + [TestCase(false)] + public void Merge(bool useDynamicMessage) + { + TestAllTypes value = new TestAllTypes + { + SingleInt32 = 1234, + SingleNestedMessage = new TestAllTypes.Types.NestedMessage {Bb = 5678}, + RepeatedInt32 = {4321}, + RepeatedNestedMessage = {new TestAllTypes.Types.NestedMessage {Bb = 8765}} + }; + + NestedTestAllTypes source = new NestedTestAllTypes + { + Payload = value, + Child = new NestedTestAllTypes {Payload = value} + }; + // Now we have a message source with the following structure: + // [root] -+- payload -+- single_int32 + // | +- single_nested_message + // | +- repeated_int32 + // | +- repeated_nested_message + // | + // +- child --- payload -+- single_int32 + // +- single_nested_message + // +- repeated_int32 + // +- repeated_nested_message + + FieldMask.MergeOptions options = new FieldMask.MergeOptions(); + + // Test merging each individual field. + NestedTestAllTypes destination = new NestedTestAllTypes(); + Merge(new FieldMaskTree().AddFieldPath("payload.single_int32"), + source, destination, options, useDynamicMessage); + NestedTestAllTypes expected = new NestedTestAllTypes + { + Payload = new TestAllTypes + { + SingleInt32 = 1234 + } + }; + Assert.AreEqual(expected, destination); + + destination = new NestedTestAllTypes(); + Merge(new FieldMaskTree().AddFieldPath("payload.single_nested_message"), + source, destination, options, useDynamicMessage); + expected = new NestedTestAllTypes + { + Payload = new TestAllTypes + { + SingleNestedMessage = new TestAllTypes.Types.NestedMessage {Bb = 5678} + } + }; + Assert.AreEqual(expected, destination); + + destination = new NestedTestAllTypes(); + Merge(new FieldMaskTree().AddFieldPath("payload.repeated_int32"), + source, destination, options, useDynamicMessage); + expected = new NestedTestAllTypes + { + Payload = new TestAllTypes + { + RepeatedInt32 = {4321} + } + }; + Assert.AreEqual(expected, destination); + + destination = new NestedTestAllTypes(); + Merge(new FieldMaskTree().AddFieldPath("payload.repeated_nested_message"), + source, destination, options, useDynamicMessage); + expected = new NestedTestAllTypes + { + Payload = new TestAllTypes + { + RepeatedNestedMessage = {new TestAllTypes.Types.NestedMessage {Bb = 8765}} + } + }; + Assert.AreEqual(expected, destination); + + destination = new NestedTestAllTypes(); + Merge( + new FieldMaskTree().AddFieldPath("child.payload.single_int32"), + source, + destination, + options, + useDynamicMessage); + expected = new NestedTestAllTypes + { + Child = new NestedTestAllTypes + { + Payload = new TestAllTypes + { + SingleInt32 = 1234 + } + } + }; + Assert.AreEqual(expected, destination); + + destination = new NestedTestAllTypes(); + Merge( + new FieldMaskTree().AddFieldPath("child.payload.single_nested_message"), + source, + destination, + options, + useDynamicMessage); + expected = new NestedTestAllTypes + { + Child = new NestedTestAllTypes + { + Payload = new TestAllTypes + { + SingleNestedMessage = new TestAllTypes.Types.NestedMessage {Bb = 5678} + } + } + }; + Assert.AreEqual(expected, destination); + + destination = new NestedTestAllTypes(); + Merge(new FieldMaskTree().AddFieldPath("child.payload.repeated_int32"), + source, destination, options, useDynamicMessage); + expected = new NestedTestAllTypes + { + Child = new NestedTestAllTypes + { + Payload = new TestAllTypes + { + RepeatedInt32 = {4321} + } + } + }; + Assert.AreEqual(expected, destination); + + destination = new NestedTestAllTypes(); + Merge(new FieldMaskTree().AddFieldPath("child.payload.repeated_nested_message"), + source, destination, options, useDynamicMessage); + expected = new NestedTestAllTypes + { + Child = new NestedTestAllTypes + { + Payload = new TestAllTypes + { + RepeatedNestedMessage = {new TestAllTypes.Types.NestedMessage {Bb = 8765}} + } + } + }; + Assert.AreEqual(expected, destination); + + destination = new NestedTestAllTypes(); + Merge(new FieldMaskTree().AddFieldPath("child").AddFieldPath("payload"), + source, destination, options, useDynamicMessage); + Assert.AreEqual(source, destination); + + // Test repeated options. + destination = new NestedTestAllTypes + { + Payload = new TestAllTypes + { + RepeatedInt32 = { 1000 } + } + }; + Merge(new FieldMaskTree().AddFieldPath("payload.repeated_int32"), + source, destination, options, useDynamicMessage); + // Default behavior is to append repeated fields. + Assert.AreEqual(2, destination.Payload.RepeatedInt32.Count); + Assert.AreEqual(1000, destination.Payload.RepeatedInt32[0]); + Assert.AreEqual(4321, destination.Payload.RepeatedInt32[1]); + // Change to replace repeated fields. + options.ReplaceRepeatedFields = true; + Merge(new FieldMaskTree().AddFieldPath("payload.repeated_int32"), + source, destination, options, useDynamicMessage); + Assert.AreEqual(1, destination.Payload.RepeatedInt32.Count); + Assert.AreEqual(4321, destination.Payload.RepeatedInt32[0]); + + // Test message options. + destination = new NestedTestAllTypes + { + Payload = new TestAllTypes + { + SingleInt32 = 1000, + SingleUint32 = 2000 + } + }; + Merge(new FieldMaskTree().AddFieldPath("payload"), + source, destination, options, useDynamicMessage); + // Default behavior is to merge message fields. + Assert.AreEqual(1234, destination.Payload.SingleInt32); + Assert.AreEqual(2000, destination.Payload.SingleUint32); + + // Test merging unset message fields. + NestedTestAllTypes clearedSource = source.Clone(); + clearedSource.Payload = null; + destination = new NestedTestAllTypes(); + Merge(new FieldMaskTree().AddFieldPath("payload"), + clearedSource, destination, options, useDynamicMessage); + Assert.IsNull(destination.Payload); + + // Skip a message field if they are unset in both source and target. + destination = new NestedTestAllTypes(); + Merge(new FieldMaskTree().AddFieldPath("payload.single_int32"), + clearedSource, destination, options, useDynamicMessage); + Assert.IsNull(destination.Payload); + + // Change to replace message fields. + options.ReplaceMessageFields = true; + destination = new NestedTestAllTypes + { + Payload = new TestAllTypes + { + SingleInt32 = 1000, + SingleUint32 = 2000 + } + }; + Merge(new FieldMaskTree().AddFieldPath("payload"), + source, destination, options, useDynamicMessage); + Assert.AreEqual(1234, destination.Payload.SingleInt32); + Assert.AreEqual(0, destination.Payload.SingleUint32); + + // Test merging unset message fields. + destination = new NestedTestAllTypes + { + Payload = new TestAllTypes + { + SingleInt32 = 1000, + SingleUint32 = 2000 + } + }; + Merge(new FieldMaskTree().AddFieldPath("payload"), + clearedSource, destination, options, useDynamicMessage); + Assert.IsNull(destination.Payload); + + // Test merging unset primitive fields. + destination = source.Clone(); + destination.Payload.SingleInt32 = 0; + NestedTestAllTypes sourceWithPayloadInt32Unset = destination; + destination = source.Clone(); + Merge(new FieldMaskTree().AddFieldPath("payload.single_int32"), + sourceWithPayloadInt32Unset, destination, options, useDynamicMessage); + Assert.AreEqual(0, destination.Payload.SingleInt32); + + // Change to clear unset primitive fields. + options.ReplacePrimitiveFields = true; + destination = source.Clone(); + Merge(new FieldMaskTree().AddFieldPath("payload.single_int32"), + sourceWithPayloadInt32Unset, destination, options, useDynamicMessage); + Assert.IsNotNull(destination.Payload); + } + + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.Proto2.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.Proto2.cs new file mode 100644 index 0000000..894d914 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.Proto2.cs @@ -0,0 +1,397 @@ +using Google.Protobuf.TestProtos.Proto2; +using Proto2 = Google.Protobuf.TestProtos.Proto2; +using NUnit.Framework; + +using static Google.Protobuf.TestProtos.Proto2.UnittestExtensions; + +namespace Google.Protobuf +{ + /// + /// Tests around the generated TestAllTypes message in unittest.proto + /// + public partial class GeneratedMessageTest + { + [Test] + public void DefaultProto2Values() + { + var message = new TestAllTypes(); + Assert.AreEqual(false, message.OptionalBool); + Assert.AreEqual(ByteString.Empty, message.OptionalBytes); + Assert.AreEqual(0.0, message.OptionalDouble); + Assert.AreEqual(0, message.OptionalFixed32); + Assert.AreEqual(0L, message.OptionalFixed64); + Assert.AreEqual(0.0f, message.OptionalFloat); + Assert.AreEqual(ForeignEnum.ForeignFoo, message.OptionalForeignEnum); + Assert.IsNull(message.OptionalForeignMessage); + Assert.AreEqual(ImportEnum.ImportFoo, message.OptionalImportEnum); + Assert.IsNull(message.OptionalImportMessage); + Assert.AreEqual(0, message.OptionalInt32); + Assert.AreEqual(0L, message.OptionalInt64); + Assert.AreEqual(Proto2.TestAllTypes.Types.NestedEnum.Foo, message.OptionalNestedEnum); + Assert.IsNull(message.OptionalNestedMessage); + Assert.IsNull(message.OptionalPublicImportMessage); + Assert.AreEqual(0, message.OptionalSfixed32); + Assert.AreEqual(0L, message.OptionalSfixed64); + Assert.AreEqual(0, message.OptionalSint32); + Assert.AreEqual(0L, message.OptionalSint64); + Assert.AreEqual("", message.OptionalString); + Assert.AreEqual(0U, message.OptionalUint32); + Assert.AreEqual(0UL, message.OptionalUint64); + + // Repeated fields + Assert.AreEqual(0, message.RepeatedBool.Count); + Assert.AreEqual(0, message.RepeatedBytes.Count); + Assert.AreEqual(0, message.RepeatedDouble.Count); + Assert.AreEqual(0, message.RepeatedFixed32.Count); + Assert.AreEqual(0, message.RepeatedFixed64.Count); + Assert.AreEqual(0, message.RepeatedFloat.Count); + Assert.AreEqual(0, message.RepeatedForeignEnum.Count); + Assert.AreEqual(0, message.RepeatedForeignMessage.Count); + Assert.AreEqual(0, message.RepeatedImportEnum.Count); + Assert.AreEqual(0, message.RepeatedImportMessage.Count); + Assert.AreEqual(0, message.RepeatedNestedEnum.Count); + Assert.AreEqual(0, message.RepeatedNestedMessage.Count); + Assert.AreEqual(0, message.RepeatedSfixed32.Count); + Assert.AreEqual(0, message.RepeatedSfixed64.Count); + Assert.AreEqual(0, message.RepeatedSint32.Count); + Assert.AreEqual(0, message.RepeatedSint64.Count); + Assert.AreEqual(0, message.RepeatedString.Count); + Assert.AreEqual(0, message.RepeatedUint32.Count); + Assert.AreEqual(0, message.RepeatedUint64.Count); + + // Oneof fields + Assert.AreEqual(Proto2.TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + + Assert.AreEqual(true, message.DefaultBool); + Assert.AreEqual(ByteString.CopyFromUtf8("world"), message.DefaultBytes); + Assert.AreEqual("123", message.DefaultCord); + Assert.AreEqual(52e3, message.DefaultDouble); + Assert.AreEqual(47, message.DefaultFixed32); + Assert.AreEqual(48, message.DefaultFixed64); + Assert.AreEqual(51.5, message.DefaultFloat); + Assert.AreEqual(ForeignEnum.ForeignBar, message.DefaultForeignEnum); + Assert.AreEqual(ImportEnum.ImportBar, message.DefaultImportEnum); + Assert.AreEqual(41, message.DefaultInt32); + Assert.AreEqual(42, message.DefaultInt64); + Assert.AreEqual(Proto2.TestAllTypes.Types.NestedEnum.Bar, message.DefaultNestedEnum); + Assert.AreEqual(49, message.DefaultSfixed32); + Assert.AreEqual(-50, message.DefaultSfixed64); + Assert.AreEqual(-45, message.DefaultSint32); + Assert.AreEqual(46, message.DefaultSint64); + Assert.AreEqual("hello", message.DefaultString); + Assert.AreEqual("abc", message.DefaultStringPiece); + Assert.AreEqual(43, message.DefaultUint32); + Assert.AreEqual(44, message.DefaultUint64); + + Assert.False(message.HasDefaultBool); + Assert.False(message.HasDefaultBytes); + Assert.False(message.HasDefaultCord); + Assert.False(message.HasDefaultDouble); + Assert.False(message.HasDefaultFixed32); + Assert.False(message.HasDefaultFixed64); + Assert.False(message.HasDefaultFloat); + Assert.False(message.HasDefaultForeignEnum); + Assert.False(message.HasDefaultImportEnum); + Assert.False(message.HasDefaultInt32); + Assert.False(message.HasDefaultInt64); + Assert.False(message.HasDefaultNestedEnum); + Assert.False(message.HasDefaultSfixed32); + Assert.False(message.HasDefaultSfixed64); + Assert.False(message.HasDefaultSint32); + Assert.False(message.HasDefaultSint64); + Assert.False(message.HasDefaultString); + Assert.False(message.HasDefaultStringPiece); + Assert.False(message.HasDefaultUint32); + Assert.False(message.HasDefaultUint64); + } + + [Test] + public void DefaultExtensionValues() + { + var message = new TestAllExtensions(); + Assert.AreEqual(false, message.GetExtension(OptionalBoolExtension)); + Assert.AreEqual(ByteString.Empty, message.GetExtension(OptionalBytesExtension)); + Assert.AreEqual(0.0, message.GetExtension(OptionalDoubleExtension)); + Assert.AreEqual(0, message.GetExtension(OptionalFixed32Extension)); + Assert.AreEqual(0L, message.GetExtension(OptionalFixed64Extension)); + Assert.AreEqual(0.0f, message.GetExtension(OptionalFloatExtension)); + Assert.AreEqual(ForeignEnum.ForeignFoo, message.GetExtension(OptionalForeignEnumExtension)); + Assert.IsNull(message.GetExtension(OptionalForeignMessageExtension)); + Assert.AreEqual(ImportEnum.ImportFoo, message.GetExtension(OptionalImportEnumExtension)); + Assert.IsNull(message.GetExtension(OptionalImportMessageExtension)); + Assert.AreEqual(0, message.GetExtension(OptionalInt32Extension)); + Assert.AreEqual(0L, message.GetExtension(OptionalInt64Extension)); + Assert.AreEqual(Proto2.TestAllTypes.Types.NestedEnum.Foo, message.GetExtension(OptionalNestedEnumExtension)); + Assert.IsNull(message.GetExtension(OptionalNestedMessageExtension)); + Assert.IsNull(message.GetExtension(OptionalPublicImportMessageExtension)); + Assert.AreEqual(0, message.GetExtension(OptionalSfixed32Extension)); + Assert.AreEqual(0L, message.GetExtension(OptionalSfixed64Extension)); + Assert.AreEqual(0, message.GetExtension(OptionalSint32Extension)); + Assert.AreEqual(0L, message.GetExtension(OptionalSint64Extension)); + Assert.AreEqual("", message.GetExtension(OptionalStringExtension)); + Assert.AreEqual(0U, message.GetExtension(OptionalUint32Extension)); + Assert.AreEqual(0UL, message.GetExtension(OptionalUint64Extension)); + + // Repeated fields + Assert.IsNull(message.GetExtension(RepeatedBoolExtension)); + Assert.IsNull(message.GetExtension(RepeatedBytesExtension)); + Assert.IsNull(message.GetExtension(RepeatedDoubleExtension)); + Assert.IsNull(message.GetExtension(RepeatedFixed32Extension)); + Assert.IsNull(message.GetExtension(RepeatedFixed64Extension)); + Assert.IsNull(message.GetExtension(RepeatedFloatExtension)); + Assert.IsNull(message.GetExtension(RepeatedForeignEnumExtension)); + Assert.IsNull(message.GetExtension(RepeatedForeignMessageExtension)); + Assert.IsNull(message.GetExtension(RepeatedImportEnumExtension)); + Assert.IsNull(message.GetExtension(RepeatedImportMessageExtension)); + Assert.IsNull(message.GetExtension(RepeatedNestedEnumExtension)); + Assert.IsNull(message.GetExtension(RepeatedNestedMessageExtension)); + Assert.IsNull(message.GetExtension(RepeatedSfixed32Extension)); + Assert.IsNull(message.GetExtension(RepeatedSfixed64Extension)); + Assert.IsNull(message.GetExtension(RepeatedSint32Extension)); + Assert.IsNull(message.GetExtension(RepeatedSint64Extension)); + Assert.IsNull(message.GetExtension(RepeatedStringExtension)); + Assert.IsNull(message.GetExtension(RepeatedUint32Extension)); + Assert.IsNull(message.GetExtension(RepeatedUint64Extension)); + + // Oneof fields + Assert.AreEqual(0, message.GetExtension(OneofUint32Extension)); + Assert.AreEqual("", message.GetExtension(OneofStringExtension)); + Assert.AreEqual(ByteString.Empty, message.GetExtension(OneofBytesExtension)); + Assert.IsNull(message.GetExtension(OneofNestedMessageExtension)); + + Assert.AreEqual(true, message.GetExtension(DefaultBoolExtension)); + Assert.AreEqual(ByteString.CopyFromUtf8("world"), message.GetExtension(DefaultBytesExtension)); + Assert.AreEqual("123", message.GetExtension(DefaultCordExtension)); + Assert.AreEqual(52e3, message.GetExtension(DefaultDoubleExtension)); + Assert.AreEqual(47, message.GetExtension(DefaultFixed32Extension)); + Assert.AreEqual(48, message.GetExtension(DefaultFixed64Extension)); + Assert.AreEqual(51.5, message.GetExtension(DefaultFloatExtension)); + Assert.AreEqual(ForeignEnum.ForeignBar, message.GetExtension(DefaultForeignEnumExtension)); + Assert.AreEqual(ImportEnum.ImportBar, message.GetExtension(DefaultImportEnumExtension)); + Assert.AreEqual(41, message.GetExtension(DefaultInt32Extension)); + Assert.AreEqual(42, message.GetExtension(DefaultInt64Extension)); + Assert.AreEqual(Proto2.TestAllTypes.Types.NestedEnum.Bar, message.GetExtension(DefaultNestedEnumExtension)); + Assert.AreEqual(49, message.GetExtension(DefaultSfixed32Extension)); + Assert.AreEqual(-50, message.GetExtension(DefaultSfixed64Extension)); + Assert.AreEqual(-45, message.GetExtension(DefaultSint32Extension)); + Assert.AreEqual(46, message.GetExtension(DefaultSint64Extension)); + Assert.AreEqual("hello", message.GetExtension(DefaultStringExtension)); + Assert.AreEqual("abc", message.GetExtension(DefaultStringPieceExtension)); + Assert.AreEqual(43, message.GetExtension(DefaultUint32Extension)); + Assert.AreEqual(44, message.GetExtension(DefaultUint64Extension)); + + Assert.False(message.HasExtension(DefaultBoolExtension)); + Assert.False(message.HasExtension(DefaultBytesExtension)); + Assert.False(message.HasExtension(DefaultCordExtension)); + Assert.False(message.HasExtension(DefaultDoubleExtension)); + Assert.False(message.HasExtension(DefaultFixed32Extension)); + Assert.False(message.HasExtension(DefaultFixed64Extension)); + Assert.False(message.HasExtension(DefaultFloatExtension)); + Assert.False(message.HasExtension(DefaultForeignEnumExtension)); + Assert.False(message.HasExtension(DefaultImportEnumExtension)); + Assert.False(message.HasExtension(DefaultInt32Extension)); + Assert.False(message.HasExtension(DefaultInt64Extension)); + Assert.False(message.HasExtension(DefaultNestedEnumExtension)); + Assert.False(message.HasExtension(DefaultSfixed32Extension)); + Assert.False(message.HasExtension(DefaultSfixed64Extension)); + Assert.False(message.HasExtension(DefaultSint32Extension)); + Assert.False(message.HasExtension(DefaultSint64Extension)); + Assert.False(message.HasExtension(DefaultStringExtension)); + Assert.False(message.HasExtension(DefaultStringPieceExtension)); + Assert.False(message.HasExtension(DefaultUint32Extension)); + Assert.False(message.HasExtension(DefaultUint64Extension)); + } + + [Test] + public void FieldPresence() + { + var message = new TestAllTypes(); + + Assert.False(message.HasOptionalBool); + Assert.False(message.OptionalBool); + + message.OptionalBool = true; + + Assert.True(message.HasOptionalBool); + Assert.True(message.OptionalBool); + + message.OptionalBool = false; + + Assert.True(message.HasOptionalBool); + Assert.False(message.OptionalBool); + + message.ClearOptionalBool(); + + Assert.False(message.HasOptionalBool); + Assert.False(message.OptionalBool); + + Assert.False(message.HasDefaultBool); + Assert.True(message.DefaultBool); + + message.DefaultBool = false; + + Assert.True(message.HasDefaultBool); + Assert.False(message.DefaultBool); + + message.DefaultBool = true; + + Assert.True(message.HasDefaultBool); + Assert.True(message.DefaultBool); + + message.ClearDefaultBool(); + + Assert.False(message.HasDefaultBool); + Assert.True(message.DefaultBool); + } + + [Test] + public void RequiredFields() + { + var message = new TestRequired(); + Assert.False(message.IsInitialized()); + + message.A = 1; + message.B = 2; + message.C = 3; + + Assert.True(message.IsInitialized()); + } + + /// + /// Code was accidentally left in message parser that threw exceptions when missing required fields after parsing. + /// We've decided to not throw exceptions on missing fields, instead leaving it up to the consumer how they + /// want to check and handle missing fields. + /// + [Test] + public void RequiredFieldsNoThrow() + { + Assert.DoesNotThrow(() => MessageParsingHelpers.AssertReadingMessage(TestRequired.Parser, new byte[0], m => { })); + Assert.DoesNotThrow(() => MessageParsingHelpers.AssertReadingMessage(TestRequired.Parser as MessageParser, new byte[0], m => { })); + } + + [Test] + public void RequiredFieldsInExtensions() + { + var message = new TestAllExtensions(); + Assert.True(message.IsInitialized()); + + message.SetExtension(TestRequired.Extensions.Single, new TestRequired()); + + Assert.False(message.IsInitialized()); + + var extensionMessage = message.GetExtension(TestRequired.Extensions.Single); + extensionMessage.A = 1; + extensionMessage.B = 2; + extensionMessage.C = 3; + + Assert.True(message.IsInitialized()); + + message.GetOrInitializeExtension(TestRequired.Extensions.Multi); + + Assert.True(message.IsInitialized()); + + message.GetExtension(TestRequired.Extensions.Multi).Add(new TestRequired()); + + Assert.False(message.IsInitialized()); + + extensionMessage = message.GetExtension(TestRequired.Extensions.Multi)[0]; + extensionMessage.A = 1; + extensionMessage.B = 2; + extensionMessage.C = 3; + + Assert.True(message.IsInitialized()); + + message.SetExtension(UnittestExtensions.OptionalBoolExtension, true); + + Assert.True(message.IsInitialized()); + + message.GetOrInitializeExtension(UnittestExtensions.RepeatedBoolExtension).Add(true); + + Assert.True(message.IsInitialized()); + } + + [Test] + public void RequiredFieldInNestedMessageMapValue() + { + var message = new TestRequiredMap(); + message.Foo.Add(0, new TestRequiredMap.Types.NestedMessage()); + + Assert.False(message.IsInitialized()); + + message.Foo[0].RequiredInt32 = 12; + + Assert.True(message.IsInitialized()); + } + + [Test] + public void RoundTrip_Groups() + { + var message = new TestAllTypes + { + OptionalGroup = new TestAllTypes.Types.OptionalGroup + { + A = 10 + }, + RepeatedGroup = + { + new TestAllTypes.Types.RepeatedGroup { A = 10 }, + new TestAllTypes.Types.RepeatedGroup { A = 20 }, + new TestAllTypes.Types.RepeatedGroup { A = 30 } + } + }; + + MessageParsingHelpers.AssertWritingMessage(message); + + MessageParsingHelpers.AssertRoundtrip(Proto2.TestAllTypes.Parser, message); + } + + [Test] + public void RoundTrip_ExtensionGroups() + { + var message = new TestAllExtensions(); + message.SetExtension(UnittestExtensions.OptionalGroupExtension, new OptionalGroup_extension { A = 10 }); + message.GetOrInitializeExtension(UnittestExtensions.RepeatedGroupExtension).AddRange(new[] + { + new RepeatedGroup_extension { A = 10 }, + new RepeatedGroup_extension { A = 20 }, + new RepeatedGroup_extension { A = 30 } + }); + + MessageParsingHelpers.AssertWritingMessage(message); + + MessageParsingHelpers.AssertRoundtrip( + TestAllExtensions.Parser.WithExtensionRegistry(new ExtensionRegistry() { UnittestExtensions.OptionalGroupExtension, UnittestExtensions.RepeatedGroupExtension }), + message); + } + + [Test] + public void RoundTrip_NestedExtensionGroup() + { + var message = new TestGroupExtension(); + message.SetExtension(TestNestedExtension.Extensions.OptionalGroupExtension, new TestNestedExtension.Types.OptionalGroup_extension { A = 10 }); + + MessageParsingHelpers.AssertWritingMessage(message); + + MessageParsingHelpers.AssertRoundtrip( + TestGroupExtension.Parser.WithExtensionRegistry(new ExtensionRegistry() { TestNestedExtension.Extensions.OptionalGroupExtension }), + message); + } + + [Test] + public void RoundTrip_ParseUsingCodedInput() + { + var message = new TestAllExtensions(); + message.SetExtension(UnittestExtensions.OptionalBoolExtension, true); + byte[] bytes = message.ToByteArray(); + using (CodedInputStream input = new CodedInputStream(bytes)) + { + var parsed = TestAllExtensions.Parser.WithExtensionRegistry(new ExtensionRegistry() { UnittestExtensions.OptionalBoolExtension }).ParseFrom(input); + Assert.AreEqual(message, parsed); + } + } + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/SampleNaNs.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/SampleNaNs.cs new file mode 100644 index 0000000..34019ac --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/SampleNaNs.cs @@ -0,0 +1,53 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2017 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. +#endregion + +using System; + +namespace Google.Protobuf +{ + /// + /// Samples of different not-a-number values, for testing equality comparisons. + /// + public static class SampleNaNs + { + public static double Regular { get; } = double.NaN; + + // Signalling bit is inverted compared with double.NaN. Doesn't really matter + // whether that makes it quiet or signalling - it's different. + public static double SignallingFlipped { get; } = + BitConverter.Int64BitsToDouble(BitConverter.DoubleToInt64Bits(double.NaN) ^ -0x8000_0000_0000_0000L); + + // A bit in the middle of the mantissa is flipped; this difference is preserved when casting to float. + public static double PayloadFlipped { get; } = + BitConverter.Int64BitsToDouble(BitConverter.DoubleToInt64Bits(double.NaN) ^ 0x1_0000_0000L); + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/TestCornerCases.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/TestCornerCases.cs new file mode 100644 index 0000000..248f5fa --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/TestCornerCases.cs @@ -0,0 +1,62 @@ +#region Copyright notice and license +// 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. +#endregion + +using UnitTest.Issues.TestProtos; +using NUnit.Framework; + +namespace Google.Protobuf +{ + public class TestCornerCases + { + [Test] + public void TestRoundTripNegativeEnums() + { + NegativeEnumMessage msg = new NegativeEnumMessage + { + Value = NegativeEnum.MinusOne, + Values = { NegativeEnum.Zero, NegativeEnum.MinusOne, NegativeEnum.FiveBelow }, + PackedValues = { NegativeEnum.Zero, NegativeEnum.MinusOne, NegativeEnum.FiveBelow } + }; + + Assert.AreEqual(58, msg.CalculateSize()); + + byte[] bytes = new byte[58]; + CodedOutputStream output = new CodedOutputStream(bytes); + + msg.WriteTo(output); + Assert.AreEqual(0, output.SpaceLeft); + + NegativeEnumMessage copy = NegativeEnumMessage.Parser.ParseFrom(bytes); + Assert.AreEqual(msg, copy); + } + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/WellKnownTypes/DurationTest.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/WellKnownTypes/DurationTest.cs new file mode 100644 index 0000000..141faf8 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/WellKnownTypes/DurationTest.cs @@ -0,0 +1,132 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using NUnit.Framework; +using System; + +namespace Google.Protobuf.WellKnownTypes +{ + public class DurationTest + { + [Test] + public void ToTimeSpan() + { + Assert.AreEqual(TimeSpan.FromSeconds(1), new Duration { Seconds = 1 }.ToTimeSpan()); + Assert.AreEqual(TimeSpan.FromSeconds(-1), new Duration { Seconds = -1 }.ToTimeSpan()); + Assert.AreEqual(TimeSpan.FromMilliseconds(1), new Duration { Nanos = 1000000 }.ToTimeSpan()); + Assert.AreEqual(TimeSpan.FromMilliseconds(-1), new Duration { Nanos = -1000000 }.ToTimeSpan()); + Assert.AreEqual(TimeSpan.FromTicks(1), new Duration { Nanos = 100 }.ToTimeSpan()); + Assert.AreEqual(TimeSpan.FromTicks(-1), new Duration { Nanos = -100 }.ToTimeSpan()); + + // Rounding is towards 0 + Assert.AreEqual(TimeSpan.FromTicks(2), new Duration { Nanos = 250 }.ToTimeSpan()); + Assert.AreEqual(TimeSpan.FromTicks(-2), new Duration { Nanos = -250 }.ToTimeSpan()); + } + + [Test] + public void Addition() + { + Assert.AreEqual(new Duration { Seconds = 2, Nanos = 100000000 }, + new Duration { Seconds = 1, Nanos = 600000000 } + new Duration { Nanos = 500000000 }); + Assert.AreEqual(new Duration { Seconds = -2, Nanos = -100000000 }, + new Duration { Seconds = -1, Nanos = -600000000 } + new Duration { Nanos = -500000000 }); + Assert.AreEqual(new Duration { Seconds = 1, Nanos = 100000000 }, + new Duration { Seconds = 1, Nanos = 600000000 } + new Duration { Nanos = -500000000 }); + + // Non-normalized durations, or non-normalized intermediate results + Assert.AreEqual(new Duration { Seconds = 1 }, + new Duration { Seconds = 1, Nanos = -500000000 } + new Duration { Nanos = 500000000 }); + + Assert.AreEqual(new Duration { Nanos = -900000000 }, + new Duration { Seconds = -1, Nanos = -100000000 } + new Duration { Nanos = 200000000 }); + Assert.AreEqual(new Duration { Nanos = 900000000 }, + new Duration { Seconds = 1, Nanos = 100000000 } + new Duration { Nanos = -200000000 }); + } + + [Test] + public void Subtraction() + { + Assert.AreEqual(new Duration { Seconds = 1, Nanos = 100000000 }, + new Duration { Seconds = 1, Nanos = 600000000 } - new Duration { Nanos = 500000000 }); + Assert.AreEqual(new Duration { Seconds = -1, Nanos = -100000000 }, + new Duration { Seconds = -1, Nanos = -600000000 } - new Duration { Nanos = -500000000 }); + Assert.AreEqual(new Duration { Seconds = 2, Nanos = 100000000 }, + new Duration { Seconds = 1, Nanos = 600000000 } - new Duration { Nanos = -500000000 }); + + // Non-normalized durations + Assert.AreEqual(new Duration(), + new Duration { Seconds = 1, Nanos = -500000000 } - new Duration { Nanos = 500000000 }); + Assert.AreEqual(new Duration { Seconds = 1 }, + new Duration { Nanos = 2000000000 } - new Duration { Nanos = 1000000000 }); + } + + [Test] + public void FromTimeSpan() + { + Assert.AreEqual(new Duration { Seconds = 1 }, Duration.FromTimeSpan(TimeSpan.FromSeconds(1))); + Assert.AreEqual(new Duration { Nanos = Duration.NanosecondsPerTick }, Duration.FromTimeSpan(TimeSpan.FromTicks(1))); + } + + [Test] + [TestCase(0, Duration.MaxNanoseconds + 1)] + [TestCase(0, Duration.MinNanoseconds - 1)] + [TestCase(Duration.MinSeconds - 1, 0)] + [TestCase(Duration.MaxSeconds + 1, 0)] + [TestCase(1, -1)] + [TestCase(-1, 1)] + public void ToTimeSpan_Invalid(long seconds, int nanoseconds) + { + var duration = new Duration { Seconds = seconds, Nanos = nanoseconds }; + Assert.Throws(() => duration.ToTimeSpan()); + } + + [Test] + [TestCase(0, Duration.MaxNanoseconds)] + [TestCase(0, Duration.MinNanoseconds)] + [TestCase(Duration.MinSeconds, Duration.MinNanoseconds)] + [TestCase(Duration.MaxSeconds, Duration.MaxNanoseconds)] + public void ToTimeSpan_Valid(long seconds, int nanoseconds) + { + // Only testing that these values don't throw, unlike their similar tests in ToTimeSpan_Invalid + var duration = new Duration { Seconds = seconds, Nanos = nanoseconds }; + duration.ToTimeSpan(); + } + + [Test] + public void ToString_NonNormalized() + { + // Just a single example should be sufficient... + var duration = new Duration { Seconds = 1, Nanos = -1 }; + Assert.AreEqual("{ \"@warning\": \"Invalid Duration\", \"seconds\": \"1\", \"nanos\": -1 }", duration.ToString()); + } + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/WellKnownTypes/FieldMaskTest.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/WellKnownTypes/FieldMaskTest.cs new file mode 100644 index 0000000..5dc5035 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf.Test/WellKnownTypes/FieldMaskTest.cs @@ -0,0 +1,245 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2016 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. +#endregion + +using System; +using Google.Protobuf.TestProtos; +using NUnit.Framework; + +namespace Google.Protobuf.WellKnownTypes +{ + public class FieldMaskTest + { + [Test] + [TestCase("foo__bar")] + [TestCase("foo_3_ar")] + [TestCase("fooBar")] + public void ToString_Invalid(string input) + { + var mask = new FieldMask { Paths = { input } }; + var text = mask.ToString(); + // More specific test below + Assert.That(text, Does.Contain("@warning")); + Assert.That(text, Does.Contain(input)); + } + + [Test] + public void ToString_Invalid_Precise() + { + var mask = new FieldMask { Paths = { "x", "foo__bar", @"x\y" } }; + Assert.AreEqual( + "{ \"@warning\": \"Invalid FieldMask\", \"paths\": [ \"x\", \"foo__bar\", \"x\\\\y\" ] }", + mask.ToString()); + } + + [Test] + public void IsValid() + { + Assert.IsTrue(FieldMask.IsValid("payload")); + Assert.IsFalse(FieldMask.IsValid("nonexist")); + Assert.IsTrue(FieldMask.IsValid("payload.single_int32")); + Assert.IsTrue(FieldMask.IsValid("payload.repeated_int32")); + Assert.IsTrue(FieldMask.IsValid("payload.single_nested_message")); + Assert.IsTrue(FieldMask.IsValid("payload.repeated_nested_message")); + Assert.IsFalse(FieldMask.IsValid("payload.nonexist")); + + Assert.IsTrue(FieldMask.IsValid(FieldMask.FromString("payload"))); + Assert.IsFalse(FieldMask.IsValid(FieldMask.FromString("nonexist"))); + Assert.IsFalse(FieldMask.IsValid(FieldMask.FromString("payload,nonexist"))); + + Assert.IsTrue(FieldMask.IsValid(NestedTestAllTypes.Descriptor, "payload")); + Assert.IsFalse(FieldMask.IsValid(NestedTestAllTypes.Descriptor, "nonexist")); + + Assert.IsTrue(FieldMask.IsValid(NestedTestAllTypes.Descriptor, FieldMask.FromString("payload"))); + Assert.IsFalse(FieldMask.IsValid(NestedTestAllTypes.Descriptor, FieldMask.FromString("nonexist"))); + + Assert.IsTrue(FieldMask.IsValid("payload.single_nested_message.bb")); + + // Repeated fields cannot have sub-paths. + Assert.IsFalse(FieldMask.IsValid("payload.repeated_nested_message.bb")); + + // Non-message fields cannot have sub-paths. + Assert.IsFalse(FieldMask.IsValid("payload.single_int32.bb")); + } + + [Test] + [TestCase(new string[] { }, "\"\"")] + [TestCase(new string[] { "foo" }, "\"foo\"")] + [TestCase(new string[] { "foo", "bar" }, "\"foo,bar\"")] + [TestCase(new string[] { "", "foo", "", "bar", "" }, "\",foo,,bar,\"")] + public void ToString(string[] input, string expectedOutput) + { + FieldMask mask = new FieldMask(); + mask.Paths.AddRange(input); + Assert.AreEqual(expectedOutput, mask.ToString()); + } + + [Test] + [TestCase("", new string[] { })] + [TestCase("foo", new string[] { "foo" })] + [TestCase("foo,bar.baz", new string[] { "foo", "bar.baz" })] + [TestCase(",foo,,bar,", new string[] { "foo", "bar" })] + public void FromString(string input, string[] expectedOutput) + { + FieldMask mask = FieldMask.FromString(input); + Assert.AreEqual(expectedOutput.Length, mask.Paths.Count); + for (int i = 0; i < expectedOutput.Length; i++) + { + Assert.AreEqual(expectedOutput[i], mask.Paths[i]); + } + } + + [Test] + public void FromString_Validated() + { + // Check whether the field paths are valid if a class parameter is provided. + Assert.DoesNotThrow(() => FieldMask.FromString(",payload")); + Assert.Throws(() => FieldMask.FromString("payload,nonexist")); + } + + [Test] + [TestCase(new int[] { }, new string[] { })] + [TestCase(new int[] { TestAllTypes.SingleInt32FieldNumber }, new string[] { "single_int32" })] + [TestCase(new int[] { TestAllTypes.SingleInt32FieldNumber, TestAllTypes.SingleInt64FieldNumber }, new string[] { "single_int32", "single_int64" })] + public void FromFieldNumbers(int[] input, string[] expectedOutput) + { + FieldMask mask = FieldMask.FromFieldNumbers(input); + Assert.AreEqual(expectedOutput.Length, mask.Paths.Count); + for (int i = 0; i < expectedOutput.Length; i++) + { + Assert.AreEqual(expectedOutput[i], mask.Paths[i]); + } + } + + [Test] + public void FromFieldNumbers_Invalid() + { + Assert.Throws(() => + { + int invalidFieldNumber = 1000; + FieldMask.FromFieldNumbers(invalidFieldNumber); + }); + } + + [Test] + [TestCase(new string[] { }, "\"\"")] + [TestCase(new string[] { "foo" }, "\"foo\"")] + [TestCase(new string[] { "foo", "bar" }, "\"foo,bar\"")] + [TestCase(new string[] { "", "foo", "", "bar", "" }, "\",foo,bar\"")] + public void Normalize(string[] input, string expectedOutput) + { + FieldMask mask = new FieldMask(); + mask.Paths.AddRange(input); + FieldMask result = mask.Normalize(); + Assert.AreEqual(expectedOutput, result.ToString()); + } + + [Test] + public void Union() + { + // Only test a simple case here and expect + // {@link FieldMaskTreeTest#AddFieldPath} to cover all scenarios. + FieldMask mask1 = FieldMask.FromString("foo,bar.baz,bar.quz"); + FieldMask mask2 = FieldMask.FromString("foo.bar,bar"); + FieldMask result = mask1.Union(mask2); + Assert.AreEqual(2, result.Paths.Count); + Assert.Contains("bar", result.Paths); + Assert.Contains("foo", result.Paths); + Assert.That(result.Paths, Has.No.Member("bar.baz")); + Assert.That(result.Paths, Has.No.Member("bar.quz")); + Assert.That(result.Paths, Has.No.Member("foo.bar")); + } + + [Test] + public void Union_UsingVarArgs() + { + FieldMask mask1 = FieldMask.FromString("foo"); + FieldMask mask2 = FieldMask.FromString("foo.bar,bar.quz"); + FieldMask mask3 = FieldMask.FromString("bar.quz"); + FieldMask mask4 = FieldMask.FromString("bar"); + FieldMask result = mask1.Union(mask2, mask3, mask4); + Assert.AreEqual(2, result.Paths.Count); + Assert.Contains("bar", result.Paths); + Assert.Contains("foo", result.Paths); + Assert.That(result.Paths, Has.No.Member("foo.bar")); + Assert.That(result.Paths, Has.No.Member("bar.quz")); + } + + [Test] + public void Intersection() + { + // Only test a simple case here and expect + // {@link FieldMaskTreeTest#IntersectFieldPath} to cover all scenarios. + FieldMask mask1 = FieldMask.FromString("foo,bar.baz,bar.quz"); + FieldMask mask2 = FieldMask.FromString("foo.bar,bar"); + FieldMask result = mask1.Intersection(mask2); + Assert.AreEqual(3, result.Paths.Count); + Assert.Contains("foo.bar", result.Paths); + Assert.Contains("bar.baz", result.Paths); + Assert.Contains("bar.quz", result.Paths); + Assert.That(result.Paths, Has.No.Member("foo")); + Assert.That(result.Paths, Has.No.Member("bar")); + } + + [Test] + public void Merge() + { + // Only test a simple case here and expect + // {@link FieldMaskTreeTest#Merge} to cover all scenarios. + FieldMask fieldMask = FieldMask.FromString("payload"); + NestedTestAllTypes source = new NestedTestAllTypes + { + Payload = new TestAllTypes + { + SingleInt32 = 1234, + SingleFixed64 = 4321 + } + }; + NestedTestAllTypes destination = new NestedTestAllTypes(); + fieldMask.Merge(source, destination); + Assert.AreEqual(1234, destination.Payload.SingleInt32); + Assert.AreEqual(4321, destination.Payload.SingleFixed64); + + destination = new NestedTestAllTypes + { + Payload = new TestAllTypes + { + SingleInt32 = 4321, + SingleInt64 = 5678 + } + }; + fieldMask.Merge(source, destination); + Assert.AreEqual(1234, destination.Payload.SingleInt32); + Assert.AreEqual(5678, destination.Payload.SingleInt64); + Assert.AreEqual(4321, destination.Payload.SingleFixed64); + } + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/ByteArray.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/ByteArray.cs new file mode 100644 index 0000000..69b6ef8 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/ByteArray.cs @@ -0,0 +1,79 @@ +#region Copyright notice and license +// 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. +#endregion + +using System; + +namespace Google.Protobuf +{ + /// + /// Provides a utility routine to copy small arrays much more quickly than Buffer.BlockCopy + /// + internal static class ByteArray + { + /// + /// The threshold above which you should use Buffer.BlockCopy rather than ByteArray.Copy + /// + private const int CopyThreshold = 12; + + /// + /// Determines which copy routine to use based on the number of bytes to be copied. + /// + internal static void Copy(byte[] src, int srcOffset, byte[] dst, int dstOffset, int count) + { + if (count > CopyThreshold) + { + Buffer.BlockCopy(src, srcOffset, dst, dstOffset, count); + } + else + { + int stop = srcOffset + count; + for (int i = srcOffset; i < stop; i++) + { + dst[dstOffset++] = src[i]; + } + } + } + + /// + /// Reverses the order of bytes in the array + /// + internal static void Reverse(byte[] bytes) + { + for (int first = 0, last = bytes.Length - 1; first < last; first++, last--) + { + byte temp = bytes[first]; + bytes[first] = bytes[last]; + bytes[last] = temp; + } + } + } +} \ No newline at end of file diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Collections/ProtobufEqualityComparers.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Collections/ProtobufEqualityComparers.cs new file mode 100644 index 0000000..13ef60f --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Collections/ProtobufEqualityComparers.cs @@ -0,0 +1,130 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2017 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. +#endregion + +using System; +using System.Collections.Generic; + +namespace Google.Protobuf.Collections +{ + /// + /// Provides a central place to implement equality comparisons, primarily for bitwise float/double equality. + /// + public static class ProtobufEqualityComparers + { + /// + /// Returns an equality comparer for suitable for Protobuf equality comparisons. + /// This is usually just the default equality comparer for the type, but floating point numbers are compared + /// bitwise. + /// + /// The type of equality comparer to return. + /// The equality comparer. + public static EqualityComparer GetEqualityComparer() + { + return typeof(T) == typeof(double) ? (EqualityComparer) (object) BitwiseDoubleEqualityComparer + : typeof(T) == typeof(float) ? (EqualityComparer) (object) BitwiseSingleEqualityComparer + : typeof(T) == typeof(double?) ? (EqualityComparer) (object) BitwiseNullableDoubleEqualityComparer + : typeof(T) == typeof(float?) ? (EqualityComparer) (object) BitwiseNullableSingleEqualityComparer + : EqualityComparer.Default; + } + + /// + /// Returns an equality comparer suitable for comparing 64-bit floating point values, by bitwise comparison. + /// (NaN values are considered equal, but only when they have the same representation.) + /// + public static EqualityComparer BitwiseDoubleEqualityComparer { get; } = new BitwiseDoubleEqualityComparerImpl(); + + /// + /// Returns an equality comparer suitable for comparing 32-bit floating point values, by bitwise comparison. + /// (NaN values are considered equal, but only when they have the same representation.) + /// + public static EqualityComparer BitwiseSingleEqualityComparer { get; } = new BitwiseSingleEqualityComparerImpl(); + + /// + /// Returns an equality comparer suitable for comparing nullable 64-bit floating point values, by bitwise comparison. + /// (NaN values are considered equal, but only when they have the same representation.) + /// + public static EqualityComparer BitwiseNullableDoubleEqualityComparer { get; } = new BitwiseNullableDoubleEqualityComparerImpl(); + + /// + /// Returns an equality comparer suitable for comparing nullable 32-bit floating point values, by bitwise comparison. + /// (NaN values are considered equal, but only when they have the same representation.) + /// + public static EqualityComparer BitwiseNullableSingleEqualityComparer { get; } = new BitwiseNullableSingleEqualityComparerImpl(); + + private class BitwiseDoubleEqualityComparerImpl : EqualityComparer + { + public override bool Equals(double x, double y) => + BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y); + + public override int GetHashCode(double obj) => + BitConverter.DoubleToInt64Bits(obj).GetHashCode(); + } + + private class BitwiseSingleEqualityComparerImpl : EqualityComparer + { + // Just promote values to double and use BitConverter.DoubleToInt64Bits, + // as there's no BitConverter.SingleToInt32Bits, unfortunately. + + public override bool Equals(float x, float y) => + BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y); + + public override int GetHashCode(float obj) => + BitConverter.DoubleToInt64Bits(obj).GetHashCode(); + } + + private class BitwiseNullableDoubleEqualityComparerImpl : EqualityComparer + { + public override bool Equals(double? x, double? y) => + x == null && y == null ? true + : x == null || y == null ? false + : BitwiseDoubleEqualityComparer.Equals(x.Value, y.Value); + + // The hash code for null is just a constant which is at least *unlikely* to be used + // elsewhere. (Compared with 0, say.) + public override int GetHashCode(double? obj) => + obj == null ? 293864 : BitwiseDoubleEqualityComparer.GetHashCode(obj.Value); + } + + private class BitwiseNullableSingleEqualityComparerImpl : EqualityComparer + { + public override bool Equals(float? x, float? y) => + x == null && y == null ? true + : x == null || y == null ? false + : BitwiseSingleEqualityComparer.Equals(x.Value, y.Value); + + // The hash code for null is just a constant which is at least *unlikely* to be used + // elsewhere. (Compared with 0, say.) + public override int GetHashCode(float? obj) => + obj == null ? 293864 : BitwiseSingleEqualityComparer.GetHashCode(obj.Value); + } + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Compatibility/MethodInfoExtensions.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Compatibility/MethodInfoExtensions.cs new file mode 100644 index 0000000..7b946cb --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Compatibility/MethodInfoExtensions.cs @@ -0,0 +1,47 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2017 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. +#endregion + +#if NET35 +using System; +using System.Reflection; + +namespace Google.Protobuf.Compatibility +{ + // .NET Core (at least netstandard1.0) doesn't have Delegate.CreateDelegate, and .NET 3.5 doesn't have + // MethodInfo.CreateDelegate. Proxy from one to the other on .NET 3.5... + internal static class MethodInfoExtensions + { + internal static Delegate CreateDelegate(this MethodInfo method, Type type) => + Delegate.CreateDelegate(type, method); + } +} +#endif diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Extension.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Extension.cs new file mode 100644 index 0000000..6dd1cea --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Extension.cs @@ -0,0 +1,119 @@ +#region Copyright notice and license +// 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. +#endregion + +using System; + +namespace Google.Protobuf +{ + /// + /// Represents a non-generic extension definition. This API is experimental and subject to change. + /// + public abstract class Extension + { + internal abstract Type TargetType { get; } + + /// + /// Internal use. Creates a new extension with the specified field number. + /// + protected Extension(int fieldNumber) + { + FieldNumber = fieldNumber; + } + + internal abstract IExtensionValue CreateValue(); + + /// + /// Gets the field number of this extension + /// + public int FieldNumber { get; } + + internal abstract bool IsRepeated { get; } + } + + /// + /// Represents a type-safe extension identifier used for getting and setting single extension values in instances. + /// This API is experimental and subject to change. + /// + /// The message type this field applies to + /// The field value type of this extension + public sealed class Extension : Extension where TTarget : IExtendableMessage + { + private readonly FieldCodec codec; + + /// + /// Creates a new extension identifier with the specified field number and codec + /// + public Extension(int fieldNumber, FieldCodec codec) : base(fieldNumber) + { + this.codec = codec; + } + + internal TValue DefaultValue => codec.DefaultValue; + + internal override Type TargetType => typeof(TTarget); + + internal override bool IsRepeated => false; + + internal override IExtensionValue CreateValue() + { + return new ExtensionValue(codec); + } + } + + /// + /// Represents a type-safe extension identifier used for getting repeated extension values in instances. + /// This API is experimental and subject to change. + /// + /// The message type this field applies to + /// The repeated field value type of this extension + public sealed class RepeatedExtension : Extension where TTarget : IExtendableMessage + { + private readonly FieldCodec codec; + + /// + /// Creates a new repeated extension identifier with the specified field number and codec + /// + public RepeatedExtension(int fieldNumber, FieldCodec codec) : base(fieldNumber) + { + this.codec = codec; + } + + internal override Type TargetType => typeof(TTarget); + + internal override bool IsRepeated => true; + + internal override IExtensionValue CreateValue() + { + return new RepeatedExtensionValue(codec); + } + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/FieldCodec.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/FieldCodec.cs new file mode 100644 index 0000000..ee6bd6a --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/FieldCodec.cs @@ -0,0 +1,887 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using Google.Protobuf.Collections; +using Google.Protobuf.Compatibility; +using Google.Protobuf.WellKnownTypes; +using System; +using System.Collections.Generic; +using System.Security; + +namespace Google.Protobuf +{ + /// + /// Factory methods for . + /// + public static class FieldCodec + { + // TODO: Avoid the "dual hit" of lambda expressions: create open delegates instead. (At least test...) + + /// + /// Retrieves a codec suitable for a string field with the given tag. + /// + /// The tag. + /// A codec for the given tag. + public static FieldCodec ForString(uint tag) + { + return FieldCodec.ForString(tag, ""); + } + + /// + /// Retrieves a codec suitable for a bytes field with the given tag. + /// + /// The tag. + /// A codec for the given tag. + public static FieldCodec ForBytes(uint tag) + { + return FieldCodec.ForBytes(tag, ByteString.Empty); + } + + /// + /// Retrieves a codec suitable for a bool field with the given tag. + /// + /// The tag. + /// A codec for the given tag. + public static FieldCodec ForBool(uint tag) + { + return FieldCodec.ForBool(tag, false); + } + + /// + /// Retrieves a codec suitable for an int32 field with the given tag. + /// + /// The tag. + /// A codec for the given tag. + public static FieldCodec ForInt32(uint tag) + { + return FieldCodec.ForInt32(tag, 0); + } + + /// + /// Retrieves a codec suitable for an sint32 field with the given tag. + /// + /// The tag. + /// A codec for the given tag. + public static FieldCodec ForSInt32(uint tag) + { + return FieldCodec.ForSInt32(tag, 0); + } + + /// + /// Retrieves a codec suitable for a fixed32 field with the given tag. + /// + /// The tag. + /// A codec for the given tag. + public static FieldCodec ForFixed32(uint tag) + { + return FieldCodec.ForFixed32(tag, 0); + } + + /// + /// Retrieves a codec suitable for an sfixed32 field with the given tag. + /// + /// The tag. + /// A codec for the given tag. + public static FieldCodec ForSFixed32(uint tag) + { + return FieldCodec.ForSFixed32(tag, 0); + } + + /// + /// Retrieves a codec suitable for a uint32 field with the given tag. + /// + /// The tag. + /// A codec for the given tag. + public static FieldCodec ForUInt32(uint tag) + { + return FieldCodec.ForUInt32(tag, 0); + } + + /// + /// Retrieves a codec suitable for an int64 field with the given tag. + /// + /// The tag. + /// A codec for the given tag. + public static FieldCodec ForInt64(uint tag) + { + return FieldCodec.ForInt64(tag, 0); + } + + /// + /// Retrieves a codec suitable for an sint64 field with the given tag. + /// + /// The tag. + /// A codec for the given tag. + public static FieldCodec ForSInt64(uint tag) + { + return FieldCodec.ForSInt64(tag, 0); + } + + /// + /// Retrieves a codec suitable for a fixed64 field with the given tag. + /// + /// The tag. + /// A codec for the given tag. + public static FieldCodec ForFixed64(uint tag) + { + return FieldCodec.ForFixed64(tag, 0); + } + + /// + /// Retrieves a codec suitable for an sfixed64 field with the given tag. + /// + /// The tag. + /// A codec for the given tag. + public static FieldCodec ForSFixed64(uint tag) + { + return FieldCodec.ForSFixed64(tag, 0); + } + + /// + /// Retrieves a codec suitable for a uint64 field with the given tag. + /// + /// The tag. + /// A codec for the given tag. + public static FieldCodec ForUInt64(uint tag) + { + return FieldCodec.ForUInt64(tag, 0); + } + + /// + /// Retrieves a codec suitable for a float field with the given tag. + /// + /// The tag. + /// A codec for the given tag. + public static FieldCodec ForFloat(uint tag) + { + return FieldCodec.ForFloat(tag, 0); + } + + /// + /// Retrieves a codec suitable for a double field with the given tag. + /// + /// The tag. + /// A codec for the given tag. + public static FieldCodec ForDouble(uint tag) + { + return FieldCodec.ForDouble(tag, 0); + } + + // Enums are tricky. We can probably use expression trees to build these delegates automatically, + // but it's easy to generate the code for it. + + /// + /// Retrieves a codec suitable for an enum field with the given tag. + /// + /// The tag. + /// A conversion function from to the enum type. + /// A conversion function from the enum type to . + /// A codec for the given tag. + public static FieldCodec ForEnum(uint tag, Func toInt32, Func fromInt32) + { + return FieldCodec.ForEnum(tag, toInt32, fromInt32, default(T)); + } + + /// + /// Retrieves a codec suitable for a string field with the given tag. + /// + /// The tag. + /// The default value. + /// A codec for the given tag. + public static FieldCodec ForString(uint tag, string defaultValue) + { + return new FieldCodec((ref ParseContext ctx) => ctx.ReadString(), (ref WriteContext ctx, string value) => ctx.WriteString(value), CodedOutputStream.ComputeStringSize, tag, defaultValue); + } + + /// + /// Retrieves a codec suitable for a bytes field with the given tag. + /// + /// The tag. + /// The default value. + /// A codec for the given tag. + public static FieldCodec ForBytes(uint tag, ByteString defaultValue) + { + return new FieldCodec((ref ParseContext ctx) => ctx.ReadBytes(), (ref WriteContext ctx, ByteString value) => ctx.WriteBytes(value), CodedOutputStream.ComputeBytesSize, tag, defaultValue); + } + + /// + /// Retrieves a codec suitable for a bool field with the given tag. + /// + /// The tag. + /// The default value. + /// A codec for the given tag. + public static FieldCodec ForBool(uint tag, bool defaultValue) + { + return new FieldCodec((ref ParseContext ctx) => ctx.ReadBool(), (ref WriteContext ctx, bool value) => ctx.WriteBool(value), CodedOutputStream.BoolSize, tag, defaultValue); + } + + /// + /// Retrieves a codec suitable for an int32 field with the given tag. + /// + /// The tag. + /// The default value. + /// A codec for the given tag. + public static FieldCodec ForInt32(uint tag, int defaultValue) + { + return new FieldCodec((ref ParseContext ctx) => ctx.ReadInt32(), (ref WriteContext output, int value) => output.WriteInt32(value), CodedOutputStream.ComputeInt32Size, tag, defaultValue); + } + + /// + /// Retrieves a codec suitable for an sint32 field with the given tag. + /// + /// The tag. + /// The default value. + /// A codec for the given tag. + public static FieldCodec ForSInt32(uint tag, int defaultValue) + { + return new FieldCodec((ref ParseContext ctx) => ctx.ReadSInt32(), (ref WriteContext output, int value) => output.WriteSInt32(value), CodedOutputStream.ComputeSInt32Size, tag, defaultValue); + } + + /// + /// Retrieves a codec suitable for a fixed32 field with the given tag. + /// + /// The tag. + /// The default value. + /// A codec for the given tag. + public static FieldCodec ForFixed32(uint tag, uint defaultValue) + { + return new FieldCodec((ref ParseContext ctx) => ctx.ReadFixed32(), (ref WriteContext output, uint value) => output.WriteFixed32(value), 4, tag, defaultValue); + } + + /// + /// Retrieves a codec suitable for an sfixed32 field with the given tag. + /// + /// The tag. + /// The default value. + /// A codec for the given tag. + public static FieldCodec ForSFixed32(uint tag, int defaultValue) + { + return new FieldCodec((ref ParseContext ctx) => ctx.ReadSFixed32(), (ref WriteContext output, int value) => output.WriteSFixed32(value), 4, tag, defaultValue); + } + + /// + /// Retrieves a codec suitable for a uint32 field with the given tag. + /// + /// The tag. + /// The default value. + /// A codec for the given tag. + public static FieldCodec ForUInt32(uint tag, uint defaultValue) + { + return new FieldCodec((ref ParseContext ctx) => ctx.ReadUInt32(), (ref WriteContext output, uint value) => output.WriteUInt32(value), CodedOutputStream.ComputeUInt32Size, tag, defaultValue); + } + + /// + /// Retrieves a codec suitable for an int64 field with the given tag. + /// + /// The tag. + /// The default value. + /// A codec for the given tag. + public static FieldCodec ForInt64(uint tag, long defaultValue) + { + return new FieldCodec((ref ParseContext ctx) => ctx.ReadInt64(), (ref WriteContext output, long value) => output.WriteInt64(value), CodedOutputStream.ComputeInt64Size, tag, defaultValue); + } + + /// + /// Retrieves a codec suitable for an sint64 field with the given tag. + /// + /// The tag. + /// The default value. + /// A codec for the given tag. + public static FieldCodec ForSInt64(uint tag, long defaultValue) + { + return new FieldCodec((ref ParseContext ctx) => ctx.ReadSInt64(), (ref WriteContext output, long value) => output.WriteSInt64(value), CodedOutputStream.ComputeSInt64Size, tag, defaultValue); + } + + /// + /// Retrieves a codec suitable for a fixed64 field with the given tag. + /// + /// The tag. + /// The default value. + /// A codec for the given tag. + public static FieldCodec ForFixed64(uint tag, ulong defaultValue) + { + return new FieldCodec((ref ParseContext ctx) => ctx.ReadFixed64(), (ref WriteContext output, ulong value) => output.WriteFixed64(value), 8, tag, defaultValue); + } + + /// + /// Retrieves a codec suitable for an sfixed64 field with the given tag. + /// + /// The tag. + /// The default value. + /// A codec for the given tag. + public static FieldCodec ForSFixed64(uint tag, long defaultValue) + { + return new FieldCodec((ref ParseContext ctx) => ctx.ReadSFixed64(), (ref WriteContext output, long value) => output.WriteSFixed64(value), 8, tag, defaultValue); + } + + /// + /// Retrieves a codec suitable for a uint64 field with the given tag. + /// + /// The tag. + /// The default value. + /// A codec for the given tag. + public static FieldCodec ForUInt64(uint tag, ulong defaultValue) + { + return new FieldCodec((ref ParseContext ctx) => ctx.ReadUInt64(), (ref WriteContext output, ulong value) => output.WriteUInt64(value), CodedOutputStream.ComputeUInt64Size, tag, defaultValue); + } + + /// + /// Retrieves a codec suitable for a float field with the given tag. + /// + /// The tag. + /// The default value. + /// A codec for the given tag. + public static FieldCodec ForFloat(uint tag, float defaultValue) + { + return new FieldCodec((ref ParseContext ctx) => ctx.ReadFloat(), (ref WriteContext output, float value) => output.WriteFloat(value), CodedOutputStream.FloatSize, tag, defaultValue); + } + + /// + /// Retrieves a codec suitable for a double field with the given tag. + /// + /// The tag. + /// The default value. + /// A codec for the given tag. + public static FieldCodec ForDouble(uint tag, double defaultValue) + { + return new FieldCodec((ref ParseContext ctx) => ctx.ReadDouble(), (ref WriteContext output, double value) => output.WriteDouble(value), CodedOutputStream.DoubleSize, tag, defaultValue); + } + + // Enums are tricky. We can probably use expression trees to build these delegates automatically, + // but it's easy to generate the code for it. + + /// + /// Retrieves a codec suitable for an enum field with the given tag. + /// + /// The tag. + /// A conversion function from to the enum type. + /// A conversion function from the enum type to . + /// The default value. + /// A codec for the given tag. + public static FieldCodec ForEnum(uint tag, Func toInt32, Func fromInt32, T defaultValue) + { + return new FieldCodec((ref ParseContext ctx) => fromInt32( + ctx.ReadEnum()), + (ref WriteContext output, T value) => output.WriteEnum(toInt32(value)), + value => CodedOutputStream.ComputeEnumSize(toInt32(value)), tag, defaultValue); + } + + /// + /// Retrieves a codec suitable for a message field with the given tag. + /// + /// The tag. + /// A parser to use for the message type. + /// A codec for the given tag. + public static FieldCodec ForMessage(uint tag, MessageParser parser) where T : class, IMessage + { + return new FieldCodec( + (ref ParseContext ctx) => + { + T message = parser.CreateTemplate(); + ctx.ReadMessage(message); + return message; + }, + (ref WriteContext output, T value) => output.WriteMessage(value), + (ref ParseContext ctx, ref T v) => + { + if (v == null) + { + v = parser.CreateTemplate(); + } + + ctx.ReadMessage(v); + }, + (ref T v, T v2) => + { + if (v2 == null) + { + return false; + } + else if (v == null) + { + v = v2.Clone(); + } + else + { + v.MergeFrom(v2); + } + return true; + }, + message => CodedOutputStream.ComputeMessageSize(message), tag); + } + + /// + /// Retrieves a codec suitable for a group field with the given tag. + /// + /// The start group tag. + /// The end group tag. + /// A parser to use for the group message type. + /// A codec for given tag + public static FieldCodec ForGroup(uint startTag, uint endTag, MessageParser parser) where T : class, IMessage + { + return new FieldCodec( + (ref ParseContext ctx) => + { + T message = parser.CreateTemplate(); + ctx.ReadGroup(message); + return message; + }, + (ref WriteContext output, T value) => output.WriteGroup(value), + (ref ParseContext ctx, ref T v) => + { + if (v == null) + { + v = parser.CreateTemplate(); + } + + ctx.ReadGroup(v); + }, + (ref T v, T v2) => + { + if (v2 == null) + { + return v == null; + } + else if (v == null) + { + v = v2.Clone(); + } + else + { + v.MergeFrom(v2); + } + return true; + }, + message => CodedOutputStream.ComputeGroupSize(message), startTag, endTag); + } + + /// + /// Creates a codec for a wrapper type of a class - which must be string or ByteString. + /// + public static FieldCodec ForClassWrapper(uint tag) where T : class + { + var nestedCodec = WrapperCodecs.GetCodec(); + return new FieldCodec( + (ref ParseContext ctx) => WrapperCodecs.Read(ref ctx, nestedCodec), + (ref WriteContext output, T value) => WrapperCodecs.Write(ref output, value, nestedCodec), + (ref ParseContext ctx, ref T v) => v = WrapperCodecs.Read(ref ctx, nestedCodec), + (ref T v, T v2) => { v = v2; return v == null; }, + value => WrapperCodecs.CalculateSize(value, nestedCodec), + tag, 0, + null); // Default value for the wrapper + } + + /// + /// Creates a codec for a wrapper type of a struct - which must be Int32, Int64, UInt32, UInt64, + /// Bool, Single or Double. + /// + public static FieldCodec ForStructWrapper(uint tag) where T : struct + { + var nestedCodec = WrapperCodecs.GetCodec(); + return new FieldCodec( + WrapperCodecs.GetReader(), + (ref WriteContext output, T? value) => WrapperCodecs.Write(ref output, value.Value, nestedCodec), + (ref ParseContext ctx, ref T? v) => v = WrapperCodecs.Read(ref ctx, nestedCodec), + (ref T? v, T? v2) => { if (v2.HasValue) { v = v2; } return v.HasValue; }, + value => value == null ? 0 : WrapperCodecs.CalculateSize(value.Value, nestedCodec), + tag, 0, + null); // Default value for the wrapper + } + + /// + /// Helper code to create codecs for wrapper types. + /// + /// + /// Somewhat ugly with all the static methods, but the conversions involved to/from nullable types make it + /// slightly tricky to improve. So long as we keep the public API (ForClassWrapper, ForStructWrapper) in place, + /// we can refactor later if we come up with something cleaner. + /// + private static class WrapperCodecs + { + private static readonly Dictionary Codecs = new Dictionary + { + { typeof(bool), ForBool(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Varint)) }, + { typeof(int), ForInt32(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Varint)) }, + { typeof(long), ForInt64(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Varint)) }, + { typeof(uint), ForUInt32(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Varint)) }, + { typeof(ulong), ForUInt64(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Varint)) }, + { typeof(float), ForFloat(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Fixed32)) }, + { typeof(double), ForDouble(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.Fixed64)) }, + { typeof(string), ForString(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.LengthDelimited)) }, + { typeof(ByteString), ForBytes(WireFormat.MakeTag(WrappersReflection.WrapperValueFieldNumber, WireFormat.WireType.LengthDelimited)) } + }; + + private static readonly Dictionary Readers = new Dictionary + { + // TODO: Provide more optimized readers. + { typeof(bool), (ValueReader)ParsingPrimitivesWrappers.ReadBoolWrapper }, + { typeof(int), (ValueReader)ParsingPrimitivesWrappers.ReadInt32Wrapper }, + { typeof(long), (ValueReader)ParsingPrimitivesWrappers.ReadInt64Wrapper }, + { typeof(uint), (ValueReader)ParsingPrimitivesWrappers.ReadUInt32Wrapper }, + { typeof(ulong), (ValueReader)ParsingPrimitivesWrappers.ReadUInt64Wrapper }, + { typeof(float), BitConverter.IsLittleEndian ? + (ValueReader)ParsingPrimitivesWrappers.ReadFloatWrapperLittleEndian : + (ValueReader)ParsingPrimitivesWrappers.ReadFloatWrapperSlow }, + { typeof(double), BitConverter.IsLittleEndian ? + (ValueReader)ParsingPrimitivesWrappers.ReadDoubleWrapperLittleEndian : + (ValueReader)ParsingPrimitivesWrappers.ReadDoubleWrapperSlow }, + // `string` and `ByteString` less performance-sensitive. Do not implement for now. + { typeof(string), null }, + { typeof(ByteString), null }, + }; + + /// + /// Returns a field codec which effectively wraps a value of type T in a message. + /// + /// + internal static FieldCodec GetCodec() + { + object value; + if (!Codecs.TryGetValue(typeof(T), out value)) + { + throw new InvalidOperationException("Invalid type argument requested for wrapper codec: " + typeof(T)); + } + return (FieldCodec) value; + } + + internal static ValueReader GetReader() where T : struct + { + object value; + if (!Readers.TryGetValue(typeof(T), out value)) + { + throw new InvalidOperationException("Invalid type argument requested for wrapper reader: " + typeof(T)); + } + if (value == null) + { + // Return default unoptimized reader for the wrapper type. + var nestedCoded = GetCodec(); + return (ref ParseContext ctx) => Read(ref ctx, nestedCoded); + } + // Return optimized read for the wrapper type. + return (ValueReader)value; + } + + [SecuritySafeCritical] + internal static T Read(ref ParseContext ctx, FieldCodec codec) + { + int length = ctx.ReadLength(); + int oldLimit = SegmentedBufferHelper.PushLimit(ref ctx.state, length); + + uint tag; + T value = codec.DefaultValue; + while ((tag = ctx.ReadTag()) != 0) + { + if (tag == codec.Tag) + { + value = codec.Read(ref ctx); + } + else + { + ParsingPrimitivesMessages.SkipLastField(ref ctx.buffer, ref ctx.state); + } + + } + ParsingPrimitivesMessages.CheckReadEndOfStreamTag(ref ctx.state); + SegmentedBufferHelper.PopLimit(ref ctx.state, oldLimit); + + return value; + } + + internal static void Write(ref WriteContext ctx, T value, FieldCodec codec) + { + ctx.WriteLength(codec.CalculateSizeWithTag(value)); + codec.WriteTagAndValue(ref ctx, value); + } + + internal static int CalculateSize(T value, FieldCodec codec) + { + int fieldLength = codec.CalculateSizeWithTag(value); + return CodedOutputStream.ComputeLengthSize(fieldLength) + fieldLength; + } + } + } + + internal delegate TValue ValueReader(ref ParseContext ctx); + internal delegate void ValueWriter(ref WriteContext ctx, T value); + + /// + /// + /// An encode/decode pair for a single field. This effectively encapsulates + /// all the information needed to read or write the field value from/to a coded + /// stream. + /// + /// + /// This class is public and has to be as it is used by generated code, but its public + /// API is very limited - just what the generated code needs to call directly. + /// + /// + /// + /// This never writes default values to the stream, and does not address "packedness" + /// in repeated fields itself, other than to know whether or not the field *should* be packed. + /// + public sealed class FieldCodec + { + private static readonly EqualityComparer EqualityComparer = ProtobufEqualityComparers.GetEqualityComparer(); + private static readonly T DefaultDefault; + // Only non-nullable value types support packing. This is the simplest way of detecting that. + private static readonly bool TypeSupportsPacking = default(T) != null; + + /// + /// Merges an input stream into a value + /// + internal delegate void InputMerger(ref ParseContext ctx, ref T value); + + /// + /// Merges a value into a reference to another value, returning a boolean if the value was set + /// + internal delegate bool ValuesMerger(ref T value, T other); + + static FieldCodec() + { + if (typeof(T) == typeof(string)) + { + DefaultDefault = (T)(object)""; + } + else if (typeof(T) == typeof(ByteString)) + { + DefaultDefault = (T)(object)ByteString.Empty; + } + // Otherwise it's the default value of the CLR type + } + + internal static bool IsPackedRepeatedField(uint tag) => + TypeSupportsPacking && WireFormat.GetTagWireType(tag) == WireFormat.WireType.LengthDelimited; + + internal bool PackedRepeatedField { get; } + + /// + /// Returns a delegate to write a value (unconditionally) to a coded output stream. + /// + internal ValueWriter ValueWriter { get; } + + /// + /// Returns the size calculator for just a value. + /// + internal Func ValueSizeCalculator { get; } + + /// + /// Returns a delegate to read a value from a coded input stream. It is assumed that + /// the stream is already positioned on the appropriate tag. + /// + internal ValueReader ValueReader { get; } + + /// + /// Returns a delegate to merge a value from a coded input stream. + /// It is assumed that the stream is already positioned on the appropriate tag + /// + internal InputMerger ValueMerger { get; } + + /// + /// Returns a delegate to merge two values together. + /// + internal ValuesMerger FieldMerger { get; } + + /// + /// Returns the fixed size for an entry, or 0 if sizes vary. + /// + internal int FixedSize { get; } + + /// + /// Gets the tag of the codec. + /// + /// + /// The tag of the codec. + /// + internal uint Tag { get; } + + /// + /// Gets the end tag of the codec or 0 if there is no end tag + /// + /// + /// The end tag of the codec. + /// + internal uint EndTag { get; } + + /// + /// Default value for this codec. Usually the same for every instance of the same type, but + /// for string/ByteString wrapper fields the codec's default value is null, whereas for + /// other string/ByteString fields it's "" or ByteString.Empty. + /// + /// + /// The default value of the codec's type. + /// + internal T DefaultValue { get; } + + private readonly int tagSize; + + internal FieldCodec( + ValueReader reader, + ValueWriter writer, + int fixedSize, + uint tag, + T defaultValue) : this(reader, writer, _ => fixedSize, tag, defaultValue) + { + FixedSize = fixedSize; + } + + internal FieldCodec( + ValueReader reader, + ValueWriter writer, + Func sizeCalculator, + uint tag, + T defaultValue) : this(reader, writer, (ref ParseContext ctx, ref T v) => v = reader(ref ctx), (ref T v, T v2) => { v = v2; return true; }, sizeCalculator, tag, 0, defaultValue) + { + } + + internal FieldCodec( + ValueReader reader, + ValueWriter writer, + InputMerger inputMerger, + ValuesMerger valuesMerger, + Func sizeCalculator, + uint tag, + uint endTag = 0) : this(reader, writer, inputMerger, valuesMerger, sizeCalculator, tag, endTag, DefaultDefault) + { + } + + internal FieldCodec( + ValueReader reader, + ValueWriter writer, + InputMerger inputMerger, + ValuesMerger valuesMerger, + Func sizeCalculator, + uint tag, + uint endTag, + T defaultValue) + { + ValueReader = reader; + ValueWriter = writer; + ValueMerger = inputMerger; + FieldMerger = valuesMerger; + ValueSizeCalculator = sizeCalculator; + FixedSize = 0; + Tag = tag; + EndTag = endTag; + DefaultValue = defaultValue; + tagSize = CodedOutputStream.ComputeRawVarint32Size(tag); + if (endTag != 0) + tagSize += CodedOutputStream.ComputeRawVarint32Size(endTag); + // Detect packed-ness once, so we can check for it within RepeatedField. + PackedRepeatedField = IsPackedRepeatedField(tag); + } + + /// + /// Write a tag and the given value, *if* the value is not the default. + /// + public void WriteTagAndValue(CodedOutputStream output, T value) + { + WriteContext.Initialize(output, out WriteContext ctx); + try + { + WriteTagAndValue(ref ctx, value); + } + finally + { + ctx.CopyStateTo(output); + } + + + //if (!IsDefault(value)) + //{ + // output.WriteTag(Tag); + // ValueWriter(output, value); + // if (EndTag != 0) + // { + // output.WriteTag(EndTag); + // } + //} + } + + /// + /// Write a tag and the given value, *if* the value is not the default. + /// + public void WriteTagAndValue(ref WriteContext ctx, T value) + { + if (!IsDefault(value)) + { + ctx.WriteTag(Tag); + ValueWriter(ref ctx, value); + if (EndTag != 0) + { + ctx.WriteTag(EndTag); + } + } + } + + /// + /// Reads a value of the codec type from the given . + /// + /// The input stream to read from. + /// The value read from the stream. + public T Read(CodedInputStream input) + { + ParseContext.Initialize(input, out ParseContext ctx); + try + { + return ValueReader(ref ctx); + } + finally + { + ctx.CopyStateTo(input); + } + } + + /// + /// Reads a value of the codec type from the given . + /// + /// The parse context to read from. + /// The value read. + public T Read(ref ParseContext ctx) + { + return ValueReader(ref ctx); + } + + /// + /// Calculates the size required to write the given value, with a tag, + /// if the value is not the default. + /// + public int CalculateSizeWithTag(T value) => IsDefault(value) ? 0 : ValueSizeCalculator(value) + tagSize; + + /// + /// Calculates the size required to write the given value, with a tag, even + /// if the value is the default. + /// + internal int CalculateUnconditionalSizeWithTag(T value) => ValueSizeCalculator(value) + tagSize; + + private bool IsDefault(T value) => EqualityComparer.Equals(value, DefaultValue); + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/InvalidProtocolBufferException.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/InvalidProtocolBufferException.cs new file mode 100644 index 0000000..c5ffe9b --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/InvalidProtocolBufferException.cs @@ -0,0 +1,140 @@ +#region Copyright notice and license +// 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. +#endregion + +using System; +using System.IO; + +namespace Google.Protobuf +{ + /// + /// Thrown when a protocol message being parsed is invalid in some way, + /// e.g. it contains a malformed varint or a negative byte length. + /// + public sealed class InvalidProtocolBufferException : IOException + { + internal InvalidProtocolBufferException(string message) + : base(message) + { + } + + internal InvalidProtocolBufferException(string message, Exception innerException) + : base(message, innerException) + { + } + + internal static InvalidProtocolBufferException MoreDataAvailable() + { + return new InvalidProtocolBufferException( + "Completed reading a message while more data was available in the stream."); + } + + internal static InvalidProtocolBufferException TruncatedMessage() + { + return new InvalidProtocolBufferException( + "While parsing a protocol message, the input ended unexpectedly " + + "in the middle of a field. This could mean either that the " + + "input has been truncated or that an embedded message " + + "misreported its own length."); + } + + internal static InvalidProtocolBufferException NegativeSize() + { + return new InvalidProtocolBufferException( + "CodedInputStream encountered an embedded string or message " + + "which claimed to have negative size."); + } + + internal static InvalidProtocolBufferException MalformedVarint() + { + return new InvalidProtocolBufferException( + "CodedInputStream encountered a malformed varint."); + } + + /// + /// Creates an exception for an error condition of an invalid tag being encountered. + /// + internal static InvalidProtocolBufferException InvalidTag() + { + return new InvalidProtocolBufferException( + "Protocol message contained an invalid tag (zero)."); + } + + internal static InvalidProtocolBufferException InvalidWireType() + { + return new InvalidProtocolBufferException( + "Protocol message contained a tag with an invalid wire type."); + } + + internal static InvalidProtocolBufferException InvalidBase64(Exception innerException) + { + return new InvalidProtocolBufferException("Invalid base64 data", innerException); + } + + internal static InvalidProtocolBufferException InvalidEndTag() + { + return new InvalidProtocolBufferException( + "Protocol message end-group tag did not match expected tag."); + } + + internal static InvalidProtocolBufferException RecursionLimitExceeded() + { + return new InvalidProtocolBufferException( + "Protocol message had too many levels of nesting. May be malicious. " + + "Use CodedInputStream.SetRecursionLimit() to increase the depth limit."); + } + + internal static InvalidProtocolBufferException JsonRecursionLimitExceeded() + { + return new InvalidProtocolBufferException( + "Protocol message had too many levels of nesting. May be malicious. " + + "Use JsonParser.Settings to increase the depth limit."); + } + + internal static InvalidProtocolBufferException SizeLimitExceeded() + { + return new InvalidProtocolBufferException( + "Protocol message was too large. May be malicious. " + + "Use CodedInputStream.SetSizeLimit() to increase the size limit."); + } + + internal static InvalidProtocolBufferException InvalidMessageStreamTag() + { + return new InvalidProtocolBufferException( + "Stream of protocol messages had invalid tag. Expected tag is length-delimited field 1."); + } + + internal static InvalidProtocolBufferException MissingFields() + { + return new InvalidProtocolBufferException("Message was missing required fields"); + } +} +} \ No newline at end of file diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Reflection/DescriptorPool.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Reflection/DescriptorPool.cs new file mode 100644 index 0000000..93f2fa9 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Reflection/DescriptorPool.cs @@ -0,0 +1,334 @@ +#region Copyright notice and license +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Text; +using System.Text.RegularExpressions; + +namespace Google.Protobuf.Reflection +{ + /// + /// Contains lookup tables containing all the descriptors defined in a particular file. + /// + internal sealed class DescriptorPool + { + private readonly IDictionary descriptorsByName = + new Dictionary(); + + private readonly IDictionary, FieldDescriptor> fieldsByNumber = + new Dictionary, FieldDescriptor>(); + + private readonly IDictionary, EnumValueDescriptor> enumValuesByNumber = + new Dictionary, EnumValueDescriptor>(); + + private readonly HashSet dependencies; + + internal DescriptorPool(IEnumerable dependencyFiles) + { + dependencies = new HashSet(); + foreach (var dependencyFile in dependencyFiles) + { + dependencies.Add(dependencyFile); + ImportPublicDependencies(dependencyFile); + } + + foreach (FileDescriptor dependency in dependencyFiles) + { + AddPackage(dependency.Package, dependency); + } + } + + private void ImportPublicDependencies(FileDescriptor file) + { + foreach (FileDescriptor dependency in file.PublicDependencies) + { + if (dependencies.Add(dependency)) + { + ImportPublicDependencies(dependency); + } + } + } + + /// + /// Finds a symbol of the given name within the pool. + /// + /// The type of symbol to look for + /// Fully-qualified name to look up + /// The symbol with the given name and type, + /// or null if the symbol doesn't exist or has the wrong type + internal T FindSymbol(string fullName) where T : class + { + IDescriptor result; + descriptorsByName.TryGetValue(fullName, out result); + T descriptor = result as T; + if (descriptor != null) + { + return descriptor; + } + + // dependencies contains direct dependencies and any *public* dependencies + // of those dependencies (transitively)... so we don't need to recurse here. + foreach (FileDescriptor dependency in dependencies) + { + dependency.DescriptorPool.descriptorsByName.TryGetValue(fullName, out result); + descriptor = result as T; + if (descriptor != null) + { + return descriptor; + } + } + + return null; + } + + /// + /// Adds a package to the symbol tables. If a package by the same name + /// already exists, that is fine, but if some other kind of symbol + /// exists under the same name, an exception is thrown. If the package + /// has multiple components, this also adds the parent package(s). + /// + internal void AddPackage(string fullName, FileDescriptor file) + { + int dotpos = fullName.LastIndexOf('.'); + String name; + if (dotpos != -1) + { + AddPackage(fullName.Substring(0, dotpos), file); + name = fullName.Substring(dotpos + 1); + } + else + { + name = fullName; + } + + IDescriptor old; + if (descriptorsByName.TryGetValue(fullName, out old)) + { + if (!(old is PackageDescriptor)) + { + throw new DescriptorValidationException(file, + "\"" + name + + "\" is already defined (as something other than a " + + "package) in file \"" + old.File.Name + "\"."); + } + } + descriptorsByName[fullName] = new PackageDescriptor(name, fullName, file); + } + + /// + /// Adds a symbol to the symbol table. + /// + /// The symbol already existed + /// in the symbol table. + internal void AddSymbol(IDescriptor descriptor) + { + ValidateSymbolName(descriptor); + String fullName = descriptor.FullName; + + IDescriptor old; + if (descriptorsByName.TryGetValue(fullName, out old)) + { + int dotPos = fullName.LastIndexOf('.'); + string message; + if (descriptor.File == old.File) + { + if (dotPos == -1) + { + message = "\"" + fullName + "\" is already defined."; + } + else + { + message = "\"" + fullName.Substring(dotPos + 1) + "\" is already defined in \"" + + fullName.Substring(0, dotPos) + "\"."; + } + } + else + { + message = "\"" + fullName + "\" is already defined in file \"" + old.File.Name + "\"."; + } + throw new DescriptorValidationException(descriptor, message); + } + descriptorsByName[fullName] = descriptor; + } + + private static readonly Regex ValidationRegex = new Regex("^[_A-Za-z][_A-Za-z0-9]*$", + FrameworkPortability.CompiledRegexWhereAvailable); + + /// + /// Verifies that the descriptor's name is valid (i.e. it contains + /// only letters, digits and underscores, and does not start with a digit). + /// + /// + private static void ValidateSymbolName(IDescriptor descriptor) + { + if (descriptor.Name == "") + { + throw new DescriptorValidationException(descriptor, "Missing name."); + } + if (!ValidationRegex.IsMatch(descriptor.Name)) + { + throw new DescriptorValidationException(descriptor, + "\"" + descriptor.Name + "\" is not a valid identifier."); + } + } + + /// + /// Returns the field with the given number in the given descriptor, + /// or null if it can't be found. + /// + internal FieldDescriptor FindFieldByNumber(MessageDescriptor messageDescriptor, int number) + { + FieldDescriptor ret; + fieldsByNumber.TryGetValue(new ObjectIntPair(messageDescriptor, number), out ret); + return ret; + } + + internal EnumValueDescriptor FindEnumValueByNumber(EnumDescriptor enumDescriptor, int number) + { + EnumValueDescriptor ret; + enumValuesByNumber.TryGetValue(new ObjectIntPair(enumDescriptor, number), out ret); + return ret; + } + + /// + /// Adds a field to the fieldsByNumber table. + /// + /// A field with the same + /// containing type and number already exists. + internal void AddFieldByNumber(FieldDescriptor field) + { + // for extensions, we use the extended type, otherwise we use the containing type + ObjectIntPair key = new ObjectIntPair(field.Proto.HasExtendee ? field.ExtendeeType : field.ContainingType, field.FieldNumber); + FieldDescriptor old; + if (fieldsByNumber.TryGetValue(key, out old)) + { + throw new DescriptorValidationException(field, "Field number " + field.FieldNumber + + "has already been used in \"" + + field.ContainingType.FullName + + "\" by field \"" + old.Name + "\"."); + } + fieldsByNumber[key] = field; + } + + /// + /// Adds an enum value to the enumValuesByNumber table. If an enum value + /// with the same type and number already exists, this method does nothing. + /// (This is allowed; the first value defined with the number takes precedence.) + /// + internal void AddEnumValueByNumber(EnumValueDescriptor enumValue) + { + ObjectIntPair key = new ObjectIntPair(enumValue.EnumDescriptor, enumValue.Number); + if (!enumValuesByNumber.ContainsKey(key)) + { + enumValuesByNumber[key] = enumValue; + } + } + + /// + /// Looks up a descriptor by name, relative to some other descriptor. + /// The name may be fully-qualified (with a leading '.'), partially-qualified, + /// or unqualified. C++-like name lookup semantics are used to search for the + /// matching descriptor. + /// + /// + /// This isn't heavily optimized, but it's only used during cross linking anyway. + /// If it starts being used more widely, we should look at performance more carefully. + /// + internal IDescriptor LookupSymbol(string name, IDescriptor relativeTo) + { + IDescriptor result; + if (name.StartsWith(".")) + { + // Fully-qualified name. + result = FindSymbol(name.Substring(1)); + } + else + { + // If "name" is a compound identifier, we want to search for the + // first component of it, then search within it for the rest. + int firstPartLength = name.IndexOf('.'); + string firstPart = firstPartLength == -1 ? name : name.Substring(0, firstPartLength); + + // We will search each parent scope of "relativeTo" looking for the + // symbol. + StringBuilder scopeToTry = new StringBuilder(relativeTo.FullName); + + while (true) + { + // Chop off the last component of the scope. + + int dotpos = scopeToTry.ToString().LastIndexOf("."); + if (dotpos == -1) + { + result = FindSymbol(name); + break; + } + else + { + scopeToTry.Length = dotpos + 1; + + // Append firstPart and try to find. + scopeToTry.Append(firstPart); + result = FindSymbol(scopeToTry.ToString()); + + if (result != null) + { + if (firstPartLength != -1) + { + // We only found the first part of the symbol. Now look for + // the whole thing. If this fails, we *don't* want to keep + // searching parent scopes. + scopeToTry.Length = dotpos + 1; + scopeToTry.Append(name); + result = FindSymbol(scopeToTry.ToString()); + } + break; + } + + // Not found. Remove the name so we can try again. + scopeToTry.Length = dotpos; + } + } + } + + if (result == null) + { + throw new DescriptorValidationException(relativeTo, "\"" + name + "\" is not defined."); + } + else + { + return result; + } + } + } +} \ No newline at end of file diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Reflection/DescriptorUtil.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Reflection/DescriptorUtil.cs new file mode 100644 index 0000000..f5570fc --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Reflection/DescriptorUtil.cs @@ -0,0 +1,64 @@ +#region Copyright notice and license +// 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. +#endregion + +using System.Collections.Generic; +using System.Collections.ObjectModel; + +namespace Google.Protobuf.Reflection +{ + /// + /// Internal class containing utility methods when working with descriptors. + /// + internal static class DescriptorUtil + { + /// + /// Equivalent to Func[TInput, int, TOutput] but usable in .NET 2.0. Only used to convert + /// arrays. + /// + internal delegate TOutput IndexedConverter(TInput element, int index); + + /// + /// Converts the given array into a read-only list, applying the specified conversion to + /// each input element. + /// + internal static IList ConvertAndMakeReadOnly + (IList input, IndexedConverter converter) + { + TOutput[] array = new TOutput[input.Count]; + for (int i = 0; i < array.Length; i++) + { + array[i] = converter(input[i], i); + } + return new ReadOnlyCollection(array); + } + } +} \ No newline at end of file diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Reflection/IFieldAccessor.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Reflection/IFieldAccessor.cs new file mode 100644 index 0000000..d73427b --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Reflection/IFieldAccessor.cs @@ -0,0 +1,77 @@ +#region Copyright notice and license +// 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. +#endregion + +using System; +using System.Collections; + +namespace Google.Protobuf.Reflection +{ + /// + /// Allows fields to be reflectively accessed. + /// + public interface IFieldAccessor + { + /// + /// Returns the descriptor associated with this field. + /// + FieldDescriptor Descriptor { get; } + + /// + /// Clears the field in the specified message. (For repeated fields, + /// this clears the list.) + /// + void Clear(IMessage message); + + /// + /// Fetches the field value. For repeated values, this will be an + /// implementation. For map values, this will be an + /// implementation. + /// + object GetValue(IMessage message); + + /// + /// Indicates whether the field in the specified message is set. + /// For proto3 fields that aren't explicitly optional, this throws an + /// + bool HasValue(IMessage message); + + /// + /// Mutator for single "simple" fields only. + /// + /// + /// Repeated fields are mutated by fetching the value and manipulating it as a list. + /// Map fields are mutated by fetching the value and manipulating it as a dictionary. + /// + /// The field is not a "simple" field. + void SetValue(IMessage message, object value); + } +} \ No newline at end of file diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs new file mode 100644 index 0000000..40a6ff8 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs @@ -0,0 +1,430 @@ +#region Copyright notice and license +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Reflection; +#if NET35 +// Needed for ReadOnlyDictionary, which does not exist in .NET 3.5 +using Google.Protobuf.Collections; +#endif + +namespace Google.Protobuf.Reflection +{ + /// + /// Describes a message type. + /// + public sealed class MessageDescriptor : DescriptorBase + { + private static readonly HashSet WellKnownTypeNames = new HashSet + { + "google/protobuf/any.proto", + "google/protobuf/api.proto", + "google/protobuf/duration.proto", + "google/protobuf/empty.proto", + "google/protobuf/wrappers.proto", + "google/protobuf/timestamp.proto", + "google/protobuf/field_mask.proto", + "google/protobuf/source_context.proto", + "google/protobuf/struct.proto", + "google/protobuf/type.proto", + }; + + private readonly IList fieldsInDeclarationOrder; + private readonly IList fieldsInNumberOrder; + private readonly IDictionary jsonFieldMap; + private Func extensionSetIsInitialized; + + internal MessageDescriptor(DescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int typeIndex, GeneratedClrTypeInfo generatedCodeInfo) + : base(file, file.ComputeFullName(parent, proto.Name), typeIndex) + { + Proto = proto; + Parser = generatedCodeInfo?.Parser; + ClrType = generatedCodeInfo?.ClrType; + ContainingType = parent; + + // If generatedCodeInfo is null, we just won't generate an accessor for any fields. + Oneofs = DescriptorUtil.ConvertAndMakeReadOnly( + proto.OneofDecl, + (oneof, index) => + new OneofDescriptor(oneof, file, this, index, generatedCodeInfo?.OneofNames[index])); + + int syntheticOneofCount = 0; + foreach (var oneof in Oneofs) + { + if (oneof.IsSynthetic) + { + syntheticOneofCount++; + } + else if (syntheticOneofCount != 0) + { + throw new ArgumentException("All synthetic oneofs should come after real oneofs"); + } + } + RealOneofCount = Oneofs.Count - syntheticOneofCount; + + NestedTypes = DescriptorUtil.ConvertAndMakeReadOnly( + proto.NestedType, + (type, index) => + new MessageDescriptor(type, file, this, index, generatedCodeInfo?.NestedTypes[index])); + + EnumTypes = DescriptorUtil.ConvertAndMakeReadOnly( + proto.EnumType, + (type, index) => + new EnumDescriptor(type, file, this, index, generatedCodeInfo?.NestedEnums[index])); + + Extensions = new ExtensionCollection(this, generatedCodeInfo?.Extensions); + + fieldsInDeclarationOrder = DescriptorUtil.ConvertAndMakeReadOnly( + proto.Field, + (field, index) => + new FieldDescriptor(field, file, this, index, generatedCodeInfo?.PropertyNames[index], null)); + fieldsInNumberOrder = new ReadOnlyCollection(fieldsInDeclarationOrder.OrderBy(field => field.FieldNumber).ToArray()); + // TODO: Use field => field.Proto.JsonName when we're confident it's appropriate. (And then use it in the formatter, too.) + jsonFieldMap = CreateJsonFieldMap(fieldsInNumberOrder); + file.DescriptorPool.AddSymbol(this); + Fields = new FieldCollection(this); + } + + private static ReadOnlyDictionary CreateJsonFieldMap(IList fields) + { + var map = new Dictionary(); + foreach (var field in fields) + { + map[field.Name] = field; + map[field.JsonName] = field; + } + return new ReadOnlyDictionary(map); + } + + /// + /// The brief name of the descriptor's target. + /// + public override string Name => Proto.Name; + + internal override IReadOnlyList GetNestedDescriptorListForField(int fieldNumber) + { + switch (fieldNumber) + { + case DescriptorProto.FieldFieldNumber: + return (IReadOnlyList) fieldsInDeclarationOrder; + case DescriptorProto.NestedTypeFieldNumber: + return (IReadOnlyList) NestedTypes; + case DescriptorProto.EnumTypeFieldNumber: + return (IReadOnlyList) EnumTypes; + default: + return null; + } + } + + internal DescriptorProto Proto { get; } + + /// + /// Returns a clone of the underlying describing this message. + /// Note that a copy is taken every time this method is called, so clients using it frequently + /// (and not modifying it) may want to cache the returned value. + /// + /// A protobuf representation of this message descriptor. + public DescriptorProto ToProto() => Proto.Clone(); + + internal bool IsExtensionsInitialized(IMessage message) + { + if (Proto.ExtensionRange.Count == 0) + { + return true; + } + + if (extensionSetIsInitialized == null) + { + extensionSetIsInitialized = ReflectionUtil.CreateIsInitializedCaller(ClrType); + } + + return extensionSetIsInitialized(message); + } + + /// + /// The CLR type used to represent message instances from this descriptor. + /// + /// + /// + /// The value returned by this property will be non-null for all regular fields. However, + /// if a message containing a map field is introspected, the list of nested messages will include + /// an auto-generated nested key/value pair message for the field. This is not represented in any + /// generated type, so this property will return null in such cases. + /// + /// + /// For wrapper types ( and the like), the type returned here + /// will be the generated message type, not the native type used by reflection for fields of those types. Code + /// using reflection should call to determine whether a message descriptor represents + /// a wrapper type, and handle the result appropriately. + /// + /// + [DynamicallyAccessedMembers(GeneratedClrTypeInfo.MessageAccessibility)] + public Type ClrType { get; } + + /// + /// A parser for this message type. + /// + /// + /// + /// As is not generic, this cannot be statically + /// typed to the relevant type, but it should produce objects of a type compatible with . + /// + /// + /// The value returned by this property will be non-null for all regular fields. However, + /// if a message containing a map field is introspected, the list of nested messages will include + /// an auto-generated nested key/value pair message for the field. No message parser object is created for + /// such messages, so this property will return null in such cases. + /// + /// + /// For wrapper types ( and the like), the parser returned here + /// will be the generated message type, not the native type used by reflection for fields of those types. Code + /// using reflection should call to determine whether a message descriptor represents + /// a wrapper type, and handle the result appropriately. + /// + /// + public MessageParser Parser { get; } + + /// + /// Returns whether this message is one of the "well known types" which may have runtime/protoc support. + /// + internal bool IsWellKnownType => File.Package == "google.protobuf" && WellKnownTypeNames.Contains(File.Name); + + /// + /// Returns whether this message is one of the "wrapper types" used for fields which represent primitive values + /// with the addition of presence. + /// + internal bool IsWrapperType => File.Package == "google.protobuf" && File.Name == "google/protobuf/wrappers.proto"; + + /// + /// If this is a nested type, get the outer descriptor, otherwise null. + /// + public MessageDescriptor ContainingType { get; } + + /// + /// A collection of fields, which can be retrieved by name or field number. + /// + public FieldCollection Fields { get; } + + /// + /// An unmodifiable list of extensions defined in this message's scope. + /// Note that some extensions may be incomplete (FieldDescriptor.Extension may be null) + /// if they are declared in a file generated using a version of protoc that did not fully + /// support extensions in C#. + /// + public ExtensionCollection Extensions { get; } + + /// + /// An unmodifiable list of this message type's nested types. + /// + public IList NestedTypes { get; } + + /// + /// An unmodifiable list of this message type's enum types. + /// + public IList EnumTypes { get; } + + /// + /// An unmodifiable list of the "oneof" field collections in this message type. + /// All "real" oneofs (where returns false) + /// come before synthetic ones. + /// + public IList Oneofs { get; } + + /// + /// The number of real "oneof" descriptors in this message type. Every element in + /// with an index less than this will have a property value + /// of false; every element with an index greater than or equal to this will have a + /// property value of true. + /// + public int RealOneofCount { get; } + + /// + /// Finds a field by field name. + /// + /// The unqualified name of the field (e.g. "foo"). + /// The field's descriptor, or null if not found. + public FieldDescriptor FindFieldByName(String name) => File.DescriptorPool.FindSymbol(FullName + "." + name); + + /// + /// Finds a field by field number. + /// + /// The field number within this message type. + /// The field's descriptor, or null if not found. + public FieldDescriptor FindFieldByNumber(int number) => File.DescriptorPool.FindFieldByNumber(this, number); + + /// + /// Finds a nested descriptor by name. The is valid for fields, nested + /// message types, oneofs and enums. + /// + /// The unqualified name of the descriptor, e.g. "Foo" + /// The descriptor, or null if not found. + public T FindDescriptor(string name) where T : class, IDescriptor => + File.DescriptorPool.FindSymbol(FullName + "." + name); + + /// + /// The (possibly empty) set of custom options for this message. + /// + [Obsolete("CustomOptions are obsolete. Use the GetOptions() method.")] + public CustomOptions CustomOptions => new CustomOptions(Proto.Options?._extensions?.ValuesByNumber); + + /// + /// The MessageOptions, defined in descriptor.proto. + /// If the options message is not present (i.e. there are no options), null is returned. + /// Custom options can be retrieved as extensions of the returned message. + /// NOTE: A defensive copy is created each time this property is retrieved. + /// + public MessageOptions GetOptions() => Proto.Options?.Clone(); + + /// + /// Gets a single value message option for this descriptor + /// + [Obsolete("GetOption is obsolete. Use the GetOptions() method.")] + public T GetOption(Extension extension) + { + var value = Proto.Options.GetExtension(extension); + return value is IDeepCloneable ? (value as IDeepCloneable).Clone() : value; + } + + /// + /// Gets a repeated value message option for this descriptor + /// + [Obsolete("GetOption is obsolete. Use the GetOptions() method.")] + public Collections.RepeatedField GetOption(RepeatedExtension extension) + { + return Proto.Options.GetExtension(extension).Clone(); + } + + /// + /// Looks up and cross-links all fields and nested types. + /// + internal void CrossLink() + { + foreach (MessageDescriptor message in NestedTypes) + { + message.CrossLink(); + } + + foreach (FieldDescriptor field in fieldsInDeclarationOrder) + { + field.CrossLink(); + } + + foreach (OneofDescriptor oneof in Oneofs) + { + oneof.CrossLink(); + } + + Extensions.CrossLink(); + } + + /// + /// A collection to simplify retrieving the field accessor for a particular field. + /// + public sealed class FieldCollection + { + private readonly MessageDescriptor messageDescriptor; + + internal FieldCollection(MessageDescriptor messageDescriptor) + { + this.messageDescriptor = messageDescriptor; + } + + /// + /// Returns the fields in the message as an immutable list, in the order in which they + /// are declared in the source .proto file. + /// + public IList InDeclarationOrder() => messageDescriptor.fieldsInDeclarationOrder; + + /// + /// Returns the fields in the message as an immutable list, in ascending field number + /// order. Field numbers need not be contiguous, so there is no direct mapping from the + /// index in the list to the field number; to retrieve a field by field number, it is better + /// to use the indexer. + /// + public IList InFieldNumberOrder() => messageDescriptor.fieldsInNumberOrder; + + // TODO: consider making this public in the future. (Being conservative for now...) + + /// + /// Returns a read-only dictionary mapping the field names in this message as they're available + /// in the JSON representation to the field descriptors. For example, a field foo_bar + /// in the message would result two entries, one with a key fooBar and one with a key + /// foo_bar, both referring to the same field. + /// + internal IDictionary ByJsonName() => messageDescriptor.jsonFieldMap; + + /// + /// Retrieves the descriptor for the field with the given number. + /// + /// Number of the field to retrieve the descriptor for + /// The accessor for the given field + /// The message descriptor does not contain a field + /// with the given number + public FieldDescriptor this[int number] + { + get + { + var fieldDescriptor = messageDescriptor.FindFieldByNumber(number); + if (fieldDescriptor == null) + { + throw new KeyNotFoundException("No such field number"); + } + return fieldDescriptor; + } + } + + /// + /// Retrieves the descriptor for the field with the given name. + /// + /// Name of the field to retrieve the descriptor for + /// The descriptor for the given field + /// The message descriptor does not contain a field + /// with the given name + public FieldDescriptor this[string name] + { + get + { + var fieldDescriptor = messageDescriptor.FindFieldByName(name); + if (fieldDescriptor == null) + { + throw new KeyNotFoundException("No such field name"); + } + return fieldDescriptor; + } + } + } + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/UnknownField.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/UnknownField.cs new file mode 100644 index 0000000..4793a64 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/UnknownField.cs @@ -0,0 +1,290 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2017 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using Google.Protobuf.Collections; + +namespace Google.Protobuf +{ + /// + /// Represents a single field in an UnknownFieldSet. + /// + /// An UnknownField consists of four lists of values. The lists correspond + /// to the four "wire types" used in the protocol buffer binary format. + /// Normally, only one of the four lists will contain any values, since it + /// is impossible to define a valid message type that declares two different + /// types for the same field number. However, the code is designed to allow + /// for the case where the same unknown field number is encountered using + /// multiple different wire types. + /// + /// + internal sealed class UnknownField + { + private List varintList; + private List fixed32List; + private List fixed64List; + private List lengthDelimitedList; + private List groupList; + + /// + /// Creates a new UnknownField. + /// + public UnknownField() + { + } + + /// + /// Checks if two unknown field are equal. + /// + public override bool Equals(object other) + { + if (ReferenceEquals(this, other)) + { + return true; + } + UnknownField otherField = other as UnknownField; + return otherField != null + && Lists.Equals(varintList, otherField.varintList) + && Lists.Equals(fixed32List, otherField.fixed32List) + && Lists.Equals(fixed64List, otherField.fixed64List) + && Lists.Equals(lengthDelimitedList, otherField.lengthDelimitedList) + && Lists.Equals(groupList, otherField.groupList); + } + + /// + /// Get the hash code of the unknown field. + /// + public override int GetHashCode() + { + int hash = 43; + hash = hash * 47 + Lists.GetHashCode(varintList); + hash = hash * 47 + Lists.GetHashCode(fixed32List); + hash = hash * 47 + Lists.GetHashCode(fixed64List); + hash = hash * 47 + Lists.GetHashCode(lengthDelimitedList); + hash = hash * 47 + Lists.GetHashCode(groupList); + return hash; + } + + /// + /// Serializes the field, including the field number, and writes it to + /// + /// + /// The unknown field number. + /// The write context to write to. + internal void WriteTo(int fieldNumber, ref WriteContext output) + { + if (varintList != null) + { + foreach (ulong value in varintList) + { + output.WriteTag(fieldNumber, WireFormat.WireType.Varint); + output.WriteUInt64(value); + } + } + if (fixed32List != null) + { + foreach (uint value in fixed32List) + { + output.WriteTag(fieldNumber, WireFormat.WireType.Fixed32); + output.WriteFixed32(value); + } + } + if (fixed64List != null) + { + foreach (ulong value in fixed64List) + { + output.WriteTag(fieldNumber, WireFormat.WireType.Fixed64); + output.WriteFixed64(value); + } + } + if (lengthDelimitedList != null) + { + foreach (ByteString value in lengthDelimitedList) + { + output.WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteBytes(value); + } + } + if (groupList != null) + { + foreach (UnknownFieldSet value in groupList) + { + output.WriteTag(fieldNumber, WireFormat.WireType.StartGroup); + value.WriteTo(ref output); + output.WriteTag(fieldNumber, WireFormat.WireType.EndGroup); + } + } + } + + /// + /// Computes the number of bytes required to encode this field, including field + /// number. + /// + internal int GetSerializedSize(int fieldNumber) + { + int result = 0; + if (varintList != null) + { + result += CodedOutputStream.ComputeTagSize(fieldNumber) * varintList.Count; + foreach (ulong value in varintList) + { + result += CodedOutputStream.ComputeUInt64Size(value); + } + } + if (fixed32List != null) + { + result += CodedOutputStream.ComputeTagSize(fieldNumber) * fixed32List.Count; + result += CodedOutputStream.ComputeFixed32Size(1) * fixed32List.Count; + } + if (fixed64List != null) + { + result += CodedOutputStream.ComputeTagSize(fieldNumber) * fixed64List.Count; + result += CodedOutputStream.ComputeFixed64Size(1) * fixed64List.Count; + } + if (lengthDelimitedList != null) + { + result += CodedOutputStream.ComputeTagSize(fieldNumber) * lengthDelimitedList.Count; + foreach (ByteString value in lengthDelimitedList) + { + result += CodedOutputStream.ComputeBytesSize(value); + } + } + if (groupList != null) + { + result += CodedOutputStream.ComputeTagSize(fieldNumber) * 2 * groupList.Count; + foreach (UnknownFieldSet value in groupList) + { + result += value.CalculateSize(); + } + } + return result; + } + + /// + /// Merge the values in into this field. For each list + /// of values, 's values are append to the ones in this + /// field. + /// + internal UnknownField MergeFrom(UnknownField other) + { + varintList = AddAll(varintList, other.varintList); + fixed32List = AddAll(fixed32List, other.fixed32List); + fixed64List = AddAll(fixed64List, other.fixed64List); + lengthDelimitedList = AddAll(lengthDelimitedList, other.lengthDelimitedList); + groupList = AddAll(groupList, other.groupList); + return this; + } + + /// + /// Returns a new list containing all of the given specified values from + /// both the and lists. + /// If is null and is null or empty, + /// null is returned. Otherwise, either a new list is created (if + /// is null) or the elements of are added to . + /// + private static List AddAll(List current, IList extras) + { + if (extras == null || extras.Count == 0) + { + return current; + } + if (current == null) + { + current = new List(extras); + } + else + { + current.AddRange(extras); + } + return current; + } + + /// + /// Adds a varint value. + /// + internal UnknownField AddVarint(ulong value) + { + varintList = Add(varintList, value); + return this; + } + + /// + /// Adds a fixed32 value. + /// + internal UnknownField AddFixed32(uint value) + { + fixed32List = Add(fixed32List, value); + return this; + } + + /// + /// Adds a fixed64 value. + /// + internal UnknownField AddFixed64(ulong value) + { + fixed64List = Add(fixed64List, value); + return this; + } + + /// + /// Adds a length-delimited value. + /// + internal UnknownField AddLengthDelimited(ByteString value) + { + lengthDelimitedList = Add(lengthDelimitedList, value); + return this; + } + + internal UnknownField AddGroup(UnknownFieldSet value) + { + groupList = Add(groupList, value); + return this; + } + + /// + /// Adds to the , creating + /// a new list if is null. The list is returned - either + /// the original reference or the new list. + /// + private static List Add(List list, T value) + { + if (list == null) + { + list = new List(); + } + list.Add(value); + return list; + } + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs new file mode 100644 index 0000000..e981dc2 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs @@ -0,0 +1,375 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/timestamp.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Google.Protobuf.WellKnownTypes { + + /// Holder for reflection information generated from google/protobuf/timestamp.proto + public static partial class TimestampReflection { + + #region Descriptor + /// File descriptor for google/protobuf/timestamp.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static TimestampReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Ch9nb29nbGUvcHJvdG9idWYvdGltZXN0YW1wLnByb3RvEg9nb29nbGUucHJv", + "dG9idWYiKwoJVGltZXN0YW1wEg8KB3NlY29uZHMYASABKAMSDQoFbmFub3MY", + "AiABKAVChQEKE2NvbS5nb29nbGUucHJvdG9idWZCDlRpbWVzdGFtcFByb3Rv", + "UAFaMmdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL3Rp", + "bWVzdGFtcHBi+AEBogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93", + "blR5cGVzYgZwcm90bzM=")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Timestamp), global::Google.Protobuf.WellKnownTypes.Timestamp.Parser, new[]{ "Seconds", "Nanos" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + /// + /// A Timestamp represents a point in time independent of any time zone or local + /// calendar, encoded as a count of seconds and fractions of seconds at + /// nanosecond resolution. The count is relative to an epoch at UTC midnight on + /// January 1, 1970, in the proleptic Gregorian calendar which extends the + /// Gregorian calendar backwards to year one. + /// + /// All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap + /// second table is needed for interpretation, using a [24-hour linear + /// smear](https://developers.google.com/time/smear). + /// + /// The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By + /// restricting to that range, we ensure that we can convert to and from [RFC + /// 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings. + /// + /// # Examples + /// + /// Example 1: Compute Timestamp from POSIX `time()`. + /// + /// Timestamp timestamp; + /// timestamp.set_seconds(time(NULL)); + /// timestamp.set_nanos(0); + /// + /// Example 2: Compute Timestamp from POSIX `gettimeofday()`. + /// + /// struct timeval tv; + /// gettimeofday(&tv, NULL); + /// + /// Timestamp timestamp; + /// timestamp.set_seconds(tv.tv_sec); + /// timestamp.set_nanos(tv.tv_usec * 1000); + /// + /// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. + /// + /// FILETIME ft; + /// GetSystemTimeAsFileTime(&ft); + /// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; + /// + /// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z + /// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. + /// Timestamp timestamp; + /// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); + /// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); + /// + /// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. + /// + /// long millis = System.currentTimeMillis(); + /// + /// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) + /// .setNanos((int) ((millis % 1000) * 1000000)).build(); + /// + /// Example 5: Compute Timestamp from Java `Instant.now()`. + /// + /// Instant now = Instant.now(); + /// + /// Timestamp timestamp = + /// Timestamp.newBuilder().setSeconds(now.getEpochSecond()) + /// .setNanos(now.getNano()).build(); + /// + /// Example 6: Compute Timestamp from current time in Python. + /// + /// timestamp = Timestamp() + /// timestamp.GetCurrentTime() + /// + /// # JSON Mapping + /// + /// In JSON format, the Timestamp type is encoded as a string in the + /// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the + /// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" + /// where {year} is always expressed using four digits while {month}, {day}, + /// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional + /// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), + /// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone + /// is required. A proto3 JSON serializer should always use UTC (as indicated by + /// "Z") when printing the Timestamp type and a proto3 JSON parser should be + /// able to accept both UTC and other timezones (as indicated by an offset). + /// + /// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past + /// 01:30 UTC on January 15, 2017. + /// + /// In JavaScript, one can convert a Date object to this format using the + /// standard + /// [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) + /// method. In Python, a standard `datetime.datetime` object can be converted + /// to this format using + /// [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with + /// the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use + /// the Joda Time's [`ISODateTimeFormat.dateTime()`]( + /// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D + /// ) to obtain a formatter capable of generating timestamps in this format. + /// + public sealed partial class Timestamp : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Timestamp()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Timestamp() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Timestamp(Timestamp other) : this() { + seconds_ = other.seconds_; + nanos_ = other.nanos_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public Timestamp Clone() { + return new Timestamp(this); + } + + /// Field number for the "seconds" field. + public const int SecondsFieldNumber = 1; + private long seconds_; + /// + /// Represents seconds of UTC time since Unix epoch + /// 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + /// 9999-12-31T23:59:59Z inclusive. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public long Seconds { + get { return seconds_; } + set { + seconds_ = value; + } + } + + /// Field number for the "nanos" field. + public const int NanosFieldNumber = 2; + private int nanos_; + /// + /// Non-negative fractions of a second at nanosecond resolution. Negative + /// second values with fractions must still have non-negative nanos values + /// that count forward in time. Must be from 0 to 999,999,999 + /// inclusive. + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int Nanos { + get { return nanos_; } + set { + nanos_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as Timestamp); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(Timestamp other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Seconds != other.Seconds) return false; + if (Nanos != other.Nanos) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (Seconds != 0L) hash ^= Seconds.GetHashCode(); + if (Nanos != 0) hash ^= Nanos.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Seconds != 0L) { + output.WriteRawTag(8); + output.WriteInt64(Seconds); + } + if (Nanos != 0) { + output.WriteRawTag(16); + output.WriteInt32(Nanos); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Seconds != 0L) { + output.WriteRawTag(8); + output.WriteInt64(Seconds); + } + if (Nanos != 0) { + output.WriteRawTag(16); + output.WriteInt32(Nanos); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (Seconds != 0L) { + size += 1 + pb::CodedOutputStream.ComputeInt64Size(Seconds); + } + if (Nanos != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Nanos); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(Timestamp other) { + if (other == null) { + return; + } + if (other.Seconds != 0L) { + Seconds = other.Seconds; + } + if (other.Nanos != 0) { + Nanos = other.Nanos; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Seconds = input.ReadInt64(); + break; + } + case 16: { + Nanos = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Seconds = input.ReadInt64(); + break; + } + case 16: { + Nanos = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/WriterInternalState.cs b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/WriterInternalState.cs new file mode 100644 index 0000000..a779305 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/csharp/src/Google.Protobuf/WriterInternalState.cs @@ -0,0 +1,62 @@ +#region Copyright notice and license +// 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. +#endregion + +using System; +using System.Buffers; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security; +using System.Text; +using Google.Protobuf.Collections; + +namespace Google.Protobuf +{ + + // warning: this is a mutable struct, so it needs to be only passed as a ref! + internal struct WriterInternalState + { + // NOTE: the Span representing the current buffer is kept separate so that this doesn't have to be a ref struct and so it can + // be included in CodedOutputStream's internal state + + internal int limit; // the size of the current buffer + internal int position; // position in the current buffer + + internal WriteBufferHelper writeBufferHelper; + + // If non-null, the top level parse method was started with given coded output stream as an argument + // which also means we can potentially fallback to calling WriteTo(CodedOutputStream cos) if needed. + internal CodedOutputStream CodedOutputStream => writeBufferHelper.CodedOutputStream; + } +} \ No newline at end of file diff --git a/tools/go-generator/cmd/generator/_protobuf/docs/jvm_aot.md b/tools/go-generator/cmd/generator/_protobuf/docs/jvm_aot.md new file mode 100644 index 0000000..4eb682f --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/docs/jvm_aot.md @@ -0,0 +1,18 @@ +# Ahead Of Time (AOT) compilation for the Java Virtual Machine (JVM)" + +Ahead Of Time (AOT) compilation build tools such as those provided by [GraalVM's `native-image`](https://www.graalvm.org/reference-manual/native-image/) can require some configuration when using protobuf. +Protobuf for the JVM uses reflection and some of its target classes are not possible to determine in advance. +Historically, there were good reasons to use reflection based on APIs that were published effectively requiring them, and this situation is unlikely to change. + +[The Lite version of protobuf for the JVM](https://github.com/protocolbuffers/protobuf/blob/master/java/lite.md) +avoids reflection and may be better suited for use with AOT compilation tooling. This Lite version was originally targeted for use on Android which has similar AOT compilation +goals as GraalVM's native-image tool. + +## GraalVM native-image + +This section addresses GraalVM's `native-image` configuration specifically as this AOT compilation tool due to its popularity. The `native-image` tool can be configured +with respect to: the [Java Native Interface](https://en.wikipedia.org/wiki/Java_Native_Interface) (JNI), http proxying, reflection, and other resources. While these +considerations can be manually declared as JSON files, we recommend that a JVM application is exercised along with +[the assisted configuration agent](https://www.graalvm.org/reference-manual/native-image/BuildConfiguration/#assisted-configuration-of-native-image-builds). The agent +will generate files that you can then subsequently point at when invoking `native-image`. We recommend that the generated files are retained with a project's source +code. diff --git a/tools/go-generator/cmd/generator/_protobuf/docs/options.md b/tools/go-generator/cmd/generator/_protobuf/docs/options.md new file mode 100644 index 0000000..e4ca729 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/docs/options.md @@ -0,0 +1,302 @@ +# Protobuf Global Extension Registry + +This file contains a global registry of known extensions for descriptor.proto, +so that any developer who wishes to use multiple 3rd party projects, each with +their own extensions, can be confident that there won't be collisions in +extension numbers. + +If you need an extension number for your custom option (see [custom options]( +https://developers.google.com/protocol-buffers/docs/proto#customoptions)), +please [send us a pull request](https://github.com/protocolbuffers/protobuf/pulls) to +add an entry to this doc, or [create an issue](https://github.com/protocolbuffers/protobuf/issues) +with info about your project (name and website) so we can add an entry for you. + +## Existing Registered Extensions + +1. C# port of protocol buffers + * Website: https://github.com/jskeet/protobuf-csharp-port + * Extensions: 1000 + +1. Perl/XS port of protocol buffers + * Website: http://code.google.com/p/protobuf-perlxs + * Extensions: 1001 + +1. Objective-C port of protocol buffers + * Website: http://code.google.com/p/protobuf-objc + * Extensions: 1002 + +1. Google Wave Federation Protocol open-source release (FedOne) + * Website: http://code.google.com/p/wave-protocol + * Extensions: 1003 + +1. PHP code generator plugin + * Website: ??? + * Extensions: 1004 + +1. GWT code generator plugin (third-party!) + * Website: http://code.google.com/p/protobuf-gwt/ + * Extensions: 1005 + +1. Unix Domain RPC code generator plugin + * Website: http://go/udrpc + * Extensions: 1006 + +1. Object-C generator plugin (Plausible Labs) + * Website: http://www.plausible.coop + * Extensions: 1007 + +1. TBD (code42.com) + * Website: ??? + * Extensions: 1008 + +1. Goby Underwater Autonomy Project + * Website: https://github.com/GobySoft/goby + * Extensions: 1009 + +1. Nanopb + * Website: http://kapsi.fi/~jpa/nanopb + * Extensions: 1010 + +1. Bluefin AUV Communication Extensions + * Website: http://www.bluefinrobotics.com + * Extensions: 1011 + +1. Dynamic Compact Control Language + * Website: http://github.com/GobySoft/dccl + * Extensions: 1012 + +1. ScaleOut StateServer® Native C++ API + * Website: http://www.scaleoutsoftware.com + * Extensions: 1013 + +1. FoundationDB SQL Layer + * Website: https://github.com/FoundationDB/sql-layer + * Extensions: 1014 + +1. Fender + * Website: https://github.com/hassox/fender + * Extensions: 1015 + +1. Vortex + * Website: http://www.prismtech.com/vortex + * Extensions: 1016 + +1. tresorit + * Website: https://tresorit.com/ + * Extensions: 1017 + +1. CRIU (Checkpoint Restore In Userspace) + * Website: http://criu.org/Main_Page + * Extensions: 1018 + +1. protobuf-c + * Website: https://github.com/protobuf-c/protobuf-c + * Extensions: 1019 + +1. ScalaPB + * Website: https://scalapb.github.io/ + * Extensions: 1020 + +1. protoc-gen-bq-schema + * Website: https://github.com/GoogleCloudPlatform/protoc-gen-bq-schema + * Extensions: 1021 + +1. grpc-gateway + * Website: https://github.com/gengo/grpc-gateway + * Extensions: 1022 + +1. Certificate Transparency + * Website: https://github.com/google/certificate-transparency + * Extensions: 1023 + +1. JUNOS Router Telemetry + * Website: http://www.juniper.net + * Extensions: 1024 + +1. Spine Event Engine + * Website: https://github.com/SpineEventEngine/core-java + * Extensions: 1025 + +1. Aruba cloud platform + * Website: ??? + * Extensions: 1026 -> 1030 + +1. Voltha + * Website: ??? + * Extensions: 1031 -> 1033 + +1. gator + * Website: ??? + * Extensions: 1034 + +1. protoc-gen-flowtypes + * Website: https://github.com/tmc/grpcutil/tree/master/protoc-gen-flowtypes + * Extensions: 1035 + +1. ProfaneDB + * Website: https://gitlab.com/ProfaneDB/ProfaneDB + * Extensions: 1036 + +1. protobuf-net + * Website: https://github.com/mgravell/protobuf-net + * Extensions: 1037 + +1. FICO / StreamEngine + * Website: http://www.fico.com/ + * Extensions: 1038 + +1. GopherJS + * Website: https://github.com/johanbrandhorst/protobuf + * Extensions: 1039 + +1. ygot + * Website: https://github.com/openconfig/ygot + * Extensions: 1040 + +1. go-grpcmw + * Website: https://github.com/MarquisIO/go-grpcmw + * Extensions: 1041 + +1. grpc-gateway protoc-gen-swagger + * Website: https://github.com/grpc-ecosystem/grpc-gateway + * Extensions: 1042 + +1. AN Message + * Website: TBD + * Extensions: 1043 + +1. protofire + * Website: https://github.com/ribrdb/protofire + * Extensions: 1044 + +1. Gravity + * Website: https://github.com/aphysci/gravity + * Extensions: 1045 + +1. SEMI Standards – I&C Technical Committee + * Website: http://downloads.semi.org/web/wstdsbal.nsf/9c2b317e76523cca88257641005a47f5/88a5863a580e323088256e7b00707489!OpenDocument + * Extensions: 1046 + +1. Elixir plugin + * Website: https://github.com/tony612/grpc-elixir + * Extensions: 1047 + +1. API client generators + * Website: ??? + * Extensions: 1048-1056 + +1. Netifi Proteus + * Website: https://github.com/netifi-proteus + * Extensions: 1057 + +1. CGSN Mooring Project + * Website: https://bitbucket.org/ooicgsn/cgsn-mooring + * Extensions: 1058 + +1. Container Storage Interface + * Website: https://github.com/container-storage-interface/spec + * Extensions: 1059-1069 + +1. TwirpQL Plugin + * Website: https://twirpql.dev + * Extensions: 1070 + +1. Protoc-gen-validate + * Website: https://github.com/envoyproxy/protoc-gen-validate + * Extensions: 1071 + +1. Protokt + * Website: https://github.com/open-toast/protokt + * Extensions: 1072 + +1. Dart port of protocol buffers + * Website https://github.com/dart-lang/protobuf + * Extensions: 1073 + +1. Ocaml-protoc-plugin + * Website: https://github.com/issuu/ocaml-protoc-plugin + * Extensions: 1074 + +1. Analyze Re Graphene + * Website: https://analyzere.com + * Extensions: 1075 + +1. Wire since and until + * Website: https://square.github.io/wire/ + * Extensions: 1076, 1077 + +1. Bazel, Failure Details + * Website: https://github.com/bazelbuild/bazel + * Extensions: 1078 + +1. grpc-graphql-gateway + * Website: https://github.com/ysugimoto/grpc-graphql-gateway + * Extensions: 1079 + +1. Cloudstate + * Website: https://cloudstate.io + * Extensions: 1080-1084 + +1. SummaFT protoc-plugins + * Website: https://summaft.com/ + * Extensions: 1085 + +1. ADLINK EdgeSDK + * Website: https://www.adlinktech.com/en/Edge-SDK-IoT + * Extensions: 1086 + +1. Wire wire_package + * Website: https://square.github.io/wire/ + * Extensions: 1087 + +1. Confluent Schema Registry + * Website: https://github.com/confluentinc/schema-registry + * Extensions: 1088 + +1. ScalaPB Validate + * Website: https://scalapb.github.io/docs/validation + * Extension: 1089 + +1. Astounding (Currently Private) + * Website: https://github.com/PbPipes/Astounding + * Extension: 1090 + +1. Protoc-gen-psql + * Website: https://github.com/Intrinsec/protoc-gen-psql + * Extension: 1091-1101 + +1. Protoc-gen-sanitize + * Website: https://github.com/Intrinsec/protoc-gen-sanitize + * Extension: 1102-1106 + +1. Coach Client Connect (planned release in March 2021) + * Website: https://www.coachclientconnect.com + * Extension: 1107 + +1. Kratos API Errors + * Website: https://go-kratos.dev + * Extension: 1108 + +1. Glitchdot (Currently Private) + * Website: https://go.glitchdot.com + * Extension: 1109 + +1. eigr/protocol + * Website: https://eigr.io + * Extension: 1110-1114 + +1. Container Object Storage Interface (COSI) + * Website: https://github.com/kubernetes-sigs/container-object-storage-interface-spec + * Extension: 1115-1124 + +1. Protoc-gen-jsonschema + * Website: https://github.com/chrusty/protoc-gen-jsonschema + * Extension: 1125-1129 + +1. Protoc-gen-checker + * Website: https://github.com/Intrinsec/protoc-gen-checker + * Extension: 1130-1139 + +1. Protoc-gen-go-svc + * Website: https://github.com/dane/protoc-gen-go-svc + * Extension: 1140 diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/generate-test-sources-build.xml b/tools/go-generator/cmd/generator/_protobuf/java/core/generate-test-sources-build.xml new file mode 100644 index 0000000..db44a15 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/generate-test-sources-build.xml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/BinaryReader.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/BinaryReader.java new file mode 100644 index 0000000..d64574c --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/BinaryReader.java @@ -0,0 +1,1729 @@ +// 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. + +package com.google.protobuf; + +import static com.google.protobuf.WireFormat.FIXED32_SIZE; +import static com.google.protobuf.WireFormat.FIXED64_SIZE; +import static com.google.protobuf.WireFormat.WIRETYPE_END_GROUP; +import static com.google.protobuf.WireFormat.WIRETYPE_FIXED32; +import static com.google.protobuf.WireFormat.WIRETYPE_FIXED64; +import static com.google.protobuf.WireFormat.WIRETYPE_LENGTH_DELIMITED; +import static com.google.protobuf.WireFormat.WIRETYPE_START_GROUP; +import static com.google.protobuf.WireFormat.WIRETYPE_VARINT; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.List; +import java.util.Map; + +/** + * A {@link Reader} that reads from a buffer containing a message serialized with the binary + * protocol. + */ +@ExperimentalApi +abstract class BinaryReader implements Reader { + private static final int FIXED32_MULTIPLE_MASK = FIXED32_SIZE - 1; + private static final int FIXED64_MULTIPLE_MASK = FIXED64_SIZE - 1; + + /** + * Creates a new reader using the given {@code buffer} as input. + * + * @param buffer the input buffer. The buffer (including position, limit, etc.) will not be + * modified. To increment the buffer position after the read completes, use the value returned + * by {@link #getTotalBytesRead()}. + * @param bufferIsImmutable if {@code true} the reader assumes that the content of {@code buffer} + * will never change and any allocated {@link ByteString} instances will by directly wrap + * slices of {@code buffer}. + * @return the reader + */ + public static BinaryReader newInstance(ByteBuffer buffer, boolean bufferIsImmutable) { + if (buffer.hasArray()) { + // TODO(nathanmittler): Add support for unsafe operations. + return new SafeHeapReader(buffer, bufferIsImmutable); + } + // TODO(nathanmittler): Add support for direct buffers + throw new IllegalArgumentException("Direct buffers not yet supported"); + } + + /** Only allow subclassing for inner classes. */ + private BinaryReader() {} + + /** Returns the total number of bytes read so far from the input buffer. */ + public abstract int getTotalBytesRead(); + + @Override + public boolean shouldDiscardUnknownFields() { + return false; + } + + /** + * A {@link BinaryReader} implementation that operates on a heap {@link ByteBuffer}. Uses only + * safe operations on the underlying array. + */ + private static final class SafeHeapReader extends BinaryReader { + private final boolean bufferIsImmutable; + private final byte[] buffer; + private int pos; + private final int initialPos; + private int limit; + private int tag; + private int endGroupTag; + + public SafeHeapReader(ByteBuffer bytebuf, boolean bufferIsImmutable) { + this.bufferIsImmutable = bufferIsImmutable; + buffer = bytebuf.array(); + initialPos = pos = bytebuf.arrayOffset() + bytebuf.position(); + limit = bytebuf.arrayOffset() + bytebuf.limit(); + } + + private boolean isAtEnd() { + return pos == limit; + } + + @Override + public int getTotalBytesRead() { + return pos - initialPos; + } + + @Override + public int getFieldNumber() throws IOException { + if (isAtEnd()) { + return Reader.READ_DONE; + } + tag = readVarint32(); + if (tag == endGroupTag) { + return Reader.READ_DONE; + } + return WireFormat.getTagFieldNumber(tag); + } + + @Override + public int getTag() { + return tag; + } + + @Override + public boolean skipField() throws IOException { + if (isAtEnd() || tag == endGroupTag) { + return false; + } + + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_VARINT: + skipVarint(); + return true; + case WIRETYPE_FIXED64: + skipBytes(FIXED64_SIZE); + return true; + case WIRETYPE_LENGTH_DELIMITED: + skipBytes(readVarint32()); + return true; + case WIRETYPE_FIXED32: + skipBytes(FIXED32_SIZE); + return true; + case WIRETYPE_START_GROUP: + skipGroup(); + return true; + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + + @Override + public double readDouble() throws IOException { + requireWireType(WIRETYPE_FIXED64); + return Double.longBitsToDouble(readLittleEndian64()); + } + + @Override + public float readFloat() throws IOException { + requireWireType(WIRETYPE_FIXED32); + return Float.intBitsToFloat(readLittleEndian32()); + } + + @Override + public long readUInt64() throws IOException { + requireWireType(WIRETYPE_VARINT); + return readVarint64(); + } + + @Override + public long readInt64() throws IOException { + requireWireType(WIRETYPE_VARINT); + return readVarint64(); + } + + @Override + public int readInt32() throws IOException { + requireWireType(WIRETYPE_VARINT); + return readVarint32(); + } + + @Override + public long readFixed64() throws IOException { + requireWireType(WIRETYPE_FIXED64); + return readLittleEndian64(); + } + + @Override + public int readFixed32() throws IOException { + requireWireType(WIRETYPE_FIXED32); + return readLittleEndian32(); + } + + @Override + public boolean readBool() throws IOException { + requireWireType(WIRETYPE_VARINT); + return readVarint32() != 0; + } + + @Override + public String readString() throws IOException { + return readStringInternal(false); + } + + @Override + public String readStringRequireUtf8() throws IOException { + return readStringInternal(true); + } + + public String readStringInternal(boolean requireUtf8) throws IOException { + requireWireType(WIRETYPE_LENGTH_DELIMITED); + final int size = readVarint32(); + if (size == 0) { + return ""; + } + + requireBytes(size); + if (requireUtf8 && !Utf8.isValidUtf8(buffer, pos, pos + size)) { + throw InvalidProtocolBufferException.invalidUtf8(); + } + String result = new String(buffer, pos, size, Internal.UTF_8); + pos += size; + return result; + } + + @Override + public T readMessage(Class clazz, ExtensionRegistryLite extensionRegistry) + throws IOException { + requireWireType(WIRETYPE_LENGTH_DELIMITED); + return readMessage(Protobuf.getInstance().schemaFor(clazz), extensionRegistry); + } + + @Override + public T readMessageBySchemaWithCheck( + Schema schema, ExtensionRegistryLite extensionRegistry) throws IOException { + requireWireType(WIRETYPE_LENGTH_DELIMITED); + return readMessage(schema, extensionRegistry); + } + + private T readMessage(Schema schema, ExtensionRegistryLite extensionRegistry) + throws IOException { + int size = readVarint32(); + requireBytes(size); + + // Update the limit. + int prevLimit = limit; + int newLimit = pos + size; + limit = newLimit; + + try { + // Allocate and read the message. + T message = schema.newInstance(); + schema.mergeFrom(message, this, extensionRegistry); + schema.makeImmutable(message); + + if (pos != newLimit) { + throw InvalidProtocolBufferException.parseFailure(); + } + return message; + } finally { + // Restore the limit. + limit = prevLimit; + } + } + + @Override + public T readGroup(Class clazz, ExtensionRegistryLite extensionRegistry) + throws IOException { + requireWireType(WIRETYPE_START_GROUP); + return readGroup(Protobuf.getInstance().schemaFor(clazz), extensionRegistry); + } + + @Override + public T readGroupBySchemaWithCheck( + Schema schema, ExtensionRegistryLite extensionRegistry) throws IOException { + requireWireType(WIRETYPE_START_GROUP); + return readGroup(schema, extensionRegistry); + } + + private T readGroup(Schema schema, ExtensionRegistryLite extensionRegistry) + throws IOException { + int prevEndGroupTag = endGroupTag; + endGroupTag = WireFormat.makeTag(WireFormat.getTagFieldNumber(tag), WIRETYPE_END_GROUP); + + try { + // Allocate and read the message. + T message = schema.newInstance(); + schema.mergeFrom(message, this, extensionRegistry); + schema.makeImmutable(message); + + if (tag != endGroupTag) { + throw InvalidProtocolBufferException.parseFailure(); + } + return message; + } finally { + // Restore the old end group tag. + endGroupTag = prevEndGroupTag; + } + } + + @Override + public ByteString readBytes() throws IOException { + requireWireType(WIRETYPE_LENGTH_DELIMITED); + int size = readVarint32(); + if (size == 0) { + return ByteString.EMPTY; + } + + requireBytes(size); + ByteString bytes = + bufferIsImmutable + ? ByteString.wrap(buffer, pos, size) + : ByteString.copyFrom(buffer, pos, size); + pos += size; + return bytes; + } + + @Override + public int readUInt32() throws IOException { + requireWireType(WIRETYPE_VARINT); + return readVarint32(); + } + + @Override + public int readEnum() throws IOException { + requireWireType(WIRETYPE_VARINT); + return readVarint32(); + } + + @Override + public int readSFixed32() throws IOException { + requireWireType(WIRETYPE_FIXED32); + return readLittleEndian32(); + } + + @Override + public long readSFixed64() throws IOException { + requireWireType(WIRETYPE_FIXED64); + return readLittleEndian64(); + } + + @Override + public int readSInt32() throws IOException { + requireWireType(WIRETYPE_VARINT); + return CodedInputStream.decodeZigZag32(readVarint32()); + } + + @Override + public long readSInt64() throws IOException { + requireWireType(WIRETYPE_VARINT); + return CodedInputStream.decodeZigZag64(readVarint64()); + } + + @Override + public void readDoubleList(List target) throws IOException { + if (target instanceof DoubleArrayList) { + DoubleArrayList plist = (DoubleArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed64Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addDouble(Double.longBitsToDouble(readLittleEndian64_NoCheck())); + } + break; + case WIRETYPE_FIXED64: + while (true) { + plist.addDouble(readDouble()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed64Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(Double.longBitsToDouble(readLittleEndian64_NoCheck())); + } + break; + case WIRETYPE_FIXED64: + while (true) { + target.add(readDouble()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readFloatList(List target) throws IOException { + if (target instanceof FloatArrayList) { + FloatArrayList plist = (FloatArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed32Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addFloat(Float.intBitsToFloat(readLittleEndian32_NoCheck())); + } + break; + case WIRETYPE_FIXED32: + while (true) { + plist.addFloat(readFloat()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed32Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(Float.intBitsToFloat(readLittleEndian32_NoCheck())); + } + break; + case WIRETYPE_FIXED32: + while (true) { + target.add(readFloat()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readUInt64List(List target) throws IOException { + if (target instanceof LongArrayList) { + LongArrayList plist = (LongArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addLong(readVarint64()); + } + requirePosition(fieldEndPos); + break; + case WIRETYPE_VARINT: + while (true) { + plist.addLong(readUInt64()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(readVarint64()); + } + requirePosition(fieldEndPos); + break; + case WIRETYPE_VARINT: + while (true) { + target.add(readUInt64()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readInt64List(List target) throws IOException { + if (target instanceof LongArrayList) { + LongArrayList plist = (LongArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addLong(readVarint64()); + } + requirePosition(fieldEndPos); + break; + case WIRETYPE_VARINT: + while (true) { + plist.addLong(readInt64()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(readVarint64()); + } + requirePosition(fieldEndPos); + break; + case WIRETYPE_VARINT: + while (true) { + target.add(readInt64()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readInt32List(List target) throws IOException { + if (target instanceof IntArrayList) { + IntArrayList plist = (IntArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addInt(readVarint32()); + } + requirePosition(fieldEndPos); + break; + case WIRETYPE_VARINT: + while (true) { + plist.addInt(readInt32()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(readVarint32()); + } + requirePosition(fieldEndPos); + break; + case WIRETYPE_VARINT: + while (true) { + target.add(readInt32()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readFixed64List(List target) throws IOException { + if (target instanceof LongArrayList) { + LongArrayList plist = (LongArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed64Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addLong(readLittleEndian64_NoCheck()); + } + break; + case WIRETYPE_FIXED64: + while (true) { + plist.addLong(readFixed64()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed64Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(readLittleEndian64_NoCheck()); + } + break; + case WIRETYPE_FIXED64: + while (true) { + target.add(readFixed64()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readFixed32List(List target) throws IOException { + if (target instanceof IntArrayList) { + IntArrayList plist = (IntArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed32Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addInt(readLittleEndian32_NoCheck()); + } + break; + case WIRETYPE_FIXED32: + while (true) { + plist.addInt(readFixed32()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed32Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(readLittleEndian32_NoCheck()); + } + break; + case WIRETYPE_FIXED32: + while (true) { + target.add(readFixed32()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readBoolList(List target) throws IOException { + if (target instanceof BooleanArrayList) { + BooleanArrayList plist = (BooleanArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addBoolean(readVarint32() != 0); + } + requirePosition(fieldEndPos); + break; + case WIRETYPE_VARINT: + while (true) { + plist.addBoolean(readBool()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(readVarint32() != 0); + } + requirePosition(fieldEndPos); + break; + case WIRETYPE_VARINT: + while (true) { + target.add(readBool()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readStringList(List target) throws IOException { + readStringListInternal(target, false); + } + + @Override + public void readStringListRequireUtf8(List target) throws IOException { + readStringListInternal(target, true); + } + + public void readStringListInternal(List target, boolean requireUtf8) + throws IOException { + if (WireFormat.getTagWireType(tag) != WIRETYPE_LENGTH_DELIMITED) { + throw InvalidProtocolBufferException.invalidWireType(); + } + + if (target instanceof LazyStringList && !requireUtf8) { + LazyStringList lazyList = (LazyStringList) target; + while (true) { + lazyList.add(readBytes()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + } else { + while (true) { + target.add(readStringInternal(requireUtf8)); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + } + } + + @Override + public void readMessageList( + List target, Class targetType, ExtensionRegistryLite extensionRegistry) + throws IOException { + final Schema schema = Protobuf.getInstance().schemaFor(targetType); + readMessageList(target, schema, extensionRegistry); + } + + @Override + public void readMessageList( + List target, Schema schema, ExtensionRegistryLite extensionRegistry) + throws IOException { + if (WireFormat.getTagWireType(tag) != WIRETYPE_LENGTH_DELIMITED) { + throw InvalidProtocolBufferException.invalidWireType(); + } + final int listTag = tag; + while (true) { + target.add(readMessage(schema, extensionRegistry)); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != listTag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + } + + @Override + public void readGroupList( + List target, Class targetType, ExtensionRegistryLite extensionRegistry) + throws IOException { + final Schema schema = Protobuf.getInstance().schemaFor(targetType); + readGroupList(target, schema, extensionRegistry); + } + + @Override + public void readGroupList( + List target, Schema schema, ExtensionRegistryLite extensionRegistry) + throws IOException { + if (WireFormat.getTagWireType(tag) != WIRETYPE_START_GROUP) { + throw InvalidProtocolBufferException.invalidWireType(); + } + final int listTag = tag; + while (true) { + target.add(readGroup(schema, extensionRegistry)); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != listTag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + } + + @Override + public void readBytesList(List target) throws IOException { + if (WireFormat.getTagWireType(tag) != WIRETYPE_LENGTH_DELIMITED) { + throw InvalidProtocolBufferException.invalidWireType(); + } + + while (true) { + target.add(readBytes()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + } + + @Override + public void readUInt32List(List target) throws IOException { + if (target instanceof IntArrayList) { + IntArrayList plist = (IntArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addInt(readVarint32()); + } + break; + case WIRETYPE_VARINT: + while (true) { + plist.addInt(readUInt32()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(readVarint32()); + } + break; + case WIRETYPE_VARINT: + while (true) { + target.add(readUInt32()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readEnumList(List target) throws IOException { + if (target instanceof IntArrayList) { + IntArrayList plist = (IntArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addInt(readVarint32()); + } + break; + case WIRETYPE_VARINT: + while (true) { + plist.addInt(readEnum()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(readVarint32()); + } + break; + case WIRETYPE_VARINT: + while (true) { + target.add(readEnum()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readSFixed32List(List target) throws IOException { + if (target instanceof IntArrayList) { + IntArrayList plist = (IntArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed32Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addInt(readLittleEndian32_NoCheck()); + } + break; + case WIRETYPE_FIXED32: + while (true) { + plist.addInt(readSFixed32()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed32Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(readLittleEndian32_NoCheck()); + } + break; + case WIRETYPE_FIXED32: + while (true) { + target.add(readSFixed32()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readSFixed64List(List target) throws IOException { + if (target instanceof LongArrayList) { + LongArrayList plist = (LongArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed64Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addLong(readLittleEndian64_NoCheck()); + } + break; + case WIRETYPE_FIXED64: + while (true) { + plist.addLong(readSFixed64()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + verifyPackedFixed64Length(bytes); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(readLittleEndian64_NoCheck()); + } + break; + case WIRETYPE_FIXED64: + while (true) { + target.add(readSFixed64()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readSInt32List(List target) throws IOException { + if (target instanceof IntArrayList) { + IntArrayList plist = (IntArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addInt(CodedInputStream.decodeZigZag32(readVarint32())); + } + break; + case WIRETYPE_VARINT: + while (true) { + plist.addInt(readSInt32()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(CodedInputStream.decodeZigZag32(readVarint32())); + } + break; + case WIRETYPE_VARINT: + while (true) { + target.add(readSInt32()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @Override + public void readSInt64List(List target) throws IOException { + if (target instanceof LongArrayList) { + LongArrayList plist = (LongArrayList) target; + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + plist.addLong(CodedInputStream.decodeZigZag64(readVarint64())); + } + break; + case WIRETYPE_VARINT: + while (true) { + plist.addLong(readSInt64()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } else { + switch (WireFormat.getTagWireType(tag)) { + case WIRETYPE_LENGTH_DELIMITED: + final int bytes = readVarint32(); + final int fieldEndPos = pos + bytes; + while (pos < fieldEndPos) { + target.add(CodedInputStream.decodeZigZag64(readVarint64())); + } + break; + case WIRETYPE_VARINT: + while (true) { + target.add(readSInt64()); + + if (isAtEnd()) { + return; + } + int prevPos = pos; + int nextTag = readVarint32(); + if (nextTag != tag) { + // We've reached the end of the repeated field. Rewind the buffer position to before + // the new tag. + pos = prevPos; + return; + } + } + default: + throw InvalidProtocolBufferException.invalidWireType(); + } + } + } + + @SuppressWarnings("unchecked") + @Override + public void readMap( + Map target, + MapEntryLite.Metadata metadata, + ExtensionRegistryLite extensionRegistry) + throws IOException { + requireWireType(WIRETYPE_LENGTH_DELIMITED); + int size = readVarint32(); + requireBytes(size); + + // Update the limit. + int prevLimit = limit; + int newLimit = pos + size; + limit = newLimit; + + try { + K key = metadata.defaultKey; + V value = metadata.defaultValue; + while (true) { + int number = getFieldNumber(); + if (number == READ_DONE) { + break; + } + try { + switch (number) { + case 1: + key = (K) readField(metadata.keyType, null, null); + break; + case 2: + value = + (V) + readField( + metadata.valueType, + metadata.defaultValue.getClass(), + extensionRegistry); + break; + default: + if (!skipField()) { + throw new InvalidProtocolBufferException("Unable to parse map entry."); + } + break; + } + } catch (InvalidProtocolBufferException.InvalidWireTypeException ignore) { + // the type doesn't match, skip the field. + if (!skipField()) { + throw new InvalidProtocolBufferException("Unable to parse map entry."); + } + } + } + target.put(key, value); + } finally { + // Restore the limit. + limit = prevLimit; + } + } + + private Object readField( + WireFormat.FieldType fieldType, + Class messageType, + ExtensionRegistryLite extensionRegistry) + throws IOException { + switch (fieldType) { + case BOOL: + return readBool(); + case BYTES: + return readBytes(); + case DOUBLE: + return readDouble(); + case ENUM: + return readEnum(); + case FIXED32: + return readFixed32(); + case FIXED64: + return readFixed64(); + case FLOAT: + return readFloat(); + case INT32: + return readInt32(); + case INT64: + return readInt64(); + case MESSAGE: + return readMessage(messageType, extensionRegistry); + case SFIXED32: + return readSFixed32(); + case SFIXED64: + return readSFixed64(); + case SINT32: + return readSInt32(); + case SINT64: + return readSInt64(); + case STRING: + return readStringRequireUtf8(); + case UINT32: + return readUInt32(); + case UINT64: + return readUInt64(); + default: + throw new RuntimeException("unsupported field type."); + } + } + + /** Read a raw Varint from the stream. If larger than 32 bits, discard the upper bits. */ + private int readVarint32() throws IOException { + // See implementation notes for readRawVarint64 + int i = pos; + + if (limit == pos) { + throw InvalidProtocolBufferException.truncatedMessage(); + } + + int x; + if ((x = buffer[i++]) >= 0) { + pos = i; + return x; + } else if (limit - i < 9) { + return (int) readVarint64SlowPath(); + } else if ((x ^= (buffer[i++] << 7)) < 0) { + x ^= (~0 << 7); + } else if ((x ^= (buffer[i++] << 14)) >= 0) { + x ^= (~0 << 7) ^ (~0 << 14); + } else if ((x ^= (buffer[i++] << 21)) < 0) { + x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21); + } else { + int y = buffer[i++]; + x ^= y << 28; + x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21) ^ (~0 << 28); + if (y < 0 + && buffer[i++] < 0 + && buffer[i++] < 0 + && buffer[i++] < 0 + && buffer[i++] < 0 + && buffer[i++] < 0) { + throw InvalidProtocolBufferException.malformedVarint(); + } + } + pos = i; + return x; + } + + public long readVarint64() throws IOException { + // Implementation notes: + // + // Optimized for one-byte values, expected to be common. + // The particular code below was selected from various candidates + // empirically, by winning VarintBenchmark. + // + // Sign extension of (signed) Java bytes is usually a nuisance, but + // we exploit it here to more easily obtain the sign of bytes read. + // Instead of cleaning up the sign extension bits by masking eagerly, + // we delay until we find the final (positive) byte, when we clear all + // accumulated bits with one xor. We depend on javac to constant fold. + int i = pos; + + if (limit == i) { + throw InvalidProtocolBufferException.truncatedMessage(); + } + + final byte[] buffer = this.buffer; + long x; + int y; + if ((y = buffer[i++]) >= 0) { + pos = i; + return y; + } else if (limit - i < 9) { + return readVarint64SlowPath(); + } else if ((y ^= (buffer[i++] << 7)) < 0) { + x = y ^ (~0 << 7); + } else if ((y ^= (buffer[i++] << 14)) >= 0) { + x = y ^ ((~0 << 7) ^ (~0 << 14)); + } else if ((y ^= (buffer[i++] << 21)) < 0) { + x = y ^ ((~0 << 7) ^ (~0 << 14) ^ (~0 << 21)); + } else if ((x = y ^ ((long) buffer[i++] << 28)) >= 0L) { + x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28); + } else if ((x ^= ((long) buffer[i++] << 35)) < 0L) { + x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35); + } else if ((x ^= ((long) buffer[i++] << 42)) >= 0L) { + x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42); + } else if ((x ^= ((long) buffer[i++] << 49)) < 0L) { + x ^= + (~0L << 7) + ^ (~0L << 14) + ^ (~0L << 21) + ^ (~0L << 28) + ^ (~0L << 35) + ^ (~0L << 42) + ^ (~0L << 49); + } else { + x ^= ((long) buffer[i++] << 56); + x ^= + (~0L << 7) + ^ (~0L << 14) + ^ (~0L << 21) + ^ (~0L << 28) + ^ (~0L << 35) + ^ (~0L << 42) + ^ (~0L << 49) + ^ (~0L << 56); + if (x < 0L) { + if (buffer[i++] < 0L) { + throw InvalidProtocolBufferException.malformedVarint(); + } + } + } + pos = i; + return x; + } + + private long readVarint64SlowPath() throws IOException { + long result = 0; + for (int shift = 0; shift < 64; shift += 7) { + final byte b = readByte(); + result |= (long) (b & 0x7F) << shift; + if ((b & 0x80) == 0) { + return result; + } + } + throw InvalidProtocolBufferException.malformedVarint(); + } + + private byte readByte() throws IOException { + if (pos == limit) { + throw InvalidProtocolBufferException.truncatedMessage(); + } + return buffer[pos++]; + } + + private int readLittleEndian32() throws IOException { + requireBytes(FIXED32_SIZE); + return readLittleEndian32_NoCheck(); + } + + private long readLittleEndian64() throws IOException { + requireBytes(FIXED64_SIZE); + return readLittleEndian64_NoCheck(); + } + + private int readLittleEndian32_NoCheck() { + int p = pos; + final byte[] buffer = this.buffer; + pos = p + FIXED32_SIZE; + return (((buffer[p] & 0xff)) + | ((buffer[p + 1] & 0xff) << 8) + | ((buffer[p + 2] & 0xff) << 16) + | ((buffer[p + 3] & 0xff) << 24)); + } + + private long readLittleEndian64_NoCheck() { + int p = pos; + final byte[] buffer = this.buffer; + pos = p + FIXED64_SIZE; + return (((buffer[p] & 0xffL)) + | ((buffer[p + 1] & 0xffL) << 8) + | ((buffer[p + 2] & 0xffL) << 16) + | ((buffer[p + 3] & 0xffL) << 24) + | ((buffer[p + 4] & 0xffL) << 32) + | ((buffer[p + 5] & 0xffL) << 40) + | ((buffer[p + 6] & 0xffL) << 48) + | ((buffer[p + 7] & 0xffL) << 56)); + } + + private void skipVarint() throws IOException { + if (limit - pos >= 10) { + final byte[] buffer = this.buffer; + int p = pos; + for (int i = 0; i < 10; i++) { + if (buffer[p++] >= 0) { + pos = p; + return; + } + } + } + skipVarintSlowPath(); + } + + private void skipVarintSlowPath() throws IOException { + for (int i = 0; i < 10; i++) { + if (readByte() >= 0) { + return; + } + } + throw InvalidProtocolBufferException.malformedVarint(); + } + + private void skipBytes(final int size) throws IOException { + requireBytes(size); + + pos += size; + } + + private void skipGroup() throws IOException { + int prevEndGroupTag = endGroupTag; + endGroupTag = WireFormat.makeTag(WireFormat.getTagFieldNumber(tag), WIRETYPE_END_GROUP); + while (true) { + if (getFieldNumber() == READ_DONE || !skipField()) { + break; + } + } + if (tag != endGroupTag) { + throw InvalidProtocolBufferException.parseFailure(); + } + endGroupTag = prevEndGroupTag; + } + + private void requireBytes(int size) throws IOException { + if (size < 0 || size > (limit - pos)) { + throw InvalidProtocolBufferException.truncatedMessage(); + } + } + + private void requireWireType(int requiredWireType) throws IOException { + if (WireFormat.getTagWireType(tag) != requiredWireType) { + throw InvalidProtocolBufferException.invalidWireType(); + } + } + + private void verifyPackedFixed64Length(int bytes) throws IOException { + requireBytes(bytes); + if ((bytes & FIXED64_MULTIPLE_MASK) != 0) { + // Require that the number of bytes be a multiple of 8. + throw InvalidProtocolBufferException.parseFailure(); + } + } + + private void verifyPackedFixed32Length(int bytes) throws IOException { + requireBytes(bytes); + if ((bytes & FIXED32_MULTIPLE_MASK) != 0) { + // Require that the number of bytes be a multiple of 4. + throw InvalidProtocolBufferException.parseFailure(); + } + } + + private void requirePosition(int expectedPosition) throws IOException { + if (pos != expectedPosition) { + throw InvalidProtocolBufferException.truncatedMessage(); + } + } + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/ByteBufferWriter.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/ByteBufferWriter.java new file mode 100644 index 0000000..2cb3ada --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/ByteBufferWriter.java @@ -0,0 +1,181 @@ +// 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. + +package com.google.protobuf; + +import static java.lang.Math.max; +import static java.lang.Math.min; + +import java.io.IOException; +import java.io.OutputStream; +import java.lang.ref.SoftReference; +import java.lang.reflect.Field; +import java.nio.ByteBuffer; +import java.nio.channels.WritableByteChannel; + +/** Utility class to provide efficient writing of {@link ByteBuffer}s to {@link OutputStream}s. */ +final class ByteBufferWriter { + private ByteBufferWriter() {} + + /** + * Minimum size for a cached buffer. This prevents us from allocating buffers that are too small + * to be easily reused. + */ + // TODO(nathanmittler): tune this property or allow configuration? + private static final int MIN_CACHED_BUFFER_SIZE = 1024; + + /** + * Maximum size for a cached buffer. If a larger buffer is required, it will be allocated but not + * cached. + */ + // TODO(nathanmittler): tune this property or allow configuration? + private static final int MAX_CACHED_BUFFER_SIZE = 16 * 1024; + + /** The fraction of the requested buffer size under which the buffer will be reallocated. */ + // TODO(nathanmittler): tune this property or allow configuration? + private static final float BUFFER_REALLOCATION_THRESHOLD = 0.5f; + + /** + * Keeping a soft reference to a thread-local buffer. This buffer is used for writing a {@link + * ByteBuffer} to an {@link OutputStream} when no zero-copy alternative was available. Using a + * "soft" reference since VMs may keep this reference around longer than "weak" (e.g. HotSpot will + * maintain soft references until memory pressure warrants collection). + */ + private static final ThreadLocal> BUFFER = + new ThreadLocal>(); + + /** This is a hack for GAE, where {@code FileOutputStream} is unavailable. */ + private static final Class FILE_OUTPUT_STREAM_CLASS = safeGetClass("java.io.FileOutputStream"); + + private static final long CHANNEL_FIELD_OFFSET = getChannelFieldOffset(FILE_OUTPUT_STREAM_CLASS); + + /** + * For testing purposes only. Clears the cached buffer to force a new allocation on the next + * invocation. + */ + static void clearCachedBuffer() { + BUFFER.set(null); + } + + /** + * Writes the remaining content of the buffer to the given stream. The buffer {@code position} + * will remain unchanged by this method. + */ + static void write(ByteBuffer buffer, OutputStream output) throws IOException { + final int initialPos = buffer.position(); + try { + if (buffer.hasArray()) { + // Optimized write for array-backed buffers. + // Note that we're taking the risk that a malicious OutputStream could modify the array. + output.write(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()); + } else if (!writeToChannel(buffer, output)) { + // Read all of the data from the buffer to an array. + // TODO(nathanmittler): Consider performance improvements for other "known" stream types. + final byte[] array = getOrCreateBuffer(buffer.remaining()); + while (buffer.hasRemaining()) { + int length = min(buffer.remaining(), array.length); + buffer.get(array, 0, length); + output.write(array, 0, length); + } + } + } finally { + // Restore the initial position. + buffer.position(initialPos); + } + } + + private static byte[] getOrCreateBuffer(int requestedSize) { + requestedSize = max(requestedSize, MIN_CACHED_BUFFER_SIZE); + + byte[] buffer = getBuffer(); + // Only allocate if we need to. + if (buffer == null || needToReallocate(requestedSize, buffer.length)) { + buffer = new byte[requestedSize]; + + // Only cache the buffer if it's not too big. + if (requestedSize <= MAX_CACHED_BUFFER_SIZE) { + setBuffer(buffer); + } + } + return buffer; + } + + private static boolean needToReallocate(int requestedSize, int bufferLength) { + // First check against just the requested length to avoid the multiply. + return bufferLength < requestedSize + && bufferLength < requestedSize * BUFFER_REALLOCATION_THRESHOLD; + } + + private static byte[] getBuffer() { + SoftReference sr = BUFFER.get(); + return sr == null ? null : sr.get(); + } + + private static void setBuffer(byte[] value) { + BUFFER.set(new SoftReference(value)); + } + + private static boolean writeToChannel(ByteBuffer buffer, OutputStream output) throws IOException { + if (CHANNEL_FIELD_OFFSET >= 0 && FILE_OUTPUT_STREAM_CLASS.isInstance(output)) { + // Use a channel to write out the ByteBuffer. This will automatically empty the buffer. + WritableByteChannel channel = null; + try { + channel = (WritableByteChannel) UnsafeUtil.getObject(output, CHANNEL_FIELD_OFFSET); + } catch (ClassCastException e) { + // Absorb. + } + if (channel != null) { + channel.write(buffer); + return true; + } + } + return false; + } + + private static Class safeGetClass(String className) { + try { + return Class.forName(className); + } catch (ClassNotFoundException e) { + return null; + } + } + + private static long getChannelFieldOffset(Class clazz) { + try { + if (clazz != null && UnsafeUtil.hasUnsafeArrayOperations()) { + Field field = clazz.getDeclaredField("channel"); + return UnsafeUtil.objectFieldOffset(field); + } + } catch (Throwable e) { + // Absorb + } + return -1; + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/DescriptorMessageInfoFactory.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/DescriptorMessageInfoFactory.java new file mode 100644 index 0000000..adee556 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/DescriptorMessageInfoFactory.java @@ -0,0 +1,793 @@ +// 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. + +package com.google.protobuf; + +import static com.google.protobuf.FieldInfo.forField; +import static com.google.protobuf.FieldInfo.forFieldWithEnumVerifier; +import static com.google.protobuf.FieldInfo.forMapField; +import static com.google.protobuf.FieldInfo.forOneofMemberField; +import static com.google.protobuf.FieldInfo.forPackedField; +import static com.google.protobuf.FieldInfo.forPackedFieldWithEnumVerifier; +import static com.google.protobuf.FieldInfo.forProto2OptionalField; +import static com.google.protobuf.FieldInfo.forProto2RequiredField; +import static com.google.protobuf.FieldInfo.forRepeatedMessageField; + +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Descriptors.FieldDescriptor.Type; +import com.google.protobuf.Descriptors.OneofDescriptor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Stack; +import java.util.concurrent.ConcurrentHashMap; + +/** A factory for message info based on protobuf descriptors for a {@link GeneratedMessageV3}. */ +@ExperimentalApi +final class DescriptorMessageInfoFactory implements MessageInfoFactory { + private static final String GET_DEFAULT_INSTANCE_METHOD_NAME = "getDefaultInstance"; + private static final DescriptorMessageInfoFactory instance = new DescriptorMessageInfoFactory(); + + /** + * Names that should be avoided (in UpperCamelCase format). + * Using them causes the compiler to generate accessors whose names + * collide with methods defined in base classes. + * + * Keep this list in sync with kForbiddenWordList in + * src/google/protobuf/compiler/java/java_helpers.cc + */ + private static final Set specialFieldNames = + new HashSet<>(Arrays.asList( + // java.lang.Object: + "Class", + // com.google.protobuf.MessageLiteOrBuilder: + "DefaultInstanceForType", + // com.google.protobuf.MessageLite: + "ParserForType", + "SerializedSize", + // com.google.protobuf.MessageOrBuilder: + "AllFields", + "DescriptorForType", + "InitializationErrorString", + "UnknownFields", + // obsolete. kept for backwards compatibility of generated code + "CachedSize")); + + // Disallow construction - it's a singleton. + private DescriptorMessageInfoFactory() {} + + public static DescriptorMessageInfoFactory getInstance() { + return instance; + } + + @Override + public boolean isSupported(Class messageType) { + return GeneratedMessageV3.class.isAssignableFrom(messageType); + } + + @Override + public MessageInfo messageInfoFor(Class messageType) { + if (!GeneratedMessageV3.class.isAssignableFrom(messageType)) { + throw new IllegalArgumentException("Unsupported message type: " + messageType.getName()); + } + + return convert(messageType, descriptorForType(messageType)); + } + + private static Message getDefaultInstance(Class messageType) { + try { + Method method = messageType.getDeclaredMethod(GET_DEFAULT_INSTANCE_METHOD_NAME); + return (Message) method.invoke(null); + } catch (Exception e) { + throw new IllegalArgumentException( + "Unable to get default instance for message class " + messageType.getName(), e); + } + } + + private static Descriptor descriptorForType(Class messageType) { + return getDefaultInstance(messageType).getDescriptorForType(); + } + + private static MessageInfo convert(Class messageType, Descriptor messageDescriptor) { + switch (messageDescriptor.getFile().getSyntax()) { + case PROTO2: + return convertProto2(messageType, messageDescriptor); + case PROTO3: + return convertProto3(messageType, messageDescriptor); + default: + throw new IllegalArgumentException( + "Unsupported syntax: " + messageDescriptor.getFile().getSyntax()); + } + } + + /** + * A helper class to determine whether a message type needs to implement {@code isInitialized()}. + * + *

If a message type doesn't have any required fields or extensions (directly and + * transitively), it doesn't need to implement isInitialized() and can always return true there. + * It's a bit tricky to determine whether a type has transitive required fields because protobuf + * allows cycle references within the same .proto file (e.g., message Foo has a Bar field, and + * message Bar has a Foo field). For that we use Tarjan's strongly connected components algorithm + * to classify messages into strongly connected groups. Messages in the same group are + * transitively including each other, so they should either all have transitive required fields + * (or extensions), or none have. + * + *

This class is thread-safe. + */ + static class IsInitializedCheckAnalyzer { + + private final Map resultCache = + new ConcurrentHashMap(); + + // The following data members are part of Tarjan's SCC algorithm. See: + // https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm + private int index = 0; + private final Stack stack = new Stack(); + private final Map nodeCache = new HashMap(); + + public boolean needsIsInitializedCheck(Descriptor descriptor) { + Boolean cachedValue = resultCache.get(descriptor); + if (cachedValue != null) { + return cachedValue; + } + synchronized (this) { + // Double-check the cache because some other thread may have updated it while we + // were acquiring the lock. + cachedValue = resultCache.get(descriptor); + if (cachedValue != null) { + return cachedValue; + } + return dfs(descriptor).component.needsIsInitializedCheck; + } + } + + private static class Node { + final Descriptor descriptor; + final int index; + int lowLink; + StronglyConnectedComponent component; // null if the node is still on stack. + + Node(Descriptor descriptor, int index) { + this.descriptor = descriptor; + this.index = index; + this.lowLink = index; + this.component = null; + } + } + + private static class StronglyConnectedComponent { + final List messages = new ArrayList(); + boolean needsIsInitializedCheck = false; + } + + private Node dfs(Descriptor descriptor) { + Node result = new Node(descriptor, index++); + stack.push(result); + nodeCache.put(descriptor, result); + + // Recurse the fields / nodes in graph + for (FieldDescriptor field : descriptor.getFields()) { + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + Node child = nodeCache.get(field.getMessageType()); + if (child == null) { + // Unexplored node + child = dfs(field.getMessageType()); + result.lowLink = Math.min(result.lowLink, child.lowLink); + } else { + if (child.component == null) { + // Still in the stack so we found a back edge. + result.lowLink = Math.min(result.lowLink, child.lowLink); + } + } + } + } + + if (result.index == result.lowLink) { + // This is the root of a strongly connected component. + StronglyConnectedComponent component = new StronglyConnectedComponent(); + while (true) { + Node node = stack.pop(); + node.component = component; + component.messages.add(node.descriptor); + if (node == result) { + break; + } + } + + analyze(component); + } + + return result; + } + + // Determine whether messages in this SCC needs isInitialized check. + private void analyze(StronglyConnectedComponent component) { + boolean needsIsInitializedCheck = false; + loop: + for (Descriptor descriptor : component.messages) { + if (descriptor.isExtendable()) { + needsIsInitializedCheck = true; + break; + } + + for (FieldDescriptor field : descriptor.getFields()) { + if (field.isRequired()) { + needsIsInitializedCheck = true; + break loop; + } + + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + // Since we are analyzing the graph bottom-up, all referenced fields should either be + // in this same component or in a different already-analyzed component. + Node node = nodeCache.get(field.getMessageType()); + if (node.component != component) { + if (node.component.needsIsInitializedCheck) { + needsIsInitializedCheck = true; + break loop; + } + } + } + } + } + + component.needsIsInitializedCheck = needsIsInitializedCheck; + + for (Descriptor descriptor : component.messages) { + resultCache.put(descriptor, component.needsIsInitializedCheck); + } + } + } + + private static IsInitializedCheckAnalyzer isInitializedCheckAnalyzer = + new IsInitializedCheckAnalyzer(); + + private static boolean needsIsInitializedCheck(Descriptor descriptor) { + return isInitializedCheckAnalyzer.needsIsInitializedCheck(descriptor); + } + + private static StructuralMessageInfo convertProto2( + Class messageType, Descriptor messageDescriptor) { + List fieldDescriptors = messageDescriptor.getFields(); + StructuralMessageInfo.Builder builder = + StructuralMessageInfo.newBuilder(fieldDescriptors.size()); + builder.withDefaultInstance(getDefaultInstance(messageType)); + builder.withSyntax(ProtoSyntax.PROTO2); + builder.withMessageSetWireFormat(messageDescriptor.getOptions().getMessageSetWireFormat()); + + OneofState oneofState = new OneofState(); + int bitFieldIndex = 0; + int presenceMask = 1; + Field bitField = null; + + // Fields in the descriptor are ordered by the index position in which they appear in the + // proto file. This is the same order used to determine the presence mask used in the + // bitFields. So to determine the appropriate presence mask to be used for a field, we simply + // need to shift the presence mask whenever a presence-checked field is encountered. + for (int i = 0; i < fieldDescriptors.size(); ++i) { + final FieldDescriptor fd = fieldDescriptors.get(i); + boolean enforceUtf8 = fd.getFile().getOptions().getJavaStringCheckUtf8(); + Internal.EnumVerifier enumVerifier = null; + if (fd.getJavaType() == Descriptors.FieldDescriptor.JavaType.ENUM) { + enumVerifier = + new Internal.EnumVerifier() { + @Override + public boolean isInRange(int number) { + return fd.getEnumType().findValueByNumber(number) != null; + } + }; + } + if (fd.getContainingOneof() != null) { + // Build a oneof member field. + builder.withField(buildOneofMember(messageType, fd, oneofState, enforceUtf8, enumVerifier)); + } else { + Field field = field(messageType, fd); + int number = fd.getNumber(); + FieldType type = getFieldType(fd); + + if (fd.isMapField()) { + // Map field points to an auto-generated message entry type with the definition: + // message MapEntry { + // K key = 1; + // V value = 2; + // } + final FieldDescriptor valueField = fd.getMessageType().findFieldByNumber(2); + if (valueField.getJavaType() == Descriptors.FieldDescriptor.JavaType.ENUM) { + enumVerifier = + new Internal.EnumVerifier() { + @Override + public boolean isInRange(int number) { + return valueField.getEnumType().findValueByNumber(number) != null; + } + }; + } + builder.withField( + forMapField( + field, + number, + SchemaUtil.getMapDefaultEntry(messageType, fd.getName()), + enumVerifier)); + continue; + } + + if (fd.isRepeated()) { + // Repeated fields are not presence-checked. + if (enumVerifier != null) { + if (fd.isPacked()) { + builder.withField( + forPackedFieldWithEnumVerifier( + field, number, type, enumVerifier, cachedSizeField(messageType, fd))); + } else { + builder.withField(forFieldWithEnumVerifier(field, number, type, enumVerifier)); + } + } else if (fd.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + builder.withField( + forRepeatedMessageField( + field, number, type, getTypeForRepeatedMessageField(messageType, fd))); + } else { + if (fd.isPacked()) { + builder.withField( + forPackedField(field, number, type, cachedSizeField(messageType, fd))); + } else { + builder.withField(forField(field, number, type, enforceUtf8)); + } + } + continue; + } + + if (bitField == null) { + // Lazy-create the next bitfield since we know it must exist. + bitField = bitField(messageType, bitFieldIndex); + } + + // It's a presence-checked field. + if (fd.isRequired()) { + builder.withField( + forProto2RequiredField( + field, number, type, bitField, presenceMask, enforceUtf8, enumVerifier)); + } else { + builder.withField( + forProto2OptionalField( + field, number, type, bitField, presenceMask, enforceUtf8, enumVerifier)); + } + } + + // Update the presence mask for the next iteration. If the shift clears out the mask, we will + // go to the next bitField. + presenceMask <<= 1; + if (presenceMask == 0) { + bitField = null; + presenceMask = 1; + bitFieldIndex++; + } + } + + List fieldsToCheckIsInitialized = new ArrayList(); + for (int i = 0; i < fieldDescriptors.size(); ++i) { + FieldDescriptor fd = fieldDescriptors.get(i); + if (fd.isRequired() + || (fd.getJavaType() == FieldDescriptor.JavaType.MESSAGE + && needsIsInitializedCheck(fd.getMessageType()))) { + fieldsToCheckIsInitialized.add(fd.getNumber()); + } + } + int[] numbers = new int[fieldsToCheckIsInitialized.size()]; + for (int i = 0; i < fieldsToCheckIsInitialized.size(); i++) { + numbers[i] = fieldsToCheckIsInitialized.get(i); + } + builder.withCheckInitialized(numbers); + + return builder.build(); + } + + private static StructuralMessageInfo convertProto3( + Class messageType, Descriptor messageDescriptor) { + List fieldDescriptors = messageDescriptor.getFields(); + StructuralMessageInfo.Builder builder = + StructuralMessageInfo.newBuilder(fieldDescriptors.size()); + builder.withDefaultInstance(getDefaultInstance(messageType)); + builder.withSyntax(ProtoSyntax.PROTO3); + + OneofState oneofState = new OneofState(); + boolean enforceUtf8 = true; + for (int i = 0; i < fieldDescriptors.size(); ++i) { + FieldDescriptor fd = fieldDescriptors.get(i); + if (fd.getContainingOneof() != null) { + // Build a oneof member field. + builder.withField(buildOneofMember(messageType, fd, oneofState, enforceUtf8, null)); + continue; + } + if (fd.isMapField()) { + builder.withField( + forMapField( + field(messageType, fd), + fd.getNumber(), + SchemaUtil.getMapDefaultEntry(messageType, fd.getName()), + null)); + continue; + } + if (fd.isRepeated() && fd.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + builder.withField( + forRepeatedMessageField( + field(messageType, fd), + fd.getNumber(), + getFieldType(fd), + getTypeForRepeatedMessageField(messageType, fd))); + continue; + } + if (fd.isPacked()) { + builder.withField( + forPackedField( + field(messageType, fd), + fd.getNumber(), + getFieldType(fd), + cachedSizeField(messageType, fd))); + } else { + builder.withField( + forField(field(messageType, fd), fd.getNumber(), getFieldType(fd), enforceUtf8)); + } + } + + return builder.build(); + } + + /** Builds info for a oneof member field. */ + private static FieldInfo buildOneofMember( + Class messageType, + FieldDescriptor fd, + OneofState oneofState, + boolean enforceUtf8, + Internal.EnumVerifier enumVerifier) { + OneofInfo oneof = oneofState.getOneof(messageType, fd.getContainingOneof()); + FieldType type = getFieldType(fd); + Class oneofStoredType = getOneofStoredType(messageType, fd, type); + return forOneofMemberField( + fd.getNumber(), type, oneof, oneofStoredType, enforceUtf8, enumVerifier); + } + + private static Class getOneofStoredType( + Class messageType, FieldDescriptor fd, FieldType type) { + switch (type.getJavaType()) { + case BOOLEAN: + return Boolean.class; + case BYTE_STRING: + return ByteString.class; + case DOUBLE: + return Double.class; + case FLOAT: + return Float.class; + case ENUM: + case INT: + return Integer.class; + case LONG: + return Long.class; + case STRING: + return String.class; + case MESSAGE: + return getOneofStoredTypeForMessage(messageType, fd); + default: + throw new IllegalArgumentException("Invalid type for oneof: " + type); + } + } + + private static FieldType getFieldType(FieldDescriptor fd) { + switch (fd.getType()) { + case BOOL: + if (!fd.isRepeated()) { + return FieldType.BOOL; + } + return fd.isPacked() ? FieldType.BOOL_LIST_PACKED : FieldType.BOOL_LIST; + case BYTES: + return fd.isRepeated() ? FieldType.BYTES_LIST : FieldType.BYTES; + case DOUBLE: + if (!fd.isRepeated()) { + return FieldType.DOUBLE; + } + return fd.isPacked() ? FieldType.DOUBLE_LIST_PACKED : FieldType.DOUBLE_LIST; + case ENUM: + if (!fd.isRepeated()) { + return FieldType.ENUM; + } + return fd.isPacked() ? FieldType.ENUM_LIST_PACKED : FieldType.ENUM_LIST; + case FIXED32: + if (!fd.isRepeated()) { + return FieldType.FIXED32; + } + return fd.isPacked() ? FieldType.FIXED32_LIST_PACKED : FieldType.FIXED32_LIST; + case FIXED64: + if (!fd.isRepeated()) { + return FieldType.FIXED64; + } + return fd.isPacked() ? FieldType.FIXED64_LIST_PACKED : FieldType.FIXED64_LIST; + case FLOAT: + if (!fd.isRepeated()) { + return FieldType.FLOAT; + } + return fd.isPacked() ? FieldType.FLOAT_LIST_PACKED : FieldType.FLOAT_LIST; + case GROUP: + return fd.isRepeated() ? FieldType.GROUP_LIST : FieldType.GROUP; + case INT32: + if (!fd.isRepeated()) { + return FieldType.INT32; + } + return fd.isPacked() ? FieldType.INT32_LIST_PACKED : FieldType.INT32_LIST; + case INT64: + if (!fd.isRepeated()) { + return FieldType.INT64; + } + return fd.isPacked() ? FieldType.INT64_LIST_PACKED : FieldType.INT64_LIST; + case MESSAGE: + if (fd.isMapField()) { + return FieldType.MAP; + } + return fd.isRepeated() ? FieldType.MESSAGE_LIST : FieldType.MESSAGE; + case SFIXED32: + if (!fd.isRepeated()) { + return FieldType.SFIXED32; + } + return fd.isPacked() ? FieldType.SFIXED32_LIST_PACKED : FieldType.SFIXED32_LIST; + case SFIXED64: + if (!fd.isRepeated()) { + return FieldType.SFIXED64; + } + return fd.isPacked() ? FieldType.SFIXED64_LIST_PACKED : FieldType.SFIXED64_LIST; + case SINT32: + if (!fd.isRepeated()) { + return FieldType.SINT32; + } + return fd.isPacked() ? FieldType.SINT32_LIST_PACKED : FieldType.SINT32_LIST; + case SINT64: + if (!fd.isRepeated()) { + return FieldType.SINT64; + } + return fd.isPacked() ? FieldType.SINT64_LIST_PACKED : FieldType.SINT64_LIST; + case STRING: + return fd.isRepeated() ? FieldType.STRING_LIST : FieldType.STRING; + case UINT32: + if (!fd.isRepeated()) { + return FieldType.UINT32; + } + return fd.isPacked() ? FieldType.UINT32_LIST_PACKED : FieldType.UINT32_LIST; + case UINT64: + if (!fd.isRepeated()) { + return FieldType.UINT64; + } + return fd.isPacked() ? FieldType.UINT64_LIST_PACKED : FieldType.UINT64_LIST; + default: + throw new IllegalArgumentException("Unsupported field type: " + fd.getType()); + } + } + + private static Field bitField(Class messageType, int index) { + return field(messageType, "bitField" + index + "_"); + } + + private static Field field(Class messageType, FieldDescriptor fd) { + return field(messageType, getFieldName(fd)); + } + + private static Field cachedSizeField(Class messageType, FieldDescriptor fd) { + return field(messageType, getCachedSizeFieldName(fd)); + } + + private static Field field(Class messageType, String fieldName) { + try { + return messageType.getDeclaredField(fieldName); + } catch (Exception e) { + throw new IllegalArgumentException( + "Unable to find field " + fieldName + " in message class " + messageType.getName()); + } + } + + static String getFieldName(FieldDescriptor fd) { + String name = (fd.getType() == FieldDescriptor.Type.GROUP) + ? fd.getMessageType().getName() + : fd.getName(); + + // convert to UpperCamelCase for comparison to the specialFieldNames + // (which are in UpperCamelCase) + String upperCamelCaseName = snakeCaseToUpperCamelCase(name); + + // Append underscores to match the behavior of the protoc java compiler + final String suffix; + if (specialFieldNames.contains(upperCamelCaseName)) { + // For proto field names that match the specialFieldNames, + // the protoc java compiler appends "__" to the java field name + // to prevent the field's accessor method names from clashing with other methods. + // For example: + // proto field name = "class" + // java field name = "class__" + // accessor method name = "getClass_()" (so that it does not clash with Object.getClass()) + suffix = "__"; + } else { + // For other proto field names, + // the protoc java compiler appends "_" to the java field name + // to prevent field names from clashing with java keywords. + // For example: + // proto field name = "int" + // java field name = "int_" (so that it does not clash with int keyword) + // accessor method name = "getInt()" + suffix = "_"; + } + return snakeCaseToLowerCamelCase(name) + suffix; + } + + private static String getCachedSizeFieldName(FieldDescriptor fd) { + return snakeCaseToLowerCamelCase(fd.getName()) + "MemoizedSerializedSize"; + } + + /** + * Converts a snake case string into lower camel case. + * + *

Some examples:

+ *
+   *     snakeCaseToLowerCamelCase("foo_bar") => "fooBar"
+   *     snakeCaseToLowerCamelCase("foo") => "foo"
+   * 
+ * + * @param snakeCase the string in snake case to convert + * @return the string converted to camel case, with a lowercase first character + */ + private static String snakeCaseToLowerCamelCase(String snakeCase) { + return snakeCaseToCamelCase(snakeCase, false); + } + + /** + * Converts a snake case string into upper camel case. + * + *

Some examples:

+ *
+   *     snakeCaseToUpperCamelCase("foo_bar") => "FooBar"
+   *     snakeCaseToUpperCamelCase("foo") => "Foo"
+   * 
+ * + * @param snakeCase the string in snake case to convert + * @return the string converted to camel case, with an uppercase first character + */ + private static String snakeCaseToUpperCamelCase(String snakeCase) { + return snakeCaseToCamelCase(snakeCase, true); + } + + /** + * Converts a snake case string into camel case. + * + *

For better readability, prefer calling either + * {@link #snakeCaseToLowerCamelCase(String)} or {@link #snakeCaseToUpperCamelCase(String)}.

+ * + *

Some examples:

+ *
+   *     snakeCaseToCamelCase("foo_bar", false) => "fooBar"
+   *     snakeCaseToCamelCase("foo_bar", true) => "FooBar"
+   *     snakeCaseToCamelCase("foo", false) => "foo"
+   *     snakeCaseToCamelCase("foo", true) => "Foo"
+   *     snakeCaseToCamelCase("Foo", false) => "foo"
+   *     snakeCaseToCamelCase("fooBar", false) => "fooBar"
+   * 
+ * + *

This implementation of this method must exactly match the corresponding + * function in the protocol compiler. Specifically, the + * {@code UnderscoresToCamelCase} function in + * {@code src/google/protobuf/compiler/java/java_helpers.cc}.

+ * + * @param snakeCase the string in snake case to convert + * @param capFirst true if the first letter of the returned string should be uppercase. + * false if the first letter of the returned string should be lowercase. + * @return the string converted to camel case, with an uppercase or lowercase first + * character depending on if {@code capFirst} is true or false, respectively + */ + private static String snakeCaseToCamelCase(String snakeCase, boolean capFirst) { + StringBuilder sb = new StringBuilder(snakeCase.length() + 1); + boolean capNext = capFirst; + for (int ctr = 0; ctr < snakeCase.length(); ctr++) { + char next = snakeCase.charAt(ctr); + if (next == '_') { + capNext = true; + } else if (Character.isDigit(next)) { + sb.append(next); + capNext = true; + } else if (capNext) { + sb.append(Character.toUpperCase(next)); + capNext = false; + } else if (ctr == 0) { + sb.append(Character.toLowerCase(next)); + } else { + sb.append(next); + } + } + return sb.toString(); + } + + /** + * Inspects the message to identify the stored type for a message field that is part of a oneof. + */ + private static Class getOneofStoredTypeForMessage(Class messageType, FieldDescriptor fd) { + try { + String name = fd.getType() == Type.GROUP ? fd.getMessageType().getName() : fd.getName(); + Method getter = messageType.getDeclaredMethod(getterForField(name)); + return getter.getReturnType(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** Inspects the message to identify the message type of a repeated message field. */ + private static Class getTypeForRepeatedMessageField(Class messageType, FieldDescriptor fd) { + try { + String name = fd.getType() == Type.GROUP ? fd.getMessageType().getName() : fd.getName(); + Method getter = messageType.getDeclaredMethod(getterForField(name), int.class); + return getter.getReturnType(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** Constructs the name of the get method for the given field in the proto. */ + private static String getterForField(String snakeCase) { + String camelCase = snakeCaseToLowerCamelCase(snakeCase); + StringBuilder builder = new StringBuilder("get"); + // Capitalize the first character in the field name. + builder.append(Character.toUpperCase(camelCase.charAt(0))); + builder.append(camelCase.substring(1, camelCase.length())); + return builder.toString(); + } + + private static final class OneofState { + private OneofInfo[] oneofs = new OneofInfo[2]; + + OneofInfo getOneof(Class messageType, OneofDescriptor desc) { + int index = desc.getIndex(); + if (index >= oneofs.length) { + // Grow the array. + oneofs = Arrays.copyOf(oneofs, index * 2); + } + OneofInfo info = oneofs[index]; + if (info == null) { + info = newInfo(messageType, desc); + oneofs[index] = info; + } + return info; + } + + private static OneofInfo newInfo(Class messageType, OneofDescriptor desc) { + String camelCase = snakeCaseToLowerCamelCase(desc.getName()); + String valueFieldName = camelCase + "_"; + String caseFieldName = camelCase + "Case_"; + + return new OneofInfo( + desc.getIndex(), field(messageType, caseFieldName), field(messageType, valueFieldName)); + } + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java new file mode 100644 index 0000000..c2378ad --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java @@ -0,0 +1,70 @@ +// 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. + +package com.google.protobuf; + +/** Parsers to discard unknown fields during parsing. */ +public final class DiscardUnknownFieldsParser { + + /** + * Wraps a given {@link Parser} into a new {@link Parser} that discards unknown fields during + * parsing. + * + *

Usage example: + * + *

{@code
+   * private final static Parser FOO_PARSER = DiscardUnknownFieldsParser.wrap(Foo.parser());
+   * Foo parseFooDiscardUnknown(ByteBuffer input) throws IOException {
+   *   return FOO_PARSER.parseFrom(input);
+   * }
+   * }
+ * + *

Like all other implementations of {@code Parser}, this parser is stateless and thread-safe. + * + * @param parser The delegated parser that parses messages. + * @return a {@link Parser} that will discard unknown fields during parsing. + */ + public static final Parser wrap(final Parser parser) { + return new AbstractParser() { + @Override + public T parsePartialFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException { + try { + input.discardUnknownFields(); + return parser.parsePartialFrom(input, extensionRegistry); + } finally { + input.unsetDiscardUnknownFields(); + } + } + }; + } + + private DiscardUnknownFieldsParser() {} +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/ExtensionLite.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/ExtensionLite.java new file mode 100644 index 0000000..0fb5f49 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/ExtensionLite.java @@ -0,0 +1,60 @@ +// 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. + +package com.google.protobuf; + +/** + * Lite interface that generated extensions implement. + * + *

Methods are for use by generated code only. You can hold a reference to extensions using this + * type name. + */ +public abstract class ExtensionLite { + + /** Returns the field number of the extension. */ + public abstract int getNumber(); + + /** Returns the type of the field. */ + public abstract WireFormat.FieldType getLiteType(); + + /** Returns whether it is a repeated field. */ + public abstract boolean isRepeated(); + + /** Returns the default value of the extension field. */ + public abstract Type getDefaultValue(); + + /** Returns the default instance of the extension field, if it's a message extension. */ + public abstract MessageLite getMessageDefaultInstance(); + + /** Returns whether or not this extension is a Lite Extension. */ + boolean isLite() { + return true; + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/FieldSet.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/FieldSet.java new file mode 100644 index 0000000..8d11360 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/FieldSet.java @@ -0,0 +1,1303 @@ +// 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. + +package com.google.protobuf; + +import static com.google.protobuf.Internal.checkNotNull; + +import com.google.protobuf.LazyField.LazyIterator; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +/** + * A class which represents an arbitrary set of fields of some message type. This is used to + * implement {@link DynamicMessage}, and also to represent extensions in {@link GeneratedMessage}. + * This class is package-private, since outside users should probably be using {@link + * DynamicMessage}. + * + * @author kenton@google.com Kenton Varda + */ +final class FieldSet> { + /** + * Interface for a FieldDescriptor or lite extension descriptor. This prevents FieldSet from + * depending on {@link Descriptors.FieldDescriptor}. + */ + public interface FieldDescriptorLite> extends Comparable { + int getNumber(); + + WireFormat.FieldType getLiteType(); + + WireFormat.JavaType getLiteJavaType(); + + boolean isRepeated(); + + boolean isPacked(); + + Internal.EnumLiteMap getEnumType(); + + // If getLiteJavaType() == MESSAGE, this merges a message object of the + // type into a builder of the type. Returns {@code to}. + MessageLite.Builder internalMergeFrom(MessageLite.Builder to, MessageLite from); + } + + private static final int DEFAULT_FIELD_MAP_ARRAY_SIZE = 16; + + private final SmallSortedMap fields; + private boolean isImmutable; + private boolean hasLazyField; + + /** Construct a new FieldSet. */ + private FieldSet() { + this.fields = SmallSortedMap.newFieldMap(DEFAULT_FIELD_MAP_ARRAY_SIZE); + } + + /** Construct an empty FieldSet. This is only used to initialize DEFAULT_INSTANCE. */ + @SuppressWarnings("unused") + private FieldSet(final boolean dummy) { + this(SmallSortedMap.newFieldMap(0)); + makeImmutable(); + } + + private FieldSet(SmallSortedMap fields) { + this.fields = fields; + makeImmutable(); + } + + /** Construct a new FieldSet. */ + public static > FieldSet newFieldSet() { + return new FieldSet(); + } + + /** Get an immutable empty FieldSet. */ + @SuppressWarnings("unchecked") + public static > FieldSet emptySet() { + return DEFAULT_INSTANCE; + } + + /** Construct a new Builder. */ + public static > Builder newBuilder() { + return new Builder(); + } + + @SuppressWarnings("rawtypes") + private static final FieldSet DEFAULT_INSTANCE = new FieldSet(true); + + /** Returns {@code true} if empty, {@code false} otherwise. */ + boolean isEmpty() { + return fields.isEmpty(); + } + + /** Make this FieldSet immutable from this point forward. */ + public void makeImmutable() { + if (isImmutable) { + return; + } + fields.makeImmutable(); + isImmutable = true; + } + + /** + * Returns whether the FieldSet is immutable. This is true if it is the {@link #emptySet} or if + * {@link #makeImmutable} were called. + * + * @return whether the FieldSet is immutable. + */ + public boolean isImmutable() { + return isImmutable; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + + if (!(o instanceof FieldSet)) { + return false; + } + + FieldSet other = (FieldSet) o; + return fields.equals(other.fields); + } + + @Override + public int hashCode() { + return fields.hashCode(); + } + + /** + * Clones the FieldSet. The returned FieldSet will be mutable even if the original FieldSet was + * immutable. + * + * @return the newly cloned FieldSet + */ + @Override + public FieldSet clone() { + // We can't just call fields.clone because List objects in the map + // should not be shared. + FieldSet clone = FieldSet.newFieldSet(); + for (int i = 0; i < fields.getNumArrayEntries(); i++) { + Map.Entry entry = fields.getArrayEntryAt(i); + clone.setField(entry.getKey(), entry.getValue()); + } + for (Map.Entry entry : fields.getOverflowEntries()) { + clone.setField(entry.getKey(), entry.getValue()); + } + clone.hasLazyField = hasLazyField; + return clone; + } + + + // ================================================================= + + /** See {@link Message.Builder#clear()}. */ + public void clear() { + fields.clear(); + hasLazyField = false; + } + + /** Get a simple map containing all the fields. */ + public Map getAllFields() { + if (hasLazyField) { + SmallSortedMap result = cloneAllFieldsMap(fields, /* copyList */ false); + if (fields.isImmutable()) { + result.makeImmutable(); + } + return result; + } + return fields.isImmutable() ? fields : Collections.unmodifiableMap(fields); + } + + private static > SmallSortedMap cloneAllFieldsMap( + SmallSortedMap fields, boolean copyList) { + SmallSortedMap result = SmallSortedMap.newFieldMap(DEFAULT_FIELD_MAP_ARRAY_SIZE); + for (int i = 0; i < fields.getNumArrayEntries(); i++) { + cloneFieldEntry(result, fields.getArrayEntryAt(i), copyList); + } + for (Map.Entry entry : fields.getOverflowEntries()) { + cloneFieldEntry(result, entry, copyList); + } + return result; + } + + private static > void cloneFieldEntry( + Map map, Map.Entry entry, boolean copyList) { + T key = entry.getKey(); + Object value = entry.getValue(); + if (value instanceof LazyField) { + map.put(key, ((LazyField) value).getValue()); + } else if (copyList && value instanceof List) { + map.put(key, new ArrayList<>((List) value)); + } else { + map.put(key, value); + } + } + + /** + * Get an iterator to the field map. This iterator should not be leaked out of the protobuf + * library as it is not protected from mutation when fields is not immutable. + */ + public Iterator> iterator() { + if (hasLazyField) { + return new LazyIterator(fields.entrySet().iterator()); + } + return fields.entrySet().iterator(); + } + + /** + * Get an iterator over the fields in the map in descending (i.e. reverse) order. This iterator + * should not be leaked out of the protobuf library as it is not protected from mutation when + * fields is not immutable. + */ + Iterator> descendingIterator() { + if (hasLazyField) { + return new LazyIterator(fields.descendingEntrySet().iterator()); + } + return fields.descendingEntrySet().iterator(); + } + + /** Useful for implementing {@link Message#hasField(Descriptors.FieldDescriptor)}. */ + public boolean hasField(final T descriptor) { + if (descriptor.isRepeated()) { + throw new IllegalArgumentException("hasField() can only be called on non-repeated fields."); + } + + return fields.get(descriptor) != null; + } + + /** + * Useful for implementing {@link Message#getField(Descriptors.FieldDescriptor)}. This method + * returns {@code null} if the field is not set; in this case it is up to the caller to fetch the + * field's default value. + */ + public Object getField(final T descriptor) { + Object o = fields.get(descriptor); + if (o instanceof LazyField) { + return ((LazyField) o).getValue(); + } + return o; + } + + /** + * Useful for implementing {@link Message.Builder#setField(Descriptors.FieldDescriptor,Object)}. + */ + @SuppressWarnings({"unchecked", "rawtypes"}) + public void setField(final T descriptor, Object value) { + if (descriptor.isRepeated()) { + if (!(value instanceof List)) { + throw new IllegalArgumentException( + "Wrong object type used with protocol message reflection."); + } + + // Wrap the contents in a new list so that the caller cannot change + // the list's contents after setting it. + final List newList = new ArrayList<>(); + newList.addAll((List) value); + for (final Object element : newList) { + verifyType(descriptor, element); + } + value = newList; + } else { + verifyType(descriptor, value); + } + + if (value instanceof LazyField) { + hasLazyField = true; + } + fields.put(descriptor, value); + } + + /** Useful for implementing {@link Message.Builder#clearField(Descriptors.FieldDescriptor)}. */ + public void clearField(final T descriptor) { + fields.remove(descriptor); + if (fields.isEmpty()) { + hasLazyField = false; + } + } + + /** Useful for implementing {@link Message#getRepeatedFieldCount(Descriptors.FieldDescriptor)}. */ + public int getRepeatedFieldCount(final T descriptor) { + if (!descriptor.isRepeated()) { + throw new IllegalArgumentException( + "getRepeatedField() can only be called on repeated fields."); + } + + final Object value = getField(descriptor); + if (value == null) { + return 0; + } else { + return ((List) value).size(); + } + } + + /** Useful for implementing {@link Message#getRepeatedField(Descriptors.FieldDescriptor,int)}. */ + public Object getRepeatedField(final T descriptor, final int index) { + if (!descriptor.isRepeated()) { + throw new IllegalArgumentException( + "getRepeatedField() can only be called on repeated fields."); + } + + final Object value = getField(descriptor); + + if (value == null) { + throw new IndexOutOfBoundsException(); + } else { + return ((List) value).get(index); + } + } + + /** + * Useful for implementing {@link + * Message.Builder#setRepeatedField(Descriptors.FieldDescriptor,int,Object)}. + */ + @SuppressWarnings("unchecked") + public void setRepeatedField(final T descriptor, final int index, final Object value) { + if (!descriptor.isRepeated()) { + throw new IllegalArgumentException( + "getRepeatedField() can only be called on repeated fields."); + } + + final Object list = getField(descriptor); + if (list == null) { + throw new IndexOutOfBoundsException(); + } + + verifyType(descriptor, value); + ((List) list).set(index, value); + } + + /** + * Useful for implementing {@link + * Message.Builder#addRepeatedField(Descriptors.FieldDescriptor,Object)}. + */ + @SuppressWarnings("unchecked") + public void addRepeatedField(final T descriptor, final Object value) { + if (!descriptor.isRepeated()) { + throw new IllegalArgumentException( + "addRepeatedField() can only be called on repeated fields."); + } + + verifyType(descriptor, value); + + final Object existingValue = getField(descriptor); + List list; + if (existingValue == null) { + list = new ArrayList(); + fields.put(descriptor, list); + } else { + list = (List) existingValue; + } + + list.add(value); + } + + /** + * Verifies that the given object is of the correct type to be a valid value for the given field. + * (For repeated fields, this checks if the object is the right type to be one element of the + * field.) + * + * @throws IllegalArgumentException The value is not of the right type. + */ + private void verifyType(final T descriptor, final Object value) { + if (!isValidType(descriptor.getLiteType(), value)) { + // TODO(kenton): When chaining calls to setField(), it can be hard to + // tell from the stack trace which exact call failed, since the whole + // chain is considered one line of code. It would be nice to print + // more information here, e.g. naming the field. We used to do that. + // But we can't now that FieldSet doesn't use descriptors. Maybe this + // isn't a big deal, though, since it would only really apply when using + // reflection and generally people don't chain reflection setters. + throw new IllegalArgumentException( + String.format( + "Wrong object type used with protocol message reflection.\n" + + "Field number: %d, field java type: %s, value type: %s\n", + descriptor.getNumber(), + descriptor.getLiteType().getJavaType(), + value.getClass().getName())); + } + } + + + private static boolean isValidType(final WireFormat.FieldType type, final Object value) { + checkNotNull(value); + switch (type.getJavaType()) { + case INT: + return value instanceof Integer; + case LONG: + return value instanceof Long; + case FLOAT: + return value instanceof Float; + case DOUBLE: + return value instanceof Double; + case BOOLEAN: + return value instanceof Boolean; + case STRING: + return value instanceof String; + case BYTE_STRING: + return value instanceof ByteString || value instanceof byte[]; + case ENUM: + // TODO(kenton): Caller must do type checking here, I guess. + return (value instanceof Integer || value instanceof Internal.EnumLite); + case MESSAGE: + // TODO(kenton): Caller must do type checking here, I guess. + return (value instanceof MessageLite) || (value instanceof LazyField); + } + return false; + } + + // ================================================================= + // Parsing and serialization + + /** + * See {@link Message#isInitialized()}. Note: Since {@code FieldSet} itself does not have any way + * of knowing about required fields that aren't actually present in the set, it is up to the + * caller to check that all required fields are present. + */ + public boolean isInitialized() { + for (int i = 0; i < fields.getNumArrayEntries(); i++) { + if (!isInitialized(fields.getArrayEntryAt(i))) { + return false; + } + } + for (final Map.Entry entry : fields.getOverflowEntries()) { + if (!isInitialized(entry)) { + return false; + } + } + return true; + } + + @SuppressWarnings("unchecked") + private static > boolean isInitialized( + final Map.Entry entry) { + final T descriptor = entry.getKey(); + if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE) { + if (descriptor.isRepeated()) { + for (final MessageLite element : (List) entry.getValue()) { + if (!element.isInitialized()) { + return false; + } + } + } else { + Object value = entry.getValue(); + if (value instanceof MessageLite) { + if (!((MessageLite) value).isInitialized()) { + return false; + } + } else if (value instanceof LazyField) { + return true; + } else { + throw new IllegalArgumentException( + "Wrong object type used with protocol message reflection."); + } + } + } + return true; + } + + /** + * Given a field type, return the wire type. + * + * @return One of the {@code WIRETYPE_} constants defined in {@link WireFormat}. + */ + static int getWireFormatForFieldType(final WireFormat.FieldType type, boolean isPacked) { + if (isPacked) { + return WireFormat.WIRETYPE_LENGTH_DELIMITED; + } else { + return type.getWireType(); + } + } + + /** Like {@link Message.Builder#mergeFrom(Message)}, but merges from another {@link FieldSet}. */ + public void mergeFrom(final FieldSet other) { + for (int i = 0; i < other.fields.getNumArrayEntries(); i++) { + mergeFromField(other.fields.getArrayEntryAt(i)); + } + for (final Map.Entry entry : other.fields.getOverflowEntries()) { + mergeFromField(entry); + } + } + + private static Object cloneIfMutable(Object value) { + if (value instanceof byte[]) { + byte[] bytes = (byte[]) value; + byte[] copy = new byte[bytes.length]; + System.arraycopy(bytes, 0, copy, 0, bytes.length); + return copy; + } else { + return value; + } + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private void mergeFromField(final Map.Entry entry) { + final T descriptor = entry.getKey(); + Object otherValue = entry.getValue(); + if (otherValue instanceof LazyField) { + otherValue = ((LazyField) otherValue).getValue(); + } + + if (descriptor.isRepeated()) { + Object value = getField(descriptor); + if (value == null) { + value = new ArrayList<>(); + } + for (Object element : (List) otherValue) { + ((List) value).add(cloneIfMutable(element)); + } + fields.put(descriptor, value); + } else if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE) { + Object value = getField(descriptor); + if (value == null) { + fields.put(descriptor, cloneIfMutable(otherValue)); + } else { + // Merge the messages. + value = + descriptor + .internalMergeFrom(((MessageLite) value).toBuilder(), (MessageLite) otherValue) + .build(); + fields.put(descriptor, value); + } + } else { + fields.put(descriptor, cloneIfMutable(otherValue)); + } + } + + // TODO(kenton): Move static parsing and serialization methods into some + // other class. Probably WireFormat. + + /** + * Read a field of any primitive type for immutable messages from a CodedInputStream. Enums, + * groups, and embedded messages are not handled by this method. + * + * @param input The stream from which to read. + * @param type Declared type of the field. + * @param checkUtf8 When true, check that the input is valid utf8. + * @return An object representing the field's value, of the exact type which would be returned by + * {@link Message#getField(Descriptors.FieldDescriptor)} for this field. + */ + public static Object readPrimitiveField( + CodedInputStream input, final WireFormat.FieldType type, boolean checkUtf8) + throws IOException { + if (checkUtf8) { + return WireFormat.readPrimitiveField(input, type, WireFormat.Utf8Validation.STRICT); + } else { + return WireFormat.readPrimitiveField(input, type, WireFormat.Utf8Validation.LOOSE); + } + } + + + /** See {@link Message#writeTo(CodedOutputStream)}. */ + public void writeTo(final CodedOutputStream output) throws IOException { + for (int i = 0; i < fields.getNumArrayEntries(); i++) { + final Map.Entry entry = fields.getArrayEntryAt(i); + writeField(entry.getKey(), entry.getValue(), output); + } + for (final Map.Entry entry : fields.getOverflowEntries()) { + writeField(entry.getKey(), entry.getValue(), output); + } + } + + /** Like {@link #writeTo} but uses MessageSet wire format. */ + public void writeMessageSetTo(final CodedOutputStream output) throws IOException { + for (int i = 0; i < fields.getNumArrayEntries(); i++) { + writeMessageSetTo(fields.getArrayEntryAt(i), output); + } + for (final Map.Entry entry : fields.getOverflowEntries()) { + writeMessageSetTo(entry, output); + } + } + + private void writeMessageSetTo(final Map.Entry entry, final CodedOutputStream output) + throws IOException { + final T descriptor = entry.getKey(); + if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE + && !descriptor.isRepeated() + && !descriptor.isPacked()) { + Object value = entry.getValue(); + if (value instanceof LazyField) { + value = ((LazyField) value).getValue(); + } + output.writeMessageSetExtension(entry.getKey().getNumber(), (MessageLite) value); + } else { + writeField(descriptor, entry.getValue(), output); + } + } + + /** + * Write a single tag-value pair to the stream. + * + * @param output The output stream. + * @param type The field's type. + * @param number The field's number. + * @param value Object representing the field's value. Must be of the exact type which would be + * returned by {@link Message#getField(Descriptors.FieldDescriptor)} for this field. + */ + static void writeElement( + final CodedOutputStream output, + final WireFormat.FieldType type, + final int number, + final Object value) + throws IOException { + // Special case for groups, which need a start and end tag; other fields + // can just use writeTag() and writeFieldNoTag(). + if (type == WireFormat.FieldType.GROUP) { + output.writeGroup(number, (MessageLite) value); + } else { + output.writeTag(number, getWireFormatForFieldType(type, false)); + writeElementNoTag(output, type, value); + } + } + + /** + * Write a field of arbitrary type, without its tag, to the stream. + * + * @param output The output stream. + * @param type The field's type. + * @param value Object representing the field's value. Must be of the exact type which would be + * returned by {@link Message#getField(Descriptors.FieldDescriptor)} for this field. + */ + static void writeElementNoTag( + final CodedOutputStream output, final WireFormat.FieldType type, final Object value) + throws IOException { + switch (type) { + case DOUBLE: + output.writeDoubleNoTag((Double) value); + break; + case FLOAT: + output.writeFloatNoTag((Float) value); + break; + case INT64: + output.writeInt64NoTag((Long) value); + break; + case UINT64: + output.writeUInt64NoTag((Long) value); + break; + case INT32: + output.writeInt32NoTag((Integer) value); + break; + case FIXED64: + output.writeFixed64NoTag((Long) value); + break; + case FIXED32: + output.writeFixed32NoTag((Integer) value); + break; + case BOOL: + output.writeBoolNoTag((Boolean) value); + break; + case GROUP: + output.writeGroupNoTag((MessageLite) value); + break; + case MESSAGE: + output.writeMessageNoTag((MessageLite) value); + break; + case STRING: + if (value instanceof ByteString) { + output.writeBytesNoTag((ByteString) value); + } else { + output.writeStringNoTag((String) value); + } + break; + case BYTES: + if (value instanceof ByteString) { + output.writeBytesNoTag((ByteString) value); + } else { + output.writeByteArrayNoTag((byte[]) value); + } + break; + case UINT32: + output.writeUInt32NoTag((Integer) value); + break; + case SFIXED32: + output.writeSFixed32NoTag((Integer) value); + break; + case SFIXED64: + output.writeSFixed64NoTag((Long) value); + break; + case SINT32: + output.writeSInt32NoTag((Integer) value); + break; + case SINT64: + output.writeSInt64NoTag((Long) value); + break; + + case ENUM: + if (value instanceof Internal.EnumLite) { + output.writeEnumNoTag(((Internal.EnumLite) value).getNumber()); + } else { + output.writeEnumNoTag(((Integer) value).intValue()); + } + break; + } + } + + /** Write a single field. */ + public static void writeField( + final FieldDescriptorLite descriptor, final Object value, final CodedOutputStream output) + throws IOException { + WireFormat.FieldType type = descriptor.getLiteType(); + int number = descriptor.getNumber(); + if (descriptor.isRepeated()) { + final List valueList = (List) value; + if (descriptor.isPacked()) { + output.writeTag(number, WireFormat.WIRETYPE_LENGTH_DELIMITED); + // Compute the total data size so the length can be written. + int dataSize = 0; + for (final Object element : valueList) { + dataSize += computeElementSizeNoTag(type, element); + } + output.writeRawVarint32(dataSize); + // Write the data itself, without any tags. + for (final Object element : valueList) { + writeElementNoTag(output, type, element); + } + } else { + for (final Object element : valueList) { + writeElement(output, type, number, element); + } + } + } else { + if (value instanceof LazyField) { + writeElement(output, type, number, ((LazyField) value).getValue()); + } else { + writeElement(output, type, number, value); + } + } + } + + /** + * See {@link Message#getSerializedSize()}. It's up to the caller to cache the resulting size if + * desired. + */ + public int getSerializedSize() { + int size = 0; + for (int i = 0; i < fields.getNumArrayEntries(); i++) { + final Map.Entry entry = fields.getArrayEntryAt(i); + size += computeFieldSize(entry.getKey(), entry.getValue()); + } + for (final Map.Entry entry : fields.getOverflowEntries()) { + size += computeFieldSize(entry.getKey(), entry.getValue()); + } + return size; + } + + /** Like {@link #getSerializedSize} but uses MessageSet wire format. */ + public int getMessageSetSerializedSize() { + int size = 0; + for (int i = 0; i < fields.getNumArrayEntries(); i++) { + size += getMessageSetSerializedSize(fields.getArrayEntryAt(i)); + } + for (final Map.Entry entry : fields.getOverflowEntries()) { + size += getMessageSetSerializedSize(entry); + } + return size; + } + + private int getMessageSetSerializedSize(final Map.Entry entry) { + final T descriptor = entry.getKey(); + Object value = entry.getValue(); + if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE + && !descriptor.isRepeated() + && !descriptor.isPacked()) { + if (value instanceof LazyField) { + return CodedOutputStream.computeLazyFieldMessageSetExtensionSize( + entry.getKey().getNumber(), (LazyField) value); + } else { + return CodedOutputStream.computeMessageSetExtensionSize( + entry.getKey().getNumber(), (MessageLite) value); + } + } else { + return computeFieldSize(descriptor, value); + } + } + + /** + * Compute the number of bytes that would be needed to encode a single tag/value pair of arbitrary + * type. + * + * @param type The field's type. + * @param number The field's number. + * @param value Object representing the field's value. Must be of the exact type which would be + * returned by {@link Message#getField(Descriptors.FieldDescriptor)} for this field. + */ + static int computeElementSize( + final WireFormat.FieldType type, final int number, final Object value) { + int tagSize = CodedOutputStream.computeTagSize(number); + if (type == WireFormat.FieldType.GROUP) { + // Only count the end group tag for proto2 messages as for proto1 the end + // group tag will be counted as a part of getSerializedSize(). + tagSize *= 2; + } + return tagSize + computeElementSizeNoTag(type, value); + } + + /** + * Compute the number of bytes that would be needed to encode a particular value of arbitrary + * type, excluding tag. + * + * @param type The field's type. + * @param value Object representing the field's value. Must be of the exact type which would be + * returned by {@link Message#getField(Descriptors.FieldDescriptor)} for this field. + */ + static int computeElementSizeNoTag(final WireFormat.FieldType type, final Object value) { + switch (type) { + case DOUBLE: + return CodedOutputStream.computeDoubleSizeNoTag((Double) value); + case FLOAT: + return CodedOutputStream.computeFloatSizeNoTag((Float) value); + case INT64: + return CodedOutputStream.computeInt64SizeNoTag((Long) value); + case UINT64: + return CodedOutputStream.computeUInt64SizeNoTag((Long) value); + case INT32: + return CodedOutputStream.computeInt32SizeNoTag((Integer) value); + case FIXED64: + return CodedOutputStream.computeFixed64SizeNoTag((Long) value); + case FIXED32: + return CodedOutputStream.computeFixed32SizeNoTag((Integer) value); + case BOOL: + return CodedOutputStream.computeBoolSizeNoTag((Boolean) value); + case GROUP: + return CodedOutputStream.computeGroupSizeNoTag((MessageLite) value); + case BYTES: + if (value instanceof ByteString) { + return CodedOutputStream.computeBytesSizeNoTag((ByteString) value); + } else { + return CodedOutputStream.computeByteArraySizeNoTag((byte[]) value); + } + case STRING: + if (value instanceof ByteString) { + return CodedOutputStream.computeBytesSizeNoTag((ByteString) value); + } else { + return CodedOutputStream.computeStringSizeNoTag((String) value); + } + case UINT32: + return CodedOutputStream.computeUInt32SizeNoTag((Integer) value); + case SFIXED32: + return CodedOutputStream.computeSFixed32SizeNoTag((Integer) value); + case SFIXED64: + return CodedOutputStream.computeSFixed64SizeNoTag((Long) value); + case SINT32: + return CodedOutputStream.computeSInt32SizeNoTag((Integer) value); + case SINT64: + return CodedOutputStream.computeSInt64SizeNoTag((Long) value); + + case MESSAGE: + if (value instanceof LazyField) { + return CodedOutputStream.computeLazyFieldSizeNoTag((LazyField) value); + } else { + return CodedOutputStream.computeMessageSizeNoTag((MessageLite) value); + } + + case ENUM: + if (value instanceof Internal.EnumLite) { + return CodedOutputStream.computeEnumSizeNoTag(((Internal.EnumLite) value).getNumber()); + } else { + return CodedOutputStream.computeEnumSizeNoTag((Integer) value); + } + } + + throw new RuntimeException("There is no way to get here, but the compiler thinks otherwise."); + } + + /** Compute the number of bytes needed to encode a particular field. */ + public static int computeFieldSize(final FieldDescriptorLite descriptor, final Object value) { + WireFormat.FieldType type = descriptor.getLiteType(); + int number = descriptor.getNumber(); + if (descriptor.isRepeated()) { + if (descriptor.isPacked()) { + int dataSize = 0; + for (final Object element : (List) value) { + dataSize += computeElementSizeNoTag(type, element); + } + return dataSize + + CodedOutputStream.computeTagSize(number) + + CodedOutputStream.computeRawVarint32Size(dataSize); + } else { + int size = 0; + for (final Object element : (List) value) { + size += computeElementSize(type, number, element); + } + return size; + } + } else { + return computeElementSize(type, number, value); + } + } + + /** + * A FieldSet Builder that accept a {@link MessageLite.Builder} as a field value. This is useful + * for implementing methods in {@link MessageLite.Builder}. + */ + static final class Builder> { + + private SmallSortedMap fields; + private boolean hasLazyField; + private boolean isMutable; + private boolean hasNestedBuilders; + + private Builder() { + this(SmallSortedMap.newFieldMap(DEFAULT_FIELD_MAP_ARRAY_SIZE)); + } + + private Builder(SmallSortedMap fields) { + this.fields = fields; + this.isMutable = true; + } + + /** Creates the FieldSet */ + public FieldSet build() { + if (fields.isEmpty()) { + return FieldSet.emptySet(); + } + isMutable = false; + SmallSortedMap fieldsForBuild = fields; + if (hasNestedBuilders) { + // Make a copy of the fields map with all Builders replaced by Message. + fieldsForBuild = cloneAllFieldsMap(fields, /* copyList */ false); + replaceBuilders(fieldsForBuild); + } + FieldSet fieldSet = new FieldSet<>(fieldsForBuild); + fieldSet.hasLazyField = hasLazyField; + return fieldSet; + } + + private static > void replaceBuilders( + SmallSortedMap fieldMap) { + for (int i = 0; i < fieldMap.getNumArrayEntries(); i++) { + replaceBuilders(fieldMap.getArrayEntryAt(i)); + } + for (Map.Entry entry : fieldMap.getOverflowEntries()) { + replaceBuilders(entry); + } + } + + private static > void replaceBuilders( + Map.Entry entry) { + entry.setValue(replaceBuilders(entry.getKey(), entry.getValue())); + } + + private static > Object replaceBuilders( + T descriptor, Object value) { + if (value == null) { + return value; + } + if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE) { + if (descriptor.isRepeated()) { + if (!(value instanceof List)) { + throw new IllegalStateException( + "Repeated field should contains a List but actually contains type: " + + value.getClass()); + } + @SuppressWarnings("unchecked") // We just check that value is an instance of List above. + List list = (List) value; + for (int i = 0; i < list.size(); i++) { + Object oldElement = list.get(i); + Object newElement = replaceBuilder(oldElement); + if (newElement != oldElement) { + // If the list contains a Message.Builder, then make a copy of that list and then + // modify the Message.Builder into a Message and return the new list. This way, the + // existing Message.Builder will still be able to modify the inner fields of the + // original FieldSet.Builder. + if (list == value) { + list = new ArrayList<>(list); + } + list.set(i, newElement); + } + } + return list; + } else { + return replaceBuilder(value); + } + } + return value; + } + + private static Object replaceBuilder(Object value) { + return (value instanceof MessageLite.Builder) ? ((MessageLite.Builder) value).build() : value; + } + + /** Returns a new Builder using the fields from {@code fieldSet}. */ + public static > Builder fromFieldSet(FieldSet fieldSet) { + Builder builder = new Builder(cloneAllFieldsMap(fieldSet.fields, /* copyList */ true)); + builder.hasLazyField = fieldSet.hasLazyField; + return builder; + } + + // ================================================================= + + /** Get a simple map containing all the fields. */ + public Map getAllFields() { + if (hasLazyField) { + SmallSortedMap result = cloneAllFieldsMap(fields, /* copyList */ false); + if (fields.isImmutable()) { + result.makeImmutable(); + } else { + replaceBuilders(result); + } + return result; + } + return fields.isImmutable() ? fields : Collections.unmodifiableMap(fields); + } + + /** Useful for implementing {@link Message#hasField(Descriptors.FieldDescriptor)}. */ + public boolean hasField(final T descriptor) { + if (descriptor.isRepeated()) { + throw new IllegalArgumentException("hasField() can only be called on non-repeated fields."); + } + + return fields.get(descriptor) != null; + } + + /** + * Useful for implementing {@link Message#getField(Descriptors.FieldDescriptor)}. This method + * returns {@code null} if the field is not set; in this case it is up to the caller to fetch + * the field's default value. + */ + public Object getField(final T descriptor) { + Object value = getFieldAllowBuilders(descriptor); + return replaceBuilders(descriptor, value); + } + + /** Same as {@link #getField(F)}, but allow a {@link MessageLite.Builder} to be returned. */ + Object getFieldAllowBuilders(final T descriptor) { + Object o = fields.get(descriptor); + if (o instanceof LazyField) { + return ((LazyField) o).getValue(); + } + return o; + } + + private void ensureIsMutable() { + if (!isMutable) { + fields = cloneAllFieldsMap(fields, /* copyList */ true); + isMutable = true; + } + } + + /** + * Useful for implementing {@link Message.Builder#setField(Descriptors.FieldDescriptor, + * Object)}. + */ + @SuppressWarnings({"unchecked", "rawtypes"}) + public void setField(final T descriptor, Object value) { + ensureIsMutable(); + if (descriptor.isRepeated()) { + if (!(value instanceof List)) { + throw new IllegalArgumentException( + "Wrong object type used with protocol message reflection."); + } + + // Wrap the contents in a new list so that the caller cannot change + // the list's contents after setting it. + final List newList = new ArrayList((List) value); + for (final Object element : newList) { + verifyType(descriptor, element); + hasNestedBuilders = hasNestedBuilders || element instanceof MessageLite.Builder; + } + value = newList; + } else { + verifyType(descriptor, value); + } + + if (value instanceof LazyField) { + hasLazyField = true; + } + hasNestedBuilders = hasNestedBuilders || value instanceof MessageLite.Builder; + + fields.put(descriptor, value); + } + + /** Useful for implementing {@link Message.Builder#clearField(Descriptors.FieldDescriptor)}. */ + public void clearField(final T descriptor) { + ensureIsMutable(); + fields.remove(descriptor); + if (fields.isEmpty()) { + hasLazyField = false; + } + } + + /** + * Useful for implementing {@link Message#getRepeatedFieldCount(Descriptors.FieldDescriptor)}. + */ + public int getRepeatedFieldCount(final T descriptor) { + if (!descriptor.isRepeated()) { + throw new IllegalArgumentException( + "getRepeatedField() can only be called on repeated fields."); + } + + final Object value = getField(descriptor); + if (value == null) { + return 0; + } else { + return ((List) value).size(); + } + } + + /** + * Useful for implementing {@link Message#getRepeatedField(Descriptors.FieldDescriptor, int)}. + */ + public Object getRepeatedField(final T descriptor, final int index) { + if (hasNestedBuilders) { + ensureIsMutable(); + } + Object value = getRepeatedFieldAllowBuilders(descriptor, index); + return replaceBuilder(value); + } + + /** + * Same as {@link #getRepeatedField(F, int)}, but allow a {@link MessageLite.Builder} to be + * returned. + */ + Object getRepeatedFieldAllowBuilders(final T descriptor, final int index) { + if (!descriptor.isRepeated()) { + throw new IllegalArgumentException( + "getRepeatedField() can only be called on repeated fields."); + } + + final Object value = getFieldAllowBuilders(descriptor); + + if (value == null) { + throw new IndexOutOfBoundsException(); + } else { + return ((List) value).get(index); + } + } + + /** + * Useful for implementing {@link Message.Builder#setRepeatedField(Descriptors.FieldDescriptor, + * int, Object)}. + */ + @SuppressWarnings("unchecked") + public void setRepeatedField(final T descriptor, final int index, final Object value) { + ensureIsMutable(); + if (!descriptor.isRepeated()) { + throw new IllegalArgumentException( + "getRepeatedField() can only be called on repeated fields."); + } + + hasNestedBuilders = hasNestedBuilders || value instanceof MessageLite.Builder; + + final Object list = getField(descriptor); + if (list == null) { + throw new IndexOutOfBoundsException(); + } + + verifyType(descriptor, value); + ((List) list).set(index, value); + } + + /** + * Useful for implementing {@link Message.Builder#addRepeatedField(Descriptors.FieldDescriptor, + * Object)}. + */ + @SuppressWarnings("unchecked") + public void addRepeatedField(final T descriptor, final Object value) { + ensureIsMutable(); + if (!descriptor.isRepeated()) { + throw new IllegalArgumentException( + "addRepeatedField() can only be called on repeated fields."); + } + + hasNestedBuilders = hasNestedBuilders || value instanceof MessageLite.Builder; + + verifyType(descriptor, value); + + final Object existingValue = getField(descriptor); + List list; + if (existingValue == null) { + list = new ArrayList<>(); + fields.put(descriptor, list); + } else { + list = (List) existingValue; + } + + list.add(value); + } + + /** + * Verifies that the given object is of the correct type to be a valid value for the given + * field. (For repeated fields, this checks if the object is the right type to be one element of + * the field.) + * + * @throws IllegalArgumentException The value is not of the right type. + */ + private void verifyType(final T descriptor, final Object value) { + if (!FieldSet.isValidType(descriptor.getLiteType(), value)) { + // Builder can accept Message.Builder values even though FieldSet will reject. + if (descriptor.getLiteType().getJavaType() == WireFormat.JavaType.MESSAGE + && value instanceof MessageLite.Builder) { + return; + } + throw new IllegalArgumentException( + String.format( + "Wrong object type used with protocol message reflection.\n" + + "Field number: %d, field java type: %s, value type: %s\n", + descriptor.getNumber(), + descriptor.getLiteType().getJavaType(), + value.getClass().getName())); + } + } + + /** + * See {@link Message#isInitialized()}. Note: Since {@code FieldSet} itself does not have any + * way of knowing about required fields that aren't actually present in the set, it is up to the + * caller to check that all required fields are present. + */ + public boolean isInitialized() { + for (int i = 0; i < fields.getNumArrayEntries(); i++) { + if (!FieldSet.isInitialized(fields.getArrayEntryAt(i))) { + return false; + } + } + for (final Map.Entry entry : fields.getOverflowEntries()) { + if (!FieldSet.isInitialized(entry)) { + return false; + } + } + return true; + } + + /** + * Like {@link Message.Builder#mergeFrom(Message)}, but merges from another {@link FieldSet}. + */ + public void mergeFrom(final FieldSet other) { + ensureIsMutable(); + for (int i = 0; i < other.fields.getNumArrayEntries(); i++) { + mergeFromField(other.fields.getArrayEntryAt(i)); + } + for (final Map.Entry entry : other.fields.getOverflowEntries()) { + mergeFromField(entry); + } + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private void mergeFromField(final Map.Entry entry) { + final T descriptor = entry.getKey(); + Object otherValue = entry.getValue(); + if (otherValue instanceof LazyField) { + otherValue = ((LazyField) otherValue).getValue(); + } + + if (descriptor.isRepeated()) { + Object value = getField(descriptor); + if (value == null) { + value = new ArrayList<>(); + } + for (Object element : (List) otherValue) { + ((List) value).add(FieldSet.cloneIfMutable(element)); + } + fields.put(descriptor, value); + } else if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE) { + Object value = getField(descriptor); + if (value == null) { + fields.put(descriptor, FieldSet.cloneIfMutable(otherValue)); + } else { + // Merge the messages. + if (value instanceof MessageLite.Builder) { + descriptor.internalMergeFrom((MessageLite.Builder) value, (MessageLite) otherValue); + } else { + value = + descriptor + .internalMergeFrom(((MessageLite) value).toBuilder(), (MessageLite) otherValue) + .build(); + fields.put(descriptor, value); + } + } + } else { + fields.put(descriptor, cloneIfMutable(otherValue)); + } + } + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/LongArrayList.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/LongArrayList.java new file mode 100644 index 0000000..bda43a4 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/LongArrayList.java @@ -0,0 +1,297 @@ +// 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. + +package com.google.protobuf; + +import static com.google.protobuf.Internal.checkNotNull; + +import com.google.protobuf.Internal.LongList; +import java.util.Arrays; +import java.util.Collection; +import java.util.RandomAccess; + +/** + * An implementation of {@link LongList} on top of a primitive array. + * + * @author dweis@google.com (Daniel Weis) + */ +final class LongArrayList extends AbstractProtobufList + implements LongList, RandomAccess, PrimitiveNonBoxingCollection { + + private static final LongArrayList EMPTY_LIST = new LongArrayList(new long[0], 0); + static { + EMPTY_LIST.makeImmutable(); + } + + public static LongArrayList emptyList() { + return EMPTY_LIST; + } + + /** The backing store for the list. */ + private long[] array; + + /** + * The size of the list distinct from the length of the array. That is, it is the number of + * elements set in the list. + */ + private int size; + + /** Constructs a new mutable {@code LongArrayList} with default capacity. */ + LongArrayList() { + this(new long[DEFAULT_CAPACITY], 0); + } + + /** + * Constructs a new mutable {@code LongArrayList} containing the same elements as {@code other}. + */ + private LongArrayList(long[] other, int size) { + array = other; + 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) { + return true; + } + if (!(o instanceof LongArrayList)) { + return super.equals(o); + } + LongArrayList other = (LongArrayList) o; + if (size != other.size) { + return false; + } + + final long[] arr = other.array; + for (int i = 0; i < size; i++) { + if (array[i] != arr[i]) { + return false; + } + } + + return true; + } + + @Override + public int hashCode() { + int result = 1; + for (int i = 0; i < size; i++) { + result = (31 * result) + Internal.hashLong(array[i]); + } + return result; + } + + @Override + public LongList mutableCopyWithCapacity(int capacity) { + if (capacity < size) { + throw new IllegalArgumentException(); + } + return new LongArrayList(Arrays.copyOf(array, capacity), size); + } + + @Override + public Long get(int index) { + return getLong(index); + } + + @Override + public long getLong(int index) { + ensureIndexInRange(index); + return array[index]; + } + + @Override + public int indexOf(Object element) { + if (!(element instanceof Long)) { + return -1; + } + long unboxedElement = (Long) element; + int numElems = size(); + for (int i = 0; i < numElems; i++) { + if (array[i] == unboxedElement) { + return i; + } + } + return -1; + } + + @Override + public boolean contains(Object element) { + return indexOf(element) != -1; + } + + @Override + public int size() { + return size; + } + + @Override + public Long set(int index, Long element) { + return setLong(index, element); + } + + @Override + public long setLong(int index, long element) { + ensureIsMutable(); + ensureIndexInRange(index); + long previousValue = array[index]; + array[index] = element; + return previousValue; + } + + @Override + public boolean add(Long element) { + addLong(element); + return true; + } + + @Override + public void add(int index, Long element) { + addLong(index, element); + } + + /** Like {@link #add(Long)} but more efficient in that it doesn't box the element. */ + @Override + public void addLong(long element) { + ensureIsMutable(); + if (size == array.length) { + // Resize to 1.5x the size + int length = ((size * 3) / 2) + 1; + long[] newArray = new long[length]; + + System.arraycopy(array, 0, newArray, 0, size); + array = newArray; + } + + array[size++] = element; + } + + /** Like {@link #add(int, Long)} but more efficient in that it doesn't box the element. */ + private void addLong(int index, long element) { + ensureIsMutable(); + if (index < 0 || index > size) { + throw new IndexOutOfBoundsException(makeOutOfBoundsExceptionMessage(index)); + } + + if (size < array.length) { + // Shift everything over to make room + System.arraycopy(array, index, array, index + 1, size - index); + } else { + // Resize to 1.5x the size + int length = ((size * 3) / 2) + 1; + long[] newArray = new long[length]; + + // Copy the first part directly + System.arraycopy(array, 0, newArray, 0, index); + + // Copy the rest shifted over by one to make room + System.arraycopy(array, index, newArray, index + 1, size - index); + array = newArray; + } + + array[index] = element; + size++; + modCount++; + } + + @Override + public boolean addAll(Collection collection) { + ensureIsMutable(); + + checkNotNull(collection); + + // We specialize when adding another LongArrayList to avoid boxing elements. + if (!(collection instanceof LongArrayList)) { + return super.addAll(collection); + } + + LongArrayList list = (LongArrayList) collection; + if (list.size == 0) { + return false; + } + + int overflow = Integer.MAX_VALUE - size; + if (overflow < list.size) { + // We can't actually represent a list this large. + throw new OutOfMemoryError(); + } + + int newSize = size + list.size; + if (newSize > array.length) { + array = Arrays.copyOf(array, newSize); + } + + System.arraycopy(list.array, 0, array, size, list.size); + size = newSize; + modCount++; + return true; + } + + @Override + public Long remove(int index) { + ensureIsMutable(); + ensureIndexInRange(index); + long value = array[index]; + if (index < size - 1) { + System.arraycopy(array, index + 1, array, index, size - index - 1); + } + size--; + modCount++; + return value; + } + + /** + * Ensures that the provided {@code index} is within the range of {@code [0, size]}. Throws an + * {@link IndexOutOfBoundsException} if it is not. + * + * @param index the index to verify is in range + */ + private void ensureIndexInRange(int index) { + if (index < 0 || index >= size) { + throw new IndexOutOfBoundsException(makeOutOfBoundsExceptionMessage(index)); + } + } + + private String makeOutOfBoundsExceptionMessage(int index) { + return "Index:" + index + ", Size:" + size; + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/MessageSetSchema.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/MessageSetSchema.java new file mode 100644 index 0000000..187dc8b --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/MessageSetSchema.java @@ -0,0 +1,392 @@ +// 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. + +package com.google.protobuf; + +import java.io.IOException; +import java.util.Iterator; +import java.util.Map.Entry; + +/** Schema used for proto2 messages using message_set_wireformat. */ +final class MessageSetSchema implements Schema { + private final MessageLite defaultInstance; + private final UnknownFieldSchema unknownFieldSchema; + private final boolean hasExtensions; + private final ExtensionSchema extensionSchema; + + private MessageSetSchema( + UnknownFieldSchema unknownFieldSchema, + ExtensionSchema extensionSchema, + MessageLite defaultInstance) { + this.unknownFieldSchema = unknownFieldSchema; + this.hasExtensions = extensionSchema.hasExtensions(defaultInstance); + this.extensionSchema = extensionSchema; + this.defaultInstance = defaultInstance; + } + + static MessageSetSchema newSchema( + UnknownFieldSchema unknownFieldSchema, + ExtensionSchema extensionSchema, + MessageLite defaultInstance) { + return new MessageSetSchema(unknownFieldSchema, extensionSchema, defaultInstance); + } + + @SuppressWarnings("unchecked") + @Override + public T newInstance() { + return (T) defaultInstance.newBuilderForType().buildPartial(); + } + + @Override + public boolean equals(T message, T other) { + Object messageUnknown = unknownFieldSchema.getFromMessage(message); + Object otherUnknown = unknownFieldSchema.getFromMessage(other); + if (!messageUnknown.equals(otherUnknown)) { + return false; + } + if (hasExtensions) { + FieldSet messageExtensions = extensionSchema.getExtensions(message); + FieldSet otherExtensions = extensionSchema.getExtensions(other); + return messageExtensions.equals(otherExtensions); + } + return true; + } + + @Override + public int hashCode(T message) { + int hashCode = unknownFieldSchema.getFromMessage(message).hashCode(); + if (hasExtensions) { + FieldSet extensions = extensionSchema.getExtensions(message); + hashCode = (hashCode * 53) + extensions.hashCode(); + } + return hashCode; + } + + @Override + public void mergeFrom(T message, T other) { + SchemaUtil.mergeUnknownFields(unknownFieldSchema, message, other); + if (hasExtensions) { + SchemaUtil.mergeExtensions(extensionSchema, message, other); + } + } + + @SuppressWarnings("unchecked") + @Override + public void writeTo(T message, Writer writer) throws IOException { + FieldSet extensions = extensionSchema.getExtensions(message); + Iterator iterator = extensions.iterator(); + while (iterator.hasNext()) { + Entry extension = (Entry) iterator.next(); + FieldSet.FieldDescriptorLite fd = (FieldSet.FieldDescriptorLite) extension.getKey(); + if (fd.getLiteJavaType() != WireFormat.JavaType.MESSAGE || fd.isRepeated() || fd.isPacked()) { + throw new IllegalStateException("Found invalid MessageSet item."); + } + if (extension instanceof LazyField.LazyEntry) { + writer.writeMessageSetItem( + fd.getNumber(), ((LazyField.LazyEntry) extension).getField().toByteString()); + } else { + writer.writeMessageSetItem(fd.getNumber(), extension.getValue()); + } + } + writeUnknownFieldsHelper(unknownFieldSchema, message, writer); + } + + /** + * A helper method for wildcard capture of {@code unknownFieldSchema}. See: + * https://docs.oracle.com/javase/tutorial/java/generics/capture.html + */ + private void writeUnknownFieldsHelper( + UnknownFieldSchema unknownFieldSchema, T message, Writer writer) throws IOException { + unknownFieldSchema.writeAsMessageSetTo(unknownFieldSchema.getFromMessage(message), writer); + } + + @SuppressWarnings("ReferenceEquality") + @Override + public void mergeFrom( + T message, byte[] data, int position, int limit, ArrayDecoders.Registers registers) + throws IOException { + UnknownFieldSetLite unknownFields = ((GeneratedMessageLite) message).unknownFields; + if (unknownFields == UnknownFieldSetLite.getDefaultInstance()) { + unknownFields = UnknownFieldSetLite.newInstance(); + ((GeneratedMessageLite) message).unknownFields = unknownFields; + } + final FieldSet extensions = + ((GeneratedMessageLite.ExtendableMessage) message).ensureExtensionsAreMutable(); + GeneratedMessageLite.GeneratedExtension extension = null; + while (position < limit) { + position = ArrayDecoders.decodeVarint32(data, position, registers); + final int startTag = registers.int1; + if (startTag != WireFormat.MESSAGE_SET_ITEM_TAG) { + if (WireFormat.getTagWireType(startTag) == WireFormat.WIRETYPE_LENGTH_DELIMITED) { + extension = + (GeneratedMessageLite.GeneratedExtension) extensionSchema.findExtensionByNumber( + registers.extensionRegistry, defaultInstance, + WireFormat.getTagFieldNumber(startTag)); + if (extension != null) { + position = + ArrayDecoders.decodeMessageField( + Protobuf.getInstance().schemaFor( + extension.getMessageDefaultInstance().getClass()), + data, position, limit, registers); + extensions.setField(extension.descriptor, registers.object1); + } else { + position = + ArrayDecoders.decodeUnknownField( + startTag, data, position, limit, unknownFields, registers); + } + } else { + position = ArrayDecoders.skipField(startTag, data, position, limit, registers); + } + continue; + } + + int typeId = 0; + ByteString rawBytes = null; + + while (position < limit) { + position = ArrayDecoders.decodeVarint32(data, position, registers); + final int tag = registers.int1; + final int number = WireFormat.getTagFieldNumber(tag); + final int wireType = WireFormat.getTagWireType(tag); + switch (number) { + case WireFormat.MESSAGE_SET_TYPE_ID: + if (wireType == WireFormat.WIRETYPE_VARINT) { + position = ArrayDecoders.decodeVarint32(data, position, registers); + typeId = registers.int1; + extension = + (GeneratedMessageLite.GeneratedExtension) extensionSchema + .findExtensionByNumber(registers.extensionRegistry, defaultInstance, typeId); + continue; + } + break; + case WireFormat.MESSAGE_SET_MESSAGE: + if (extension != null) { + position = ArrayDecoders.decodeMessageField( + Protobuf.getInstance().schemaFor( + extension.getMessageDefaultInstance().getClass()), + data, position, limit, registers); + extensions.setField(extension.descriptor, registers.object1); + continue; + } else { + if (wireType == WireFormat.WIRETYPE_LENGTH_DELIMITED) { + position = ArrayDecoders.decodeBytes(data, position, registers); + rawBytes = (ByteString) registers.object1; + continue; + } + break; + } + default: + break; + } + if (tag == WireFormat.MESSAGE_SET_ITEM_END_TAG) { + break; + } + position = ArrayDecoders.skipField(tag, data, position, limit, registers); + } + + if (rawBytes != null) { + unknownFields.storeField( + WireFormat.makeTag(typeId, WireFormat.WIRETYPE_LENGTH_DELIMITED), rawBytes); + } + } + if (position != limit) { + throw InvalidProtocolBufferException.parseFailure(); + } + } + + @Override + public void mergeFrom(T message, Reader reader, ExtensionRegistryLite extensionRegistry) + throws IOException { + mergeFromHelper(unknownFieldSchema, extensionSchema, message, reader, extensionRegistry); + } + + /** + * A helper method for wildcard capture of {@code unknownFieldSchema}. See: + * https://docs.oracle.com/javase/tutorial/java/generics/capture.html + */ + @SuppressWarnings("unchecked") + private > void mergeFromHelper( + UnknownFieldSchema unknownFieldSchema, + ExtensionSchema extensionSchema, + T message, + Reader reader, + ExtensionRegistryLite extensionRegistry) + throws IOException { + UB unknownFields = unknownFieldSchema.getBuilderFromMessage(message); + FieldSet extensions = extensionSchema.getMutableExtensions(message); + try { + while (true) { + final int number = reader.getFieldNumber(); + if (number == Reader.READ_DONE) { + return; + } + if (parseMessageSetItemOrUnknownField( + reader, + extensionRegistry, + extensionSchema, + extensions, + unknownFieldSchema, + unknownFields)) { + continue; + } + // Done reading. + return; + } + } finally { + unknownFieldSchema.setBuilderToMessage(message, unknownFields); + } + } + + @Override + public void makeImmutable(T message) { + unknownFieldSchema.makeImmutable(message); + extensionSchema.makeImmutable(message); + } + + private > + boolean parseMessageSetItemOrUnknownField( + Reader reader, + ExtensionRegistryLite extensionRegistry, + ExtensionSchema extensionSchema, + FieldSet extensions, + UnknownFieldSchema unknownFieldSchema, + UB unknownFields) + throws IOException { + int startTag = reader.getTag(); + if (startTag != WireFormat.MESSAGE_SET_ITEM_TAG) { + if (WireFormat.getTagWireType(startTag) == WireFormat.WIRETYPE_LENGTH_DELIMITED) { + Object extension = + extensionSchema.findExtensionByNumber( + extensionRegistry, defaultInstance, WireFormat.getTagFieldNumber(startTag)); + if (extension != null) { + extensionSchema.parseLengthPrefixedMessageSetItem( + reader, extension, extensionRegistry, extensions); + return true; + } else { + return unknownFieldSchema.mergeOneFieldFrom(unknownFields, reader); + } + } else { + return reader.skipField(); + } + } + + // The wire format for MessageSet is: + // message MessageSet { + // repeated group Item = 1 { + // required int32 typeId = 2; + // required bytes message = 3; + // } + // } + // "typeId" is the extension's field number. The extension can only be + // a message type, where "message" contains the encoded bytes of that + // message. + // + // In practice, we will probably never see a MessageSet item in which + // the message appears before the type ID, or where either field does not + // appear exactly once. However, in theory such cases are valid, so we + // should be prepared to accept them. + + int typeId = 0; + ByteString rawBytes = null; // If we encounter "message" before "typeId" + Object extension = null; + + // Read bytes from input, if we get it's type first then parse it eagerly, + // otherwise we store the raw bytes in a local variable. + loop: + while (true) { + final int number = reader.getFieldNumber(); + if (number == Reader.READ_DONE) { + break; + } + + final int tag = reader.getTag(); + if (tag == WireFormat.MESSAGE_SET_TYPE_ID_TAG) { + typeId = reader.readUInt32(); + extension = + extensionSchema.findExtensionByNumber(extensionRegistry, defaultInstance, typeId); + continue; + } else if (tag == WireFormat.MESSAGE_SET_MESSAGE_TAG) { + if (extension != null) { + extensionSchema.parseLengthPrefixedMessageSetItem( + reader, extension, extensionRegistry, extensions); + continue; + } + // We haven't seen a type ID yet or we want parse message lazily. + rawBytes = reader.readBytes(); + continue; + } else { + if (!reader.skipField()) { + break loop; // End of group + } + } + } + + if (reader.getTag() != WireFormat.MESSAGE_SET_ITEM_END_TAG) { + throw InvalidProtocolBufferException.invalidEndTag(); + } + + // If there are any rawBytes left, it means the message content appears before the type ID. + if (rawBytes != null) { + if (extension != null) { // We known the type + // TODO(xiaofeng): Instead of reading into a temporary ByteString, maybe there is a way + // to read directly from Reader to the submessage? + extensionSchema.parseMessageSetItem(rawBytes, extension, extensionRegistry, extensions); + } else { + unknownFieldSchema.addLengthDelimited(unknownFields, typeId, rawBytes); + } + } + return true; + } + + @Override + public final boolean isInitialized(T message) { + FieldSet extensions = extensionSchema.getExtensions(message); + return extensions.isInitialized(); + } + + @Override + public int getSerializedSize(T message) { + int size = 0; + + size += getUnknownFieldsSerializedSize(unknownFieldSchema, message); + + if (hasExtensions) { + size += extensionSchema.getExtensions(message).getMessageSetSerializedSize(); + } + + return size; + } + + private int getUnknownFieldsSerializedSize( + UnknownFieldSchema schema, T message) { + UT unknowns = schema.getFromMessage(message); + return schema.getSerializedSizeAsMessageSet(unknowns); + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/NewInstanceSchemaFull.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/NewInstanceSchemaFull.java new file mode 100644 index 0000000..3433b65 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/NewInstanceSchemaFull.java @@ -0,0 +1,39 @@ +// 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. + +package com.google.protobuf; + +final class NewInstanceSchemaFull implements NewInstanceSchema { + @Override + public Object newInstance(Object defaultInstance) { + return ((GeneratedMessageV3) defaultInstance) + .newInstance(GeneratedMessageV3.UnusedPrivateParameter.INSTANCE); + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/NioByteString.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/NioByteString.java new file mode 100644 index 0000000..1e594ff --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/NioByteString.java @@ -0,0 +1,293 @@ +// 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. + +package com.google.protobuf; + +import static com.google.protobuf.Internal.checkNotNull; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InvalidObjectException; +import java.io.ObjectInputStream; +import java.io.OutputStream; +import java.nio.Buffer; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.InvalidMarkException; +import java.nio.charset.Charset; +import java.util.Collections; +import java.util.List; + +/** A {@link ByteString} that wraps around a {@link ByteBuffer}. */ +final class NioByteString extends ByteString.LeafByteString { + private final ByteBuffer buffer; + + NioByteString(ByteBuffer buffer) { + checkNotNull(buffer, "buffer"); + + // Use native byte order for fast fixed32/64 operations. + this.buffer = buffer.slice().order(ByteOrder.nativeOrder()); + } + + // ================================================================= + // Serializable + + /** Magic method that lets us override serialization behavior. */ + private Object writeReplace() { + return ByteString.copyFrom(buffer.slice()); + } + + /** Magic method that lets us override deserialization behavior. */ + private void readObject(@SuppressWarnings("unused") ObjectInputStream in) throws IOException { + throw new InvalidObjectException("NioByteString instances are not to be serialized directly"); + } + + // ================================================================= + + @Override + public byte byteAt(int index) { + try { + return buffer.get(index); + } catch (ArrayIndexOutOfBoundsException e) { + throw e; + } catch (IndexOutOfBoundsException e) { + throw new ArrayIndexOutOfBoundsException(e.getMessage()); + } + } + + @Override + public byte internalByteAt(int index) { + // it isn't possible to avoid the bounds checking inside of ByteBuffer, so just use the default + // implementation. + return byteAt(index); + } + + @Override + public int size() { + return buffer.remaining(); + } + + @Override + public ByteString substring(int beginIndex, int endIndex) { + try { + ByteBuffer slice = slice(beginIndex, endIndex); + return new NioByteString(slice); + } catch (ArrayIndexOutOfBoundsException e) { + throw e; + } catch (IndexOutOfBoundsException e) { + throw new ArrayIndexOutOfBoundsException(e.getMessage()); + } + } + + @Override + protected void copyToInternal( + byte[] target, int sourceOffset, int targetOffset, int numberToCopy) { + ByteBuffer slice = buffer.slice(); + ((Buffer) slice).position(sourceOffset); + slice.get(target, targetOffset, numberToCopy); + } + + @Override + public void copyTo(ByteBuffer target) { + target.put(buffer.slice()); + } + + @Override + public void writeTo(OutputStream out) throws IOException { + out.write(toByteArray()); + } + + @Override + boolean equalsRange(ByteString other, int offset, int length) { + return substring(0, length).equals(other.substring(offset, offset + length)); + } + + @Override + void writeToInternal(OutputStream out, int sourceOffset, int numberToWrite) throws IOException { + if (buffer.hasArray()) { + // Optimized write for array-backed buffers. + // Note that we're taking the risk that a malicious OutputStream could modify the array. + int bufferOffset = buffer.arrayOffset() + buffer.position() + sourceOffset; + out.write(buffer.array(), bufferOffset, numberToWrite); + return; + } + + ByteBufferWriter.write(slice(sourceOffset, sourceOffset + numberToWrite), out); + } + + @Override + void writeTo(ByteOutput output) throws IOException { + output.writeLazy(buffer.slice()); + } + + @Override + public ByteBuffer asReadOnlyByteBuffer() { + return buffer.asReadOnlyBuffer(); + } + + @Override + public List asReadOnlyByteBufferList() { + return Collections.singletonList(asReadOnlyByteBuffer()); + } + + @Override + protected String toStringInternal(Charset charset) { + final byte[] bytes; + final int offset; + final int length; + if (buffer.hasArray()) { + bytes = buffer.array(); + offset = buffer.arrayOffset() + buffer.position(); + length = buffer.remaining(); + } else { + // TODO(nathanmittler): Can we optimize this? + bytes = toByteArray(); + offset = 0; + length = bytes.length; + } + return new String(bytes, offset, length, charset); + } + + @Override + public boolean isValidUtf8() { + return Utf8.isValidUtf8(buffer); + } + + @Override + protected int partialIsValidUtf8(int state, int offset, int length) { + return Utf8.partialIsValidUtf8(state, buffer, offset, offset + length); + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + if (!(other instanceof ByteString)) { + return false; + } + ByteString otherString = ((ByteString) other); + if (size() != otherString.size()) { + return false; + } + if (size() == 0) { + return true; + } + if (other instanceof NioByteString) { + return buffer.equals(((NioByteString) other).buffer); + } + if (other instanceof RopeByteString) { + return other.equals(this); + } + return buffer.equals(otherString.asReadOnlyByteBuffer()); + } + + @Override + protected int partialHash(int h, int offset, int length) { + for (int i = offset; i < offset + length; i++) { + h = h * 31 + buffer.get(i); + } + return h; + } + + @Override + public InputStream newInput() { + return new InputStream() { + private final ByteBuffer buf = buffer.slice(); + + @Override + public void mark(int readlimit) { + buf.mark(); + } + + @Override + public boolean markSupported() { + return true; + } + + @Override + public void reset() throws IOException { + try { + buf.reset(); + } catch (InvalidMarkException e) { + throw new IOException(e); + } + } + + @Override + public int available() throws IOException { + return buf.remaining(); + } + + @Override + public int read() throws IOException { + if (!buf.hasRemaining()) { + return -1; + } + return buf.get() & 0xFF; + } + + @Override + public int read(byte[] bytes, int off, int len) throws IOException { + if (!buf.hasRemaining()) { + return -1; + } + + len = Math.min(len, buf.remaining()); + buf.get(bytes, off, len); + return len; + } + }; + } + + @Override + public CodedInputStream newCodedInput() { + return CodedInputStream.newInstance(buffer, true); + } + + /** + * Creates a slice of a range of this buffer. + * + * @param beginIndex the beginning index of the slice (inclusive). + * @param endIndex the end index of the slice (exclusive). + * @return the requested slice. + */ + private ByteBuffer slice(int beginIndex, int endIndex) { + if (beginIndex < buffer.position() || endIndex > buffer.limit() || beginIndex > endIndex) { + throw new IllegalArgumentException( + String.format("Invalid indices [%d, %d]", beginIndex, endIndex)); + } + + ByteBuffer slice = buffer.slice(); + ((Buffer) slice).position(beginIndex - buffer.position()); + ((Buffer) slice).limit(endIndex - buffer.position()); + return slice; + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/Parser.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/Parser.java new file mode 100644 index 0000000..22ee99b --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/Parser.java @@ -0,0 +1,242 @@ +// 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. + +package com.google.protobuf; + +import java.io.InputStream; +import java.nio.ByteBuffer; + +/** + * Abstract interface for parsing Protocol Messages. + * + *

The implementation should be stateless and thread-safe. + * + *

All methods may throw {@link InvalidProtocolBufferException}. In the event of invalid data, + * like an encoding error, the cause of the thrown exception will be {@code null}. However, if an + * I/O problem occurs, an exception is thrown with an {@link java.io.IOException} cause. + * + * @author liujisi@google.com (Pherl Liu) + */ +public interface Parser { + + // NB(jh): Other parts of the protobuf API that parse messages distinguish between an I/O problem + // (like failure reading bytes from a socket) and invalid data (encoding error) via the type of + // thrown exception. But it would be source-incompatible to make the methods in this interface do + // so since they were originally spec'ed to only throw InvalidProtocolBufferException. So callers + // must inspect the cause of the exception to distinguish these two cases. + + /** + * Parses a message of {@code MessageType} from the input. + * + *

Note: The caller should call {@link CodedInputStream#checkLastTagWas(int)} after calling + * this to verify that the last tag seen was the appropriate end-group tag, or zero for EOF. + */ + public MessageType parseFrom(CodedInputStream input) throws InvalidProtocolBufferException; + + /** + * Like {@link #parseFrom(CodedInputStream)}, but also parses extensions. The extensions that you + * want to be able to parse must be registered in {@code extensionRegistry}. Extensions not in the + * registry will be treated as unknown fields. + */ + public MessageType parseFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException; + + /** + * Like {@link #parseFrom(CodedInputStream)}, but does not throw an exception if the message is + * missing required fields. Instead, a partial message is returned. + */ + public MessageType parsePartialFrom(CodedInputStream input) throws InvalidProtocolBufferException; + + /** + * Like {@link #parseFrom(CodedInputStream input, ExtensionRegistryLite)}, but does not throw an + * exception if the message is missing required fields. Instead, a partial message is returned. + */ + public MessageType parsePartialFrom( + CodedInputStream input, ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException; + + // --------------------------------------------------------------- + // Convenience methods. + + /** + * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around + * {@link #parseFrom(CodedInputStream)}. + */ + public MessageType parseFrom(ByteBuffer data) throws InvalidProtocolBufferException; + + /** + * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around + * {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}. + */ + public MessageType parseFrom(ByteBuffer data, ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException; + /** + * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around + * {@link #parseFrom(CodedInputStream)}. + */ + public MessageType parseFrom(ByteString data) throws InvalidProtocolBufferException; + + /** + * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around + * {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}. + */ + public MessageType parseFrom(ByteString data, ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException; + + /** + * Like {@link #parseFrom(ByteString)}, but does not throw an exception if the message is missing + * required fields. Instead, a partial message is returned. + */ + public MessageType parsePartialFrom(ByteString data) throws InvalidProtocolBufferException; + + /** + * Like {@link #parseFrom(ByteString, ExtensionRegistryLite)}, but does not throw an exception if + * the message is missing required fields. Instead, a partial message is returned. + */ + public MessageType parsePartialFrom(ByteString data, ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException; + + /** + * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around + * {@link #parseFrom(CodedInputStream)}. + */ + public MessageType parseFrom(byte[] data, int off, int len) throws InvalidProtocolBufferException; + + /** + * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around + * {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}. + */ + public MessageType parseFrom( + byte[] data, int off, int len, ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException; + + /** + * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around + * {@link #parseFrom(CodedInputStream)}. + */ + public MessageType parseFrom(byte[] data) throws InvalidProtocolBufferException; + + /** + * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around + * {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}. + */ + public MessageType parseFrom(byte[] data, ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException; + + /** + * Like {@link #parseFrom(byte[], int, int)}, but does not throw an exception if the message is + * missing required fields. Instead, a partial message is returned. + */ + public MessageType parsePartialFrom(byte[] data, int off, int len) + throws InvalidProtocolBufferException; + + /** + * Like {@link #parseFrom(ByteString, ExtensionRegistryLite)}, but does not throw an exception if + * the message is missing required fields. Instead, a partial message is returned. + */ + public MessageType parsePartialFrom( + byte[] data, int off, int len, ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException; + + /** + * Like {@link #parseFrom(byte[])}, but does not throw an exception if the message is missing + * required fields. Instead, a partial message is returned. + */ + public MessageType parsePartialFrom(byte[] data) throws InvalidProtocolBufferException; + + /** + * Like {@link #parseFrom(byte[], ExtensionRegistryLite)}, but does not throw an exception if the + * message is missing required fields. Instead, a partial message is returned. + */ + public MessageType parsePartialFrom(byte[] data, ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException; + + /** + * Parse a message of {@code MessageType} from {@code input}. This is just a small wrapper around + * {@link #parseFrom(CodedInputStream)}. Note that this method always reads the entire + * input (unless it throws an exception). If you want it to stop earlier, you will need to wrap + * your input in some wrapper stream that limits reading. Or, use {@link + * MessageLite#writeDelimitedTo(java.io.OutputStream)} to write your message and {@link + * #parseDelimitedFrom(InputStream)} to read it. + * + *

Despite usually reading the entire input, this does not close the stream. + */ + public MessageType parseFrom(InputStream input) throws InvalidProtocolBufferException; + + /** + * Parses a message of {@code MessageType} from {@code input}. This is just a small wrapper around + * {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}. + */ + public MessageType parseFrom(InputStream input, ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException; + + /** + * Like {@link #parseFrom(InputStream)}, but does not throw an exception if the message is missing + * required fields. Instead, a partial message is returned. + */ + public MessageType parsePartialFrom(InputStream input) throws InvalidProtocolBufferException; + + /** + * Like {@link #parseFrom(InputStream, ExtensionRegistryLite)}, but does not throw an exception if + * the message is missing required fields. Instead, a partial message is returned. + */ + public MessageType parsePartialFrom(InputStream input, ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException; + + /** + * Like {@link #parseFrom(InputStream)}, but does not read until EOF. Instead, the size of message + * (encoded as a varint) is read first, then the message data. Use {@link + * MessageLite#writeDelimitedTo(java.io.OutputStream)} to write messages in this format. + * + * @return Parsed message if successful, or null if the stream is at EOF when the method starts. + * Any other error (including reaching EOF during parsing) will cause an exception to be + * thrown. + */ + public MessageType parseDelimitedFrom(InputStream input) throws InvalidProtocolBufferException; + + /** Like {@link #parseDelimitedFrom(InputStream)} but supporting extensions. */ + public MessageType parseDelimitedFrom(InputStream input, ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException; + + /** + * Like {@link #parseDelimitedFrom(InputStream)}, but does not throw an exception if the message + * is missing required fields. Instead, a partial message is returned. + */ + public MessageType parsePartialDelimitedFrom(InputStream input) + throws InvalidProtocolBufferException; + + /** + * Like {@link #parseDelimitedFrom(InputStream, ExtensionRegistryLite)}, but does not throw an + * exception if the message is missing required fields. Instead, a partial message is returned. + */ + public MessageType parsePartialDelimitedFrom( + InputStream input, ExtensionRegistryLite extensionRegistry) + throws InvalidProtocolBufferException; +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/Protobuf.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/Protobuf.java new file mode 100644 index 0000000..0affac5 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/Protobuf.java @@ -0,0 +1,149 @@ +// 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. + +package com.google.protobuf; + +import static com.google.protobuf.Internal.checkNotNull; + +import java.io.IOException; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * Main runtime interface for protobuf. Applications should interact with this interface (rather + * than directly accessing internal APIs) in order to perform operations on protobuf messages. + */ +@ExperimentalApi +final class Protobuf { + private static final Protobuf INSTANCE = new Protobuf(); + + private final SchemaFactory schemaFactory; + + // TODO(nathanmittler): Consider using ClassValue instead. + private final ConcurrentMap, Schema> schemaCache = + new ConcurrentHashMap, Schema>(); + + /** Gets the singleton instance of the Protobuf runtime. */ + public static Protobuf getInstance() { + return INSTANCE; + } + + /** Writes the given message to the target {@link Writer}. */ + public void writeTo(T message, Writer writer) throws IOException { + schemaFor(message).writeTo(message, writer); + } + + /** Reads fields from the given {@link Reader} and merges them into the message. */ + public void mergeFrom(T message, Reader reader) throws IOException { + mergeFrom(message, reader, ExtensionRegistryLite.getEmptyRegistry()); + } + + /** Reads fields from the given {@link Reader} and merges them into the message. */ + public void mergeFrom(T message, Reader reader, ExtensionRegistryLite extensionRegistry) + throws IOException { + schemaFor(message).mergeFrom(message, reader, extensionRegistry); + } + + /** Marks repeated/map/extension/unknown fields as immutable. */ + public void makeImmutable(T message) { + schemaFor(message).makeImmutable(message); + } + + /** Checks if all required fields are set. */ + boolean isInitialized(T message) { + return schemaFor(message).isInitialized(message); + } + + /** Gets the schema for the given message type. */ + public Schema schemaFor(Class messageType) { + checkNotNull(messageType, "messageType"); + @SuppressWarnings("unchecked") + Schema schema = (Schema) schemaCache.get(messageType); + if (schema == null) { + schema = schemaFactory.createSchema(messageType); + @SuppressWarnings("unchecked") + Schema previous = (Schema) registerSchema(messageType, schema); + if (previous != null) { + // A new schema was registered by another thread. + schema = previous; + } + } + return schema; + } + + /** Gets the schema for the given message. */ + @SuppressWarnings("unchecked") + public Schema schemaFor(T message) { + return schemaFor((Class) message.getClass()); + } + + /** + * Registers the given schema for the message type only if a schema was not already registered. + * + * @param messageType the type of message on which the schema operates. + * @param schema the schema for the message type. + * @return the previously registered schema, or {@code null} if the given schema was successfully + * registered. + */ + public Schema registerSchema(Class messageType, Schema schema) { + checkNotNull(messageType, "messageType"); + checkNotNull(schema, "schema"); + return schemaCache.putIfAbsent(messageType, schema); + } + + /** + * Visible for testing only. Registers the given schema for the message type. If a schema was + * previously registered, it will be replaced by the provided schema. + * + * @param messageType the type of message on which the schema operates. + * @param schema the schema for the message type. + * @return the previously registered schema, or {@code null} if no schema was registered + * previously. + */ + public Schema registerSchemaOverride(Class messageType, Schema schema) { + checkNotNull(messageType, "messageType"); + checkNotNull(schema, "schema"); + return schemaCache.put(messageType, schema); + } + + private Protobuf() { + schemaFactory = new ManifestSchemaFactory(); + } + + int getTotalSchemaSize() { + int result = 0; + for (Schema schema : schemaCache.values()) { + if (schema instanceof MessageSchema) { + result += ((MessageSchema) schema).getSchemaSize(); + } + } + return result; + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/RawMessageInfo.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/RawMessageInfo.java new file mode 100644 index 0000000..1735a08 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/RawMessageInfo.java @@ -0,0 +1,221 @@ +// 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. + +package com.google.protobuf; + +/** + * RawMessageInfo stores the same amount of information as {@link MessageInfo} but in a more compact + * format. + */ +final class RawMessageInfo implements MessageInfo { + + private final MessageLite defaultInstance; + + /** + * The compact format packs everything in a String object and a Object[] array. The String object + * is encoded with field number, field type, hasbits offset, oneof index, etc., whereas the + * Object[] array contains field references, class references, instance references, etc. + * + *

The String object encodes a sequence of integers into UTF-16 characters. For each int, it + * will be encoding into 1 to 3 UTF-16 characters depending on its unsigned value: + * + *

    + *
  • 1 char: [c1: 0x0000 - 0xD7FF] = int of the same value. + *
  • 2 chars: [c1: 0xE000 - 0xFFFF], [c2: 0x0000 - 0xD7FF] = (c2 << 13) | (c1 & 0x1FFF) + *
  • 3 chars: [c1: 0xE000 - 0xFFFF], [c2: 0xE000 - 0xFFFF], [c3: 0x0000 - 0xD7FF] = (c3 << 26) + * | ((c2 & 0x1FFF) << 13) | (c1 & 0x1FFF) + *
+ * + *

Note that we don't use UTF-16 surrogate pairs [0xD800 - 0xDFFF] because they have to come in + * pairs to form a valid UTF-16char sequence and don't help us encode values more efficiently. + * + *

The integer sequence encoded in the String object has the following layout: + * + *

    + *
  • [0]: flags, flags & 0x1 = is proto2?, flags & 0x2 = is message?. + *
  • [1]: field count, if 0, this is the end of the integer sequence and the corresponding + * Object[] array should be null. + *
  • [2]: oneof count + *
  • [3]: hasbits count, how many hasbits integers are generated. + *
  • [4]: min field number + *
  • [5]: max field number + *
  • [6]: total number of entries need to allocate + *
  • [7]: map field count + *
  • [8]: repeated field count, this doesn't include map fields. + *
  • [9]: size of checkInitialized array + *
  • [...]: field entries + *
+ * + *

Each field entry starts with a field number and the field type: + * + *

    + *
  • [0]: field number + *
  • [1]: field type with extra bits: + *
      + *
    • v & 0xFF = field type as defined in the FieldType class + *
    • v & 0x0100 = is required? + *
    • v & 0x0200 = is checkUtf8? + *
    • v & 0x0400 = needs isInitialized check? + *
    • v & 0x0800 = is map field with proto2 enum value? + *
    • v & 0x1000 = supports presence checking? + *
    + *
+ * + * If the (singular) field supports presence checking: + * + *
    + *
  • [2]: hasbits offset + *
+ * + * If the field is in an oneof: + * + *
    + *
  • [2]: oneof index + *
+ * + * For other types, the field entry only has field number and field type. + * + *

The Object[] array has 3 sections: + * + *

    + *
  • ---- oneof section ---- + *
      + *
    • [0]: value field for oneof 1. + *
    • [1]: case field for oneof 1. + *
    • ... + *
    • [.]: value field for oneof n. + *
    • [.]: case field for oneof n. + *
    + *
  • ---- hasbits section ---- + *
      + *
    • [.]: hasbits field 1 + *
    • [.]: hasbits field 2 + *
    • ... + *
    • [.]: hasbits field n + *
    + *
  • ---- field section ---- + *
      + *
    • [...]: field entries + *
    + *
+ * + *

In the Object[] array, field entries are ordered in the same way as field entries in the + * String object. The size of each entry is determined by the field type. + * + *

    + *
  • Oneof field: + *
      + *
    • Oneof message field: + *
        + *
      • [0]: message class reference. + *
      + *
    • Oneof enum fieldin proto2: + *
        + *
      • [0]: EnumLiteMap + *
      + *
    • For all other oneof fields, field entry in the Object[] array is empty. + *
    + *
  • Repeated message field: + *
      + *
    • [0]: field reference + *
    • [1]: message class reference + *
    + *
  • Proto2 singular/repeated enum field: + *
      + *
    • [0]: field reference + *
    • [1]: EnumLiteMap + *
    + *
  • Map field with a proto2 enum value: + *
      + *
    • [0]: field reference + *
    • [1]: map default entry instance + *
    • [2]: EnumLiteMap + *
    + *
  • Map field with other value types: + *
      + *
    • [0]: field reference + *
    • [1]: map default entry instance + *
    + *
  • All other field type: + *
      + *
    • [0]: field reference + *
    + *
+ * + *

In order to read the field info from this compact format, a reader needs to progress through + * the String object and the Object[] array simultaneously. + */ + private final String info; + + private final Object[] objects; + private final int flags; + + RawMessageInfo(MessageLite defaultInstance, String info, Object[] objects) { + this.defaultInstance = defaultInstance; + this.info = info; + this.objects = objects; + int position = 0; + int value = (int) info.charAt(position++); + if (value < 0xD800) { + flags = value; + } else { + int result = value & 0x1FFF; + int shift = 13; + while ((value = info.charAt(position++)) >= 0xD800) { + result |= (value & 0x1FFF) << shift; + shift += 13; + } + flags = result | (value << shift); + } + } + + String getStringInfo() { + return info; + } + + Object[] getObjects() { + return objects; + } + + @Override + public MessageLite getDefaultInstance() { + return defaultInstance; + } + + @Override + public ProtoSyntax getSyntax() { + return (flags & 0x1) == 0x1 ? ProtoSyntax.PROTO2 : ProtoSyntax.PROTO3; + } + + @Override + public boolean isMessageSetWireFormat() { + return (flags & 0x2) == 0x2; + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/SchemaFactory.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/SchemaFactory.java new file mode 100644 index 0000000..cf38dd6 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/SchemaFactory.java @@ -0,0 +1,38 @@ +// 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. + +package com.google.protobuf; + +/** A factory that manufactures {@link Schema} instances for protobuf messages. */ +@ExperimentalApi +interface SchemaFactory { + /** Creates a schema instance for the given protobuf message type. */ + Schema createSchema(Class messageType); +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/TextFormatParseLocation.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/TextFormatParseLocation.java new file mode 100644 index 0000000..eebfb1b --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/TextFormatParseLocation.java @@ -0,0 +1,101 @@ +// 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. + +package com.google.protobuf; + +import java.util.Arrays; + +/** + * A location in the source code. + * + *

A location is the starting line number and starting column number. + */ +public final class TextFormatParseLocation { + + /** The empty location. */ + public static final TextFormatParseLocation EMPTY = new TextFormatParseLocation(-1, -1); + + /** + * Create a location. + * + * @param line the starting line number + * @param column the starting column number + * @return a {@code ParseLocation} + */ + static TextFormatParseLocation create(int line, int column) { + if (line == -1 && column == -1) { + return EMPTY; + } + if (line < 0 || column < 0) { + throw new IllegalArgumentException( + String.format("line and column values must be >= 0: line %d, column: %d", line, column)); + } + return new TextFormatParseLocation(line, column); + } + + private final int line; + private final int column; + + private TextFormatParseLocation(int line, int column) { + this.line = line; + this.column = column; + } + + public int getLine() { + return line; + } + + public int getColumn() { + return column; + } + + @Override + public String toString() { + return String.format("ParseLocation{line=%d, column=%d}", line, column); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof TextFormatParseLocation)) { + return false; + } + TextFormatParseLocation that = (TextFormatParseLocation) o; + return (this.line == that.getLine()) && (this.column == that.getColumn()); + } + + @Override + public int hashCode() { + int[] values = {line, column}; + return Arrays.hashCode(values); + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/TypeRegistry.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/TypeRegistry.java new file mode 100644 index 0000000..422ff1f --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/TypeRegistry.java @@ -0,0 +1,159 @@ +// 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. + +package com.google.protobuf; + +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FileDescriptor; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.logging.Logger; + +/** + * A TypeRegistry is used to resolve Any messages. You must provide a TypeRegistry containing all + * message types used in Any message fields. + */ +public class TypeRegistry { + private static final Logger logger = Logger.getLogger(TypeRegistry.class.getName()); + + private static class EmptyTypeRegistryHolder { + private static final TypeRegistry EMPTY = + new TypeRegistry(Collections.emptyMap()); + } + + public static TypeRegistry getEmptyTypeRegistry() { + return EmptyTypeRegistryHolder.EMPTY; + } + + + public static Builder newBuilder() { + return new Builder(); + } + + /** + * Find a type by its full name. Returns null if it cannot be found in this {@link TypeRegistry}. + */ + public Descriptor find(String name) { + return types.get(name); + } + + /** + * Find a type by its typeUrl. Returns null if it cannot be found in this {@link TypeRegistry}. + */ + public final Descriptor getDescriptorForTypeUrl(String typeUrl) + throws InvalidProtocolBufferException { + return find(getTypeName(typeUrl)); + } + + private final Map types; + + TypeRegistry(Map types) { + this.types = types; + } + + private static String getTypeName(String typeUrl) throws InvalidProtocolBufferException { + String[] parts = typeUrl.split("/"); + if (parts.length == 1) { + throw new InvalidProtocolBufferException("Invalid type url found: " + typeUrl); + } + return parts[parts.length - 1]; + } + + /** A Builder is used to build {@link TypeRegistry}. */ + public static final class Builder { + private Builder() {} + + /** + * Adds a message type and all types defined in the same .proto file as well as all transitively + * imported .proto files to this {@link Builder}. + */ + public Builder add(Descriptor messageType) { + if (types == null) { + throw new IllegalStateException("A TypeRegistry.Builder can only be used once."); + } + addFile(messageType.getFile()); + return this; + } + + /** + * Adds message types and all types defined in the same .proto file as well as all transitively + * imported .proto files to this {@link Builder}. + */ + public Builder add(Iterable messageTypes) { + if (types == null) { + throw new IllegalStateException("A TypeRegistry.Builder can only be used once."); + } + for (Descriptor type : messageTypes) { + addFile(type.getFile()); + } + return this; + } + + /** Builds a {@link TypeRegistry}. This method can only be called once for one Builder. */ + public TypeRegistry build() { + TypeRegistry result = new TypeRegistry(types); + // Make sure the built {@link TypeRegistry} is immutable. + types = null; + return result; + } + + private void addFile(FileDescriptor file) { + // Skip the file if it's already added. + if (!files.add(file.getFullName())) { + return; + } + for (FileDescriptor dependency : file.getDependencies()) { + addFile(dependency); + } + for (Descriptor message : file.getMessageTypes()) { + addMessage(message); + } + } + + private void addMessage(Descriptor message) { + for (Descriptor nestedType : message.getNestedTypes()) { + addMessage(nestedType); + } + + if (types.containsKey(message.getFullName())) { + logger.warning("Type " + message.getFullName() + " is added multiple times."); + return; + } + + types.put(message.getFullName(), message); + } + + private final Set files = new HashSet<>(); + private Map types = new HashMap<>(); + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/Utf8.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/Utf8.java new file mode 100644 index 0000000..7c9133e --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/main/java/com/google/protobuf/Utf8.java @@ -0,0 +1,1996 @@ +// 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. + +package com.google.protobuf; + +import static com.google.protobuf.UnsafeUtil.addressOffset; +import static com.google.protobuf.UnsafeUtil.hasUnsafeArrayOperations; +import static com.google.protobuf.UnsafeUtil.hasUnsafeByteBufferOperations; +import static java.lang.Character.MAX_SURROGATE; +import static java.lang.Character.MIN_HIGH_SURROGATE; +import static java.lang.Character.MIN_LOW_SURROGATE; +import static java.lang.Character.MIN_SUPPLEMENTARY_CODE_POINT; +import static java.lang.Character.MIN_SURROGATE; +import static java.lang.Character.isSurrogatePair; +import static java.lang.Character.toCodePoint; + +import java.nio.ByteBuffer; + +/** + * A set of low-level, high-performance static utility methods related to the UTF-8 character + * encoding. This class has no dependencies outside of the core JDK libraries. + * + *

There are several variants of UTF-8. The one implemented by this class is the restricted + * definition of UTF-8 introduced in Unicode 3.1, which mandates the rejection of "overlong" byte + * sequences as well as rejection of 3-byte surrogate codepoint byte sequences. Note that the UTF-8 + * decoder included in Oracle's JDK has been modified to also reject "overlong" byte sequences, but + * (as of 2011) still accepts 3-byte surrogate codepoint byte sequences. + * + *

The byte sequences considered valid by this class are exactly those that can be roundtrip + * converted to Strings and back to bytes using the UTF-8 charset, without loss: + * + *

{@code
+ * Arrays.equals(bytes, new String(bytes, Internal.UTF_8).getBytes(Internal.UTF_8))
+ * }
+ * + *

See the Unicode Standard,
Table 3-6. UTF-8 Bit Distribution,
Table 3-7. + * Well Formed UTF-8 Byte Sequences. + * + *

This class supports decoding of partial byte sequences, so that the bytes in a complete UTF-8 + * byte sequences can be stored in multiple segments. Methods typically return {@link #MALFORMED} if + * the partial byte sequence is definitely not well-formed, {@link #COMPLETE} if it is well-formed + * in the absence of additional input, or if the byte sequence apparently terminated in the middle + * of a character, an opaque integer "state" value containing enough information to decode the + * character when passed to a subsequent invocation of a partial decoding method. + * + * @author martinrb@google.com (Martin Buchholz) + */ +// TODO(nathanmittler): Copy changes in this class back to Guava +final class Utf8 { + + /** + * UTF-8 is a runtime hot spot so we attempt to provide heavily optimized implementations + * depending on what is available on the platform. The processor is the platform-optimized + * delegate for which all methods are delegated directly to. + */ + private static final Processor processor = + (UnsafeProcessor.isAvailable() && !Android.isOnAndroidDevice()) + ? new UnsafeProcessor() + : new SafeProcessor(); + + /** + * A mask used when performing unsafe reads to determine if a long value contains any non-ASCII + * characters (i.e. any byte >= 0x80). + */ + private static final long ASCII_MASK_LONG = 0x8080808080808080L; + + /** + * Maximum number of bytes per Java UTF-16 char in UTF-8. + * + * @see java.nio.charset.CharsetEncoder#maxBytesPerChar() + */ + static final int MAX_BYTES_PER_CHAR = 3; + + /** + * State value indicating that the byte sequence is well-formed and complete (no further bytes are + * needed to complete a character). + */ + public static final int COMPLETE = 0; + + /** State value indicating that the byte sequence is definitely not well-formed. */ + public static final int MALFORMED = -1; + + /** + * Used by {@code Unsafe} UTF-8 string validation logic to determine the minimum string length + * above which to employ an optimized algorithm for counting ASCII characters. The reason for this + * threshold is that for small strings, the optimization may not be beneficial or may even + * negatively impact performance since it requires additional logic to avoid unaligned reads (when + * calling {@code Unsafe.getLong}). This threshold guarantees that even if the initial offset is + * unaligned, we're guaranteed to make at least one call to {@code Unsafe.getLong()} which + * provides a performance improvement that entirely subsumes the cost of the additional logic. + */ + private static final int UNSAFE_COUNT_ASCII_THRESHOLD = 16; + + // Other state values include the partial bytes of the incomplete + // character to be decoded in the simplest way: we pack the bytes + // into the state int in little-endian order. For example: + // + // int state = byte1 ^ (byte2 << 8) ^ (byte3 << 16); + // + // Such a state is unpacked thus (note the ~ operation for byte2 to + // undo byte1's sign-extension bits): + // + // int byte1 = (byte) state; + // int byte2 = (byte) ~(state >> 8); + // int byte3 = (byte) (state >> 16); + // + // We cannot store a zero byte in the state because it would be + // indistinguishable from the absence of a byte. But we don't need + // to, because partial bytes must always be negative. When building + // a state, we ensure that byte1 is negative and subsequent bytes + // are valid trailing bytes. + + /** + * Returns {@code true} if the given byte array is a well-formed UTF-8 byte sequence. + * + *

This is a convenience method, equivalent to a call to {@code isValidUtf8(bytes, 0, + * bytes.length)}. + */ + public static boolean isValidUtf8(byte[] bytes) { + return processor.isValidUtf8(bytes, 0, bytes.length); + } + + /** + * Returns {@code true} if the given byte array slice is a well-formed UTF-8 byte sequence. The + * range of bytes to be checked extends from index {@code index}, inclusive, to {@code limit}, + * exclusive. + * + *

This is a convenience method, equivalent to {@code partialIsValidUtf8(bytes, index, limit) + * == Utf8.COMPLETE}. + */ + public static boolean isValidUtf8(byte[] bytes, int index, int limit) { + return processor.isValidUtf8(bytes, index, limit); + } + + /** + * Tells whether the given byte array slice is a well-formed, malformed, or incomplete UTF-8 byte + * sequence. The range of bytes to be checked extends from index {@code index}, inclusive, to + * {@code limit}, exclusive. + * + * @param state either {@link Utf8#COMPLETE} (if this is the initial decoding operation) or the + * value returned from a call to a partial decoding method for the previous bytes + * @return {@link #MALFORMED} if the partial byte sequence is definitely not well-formed, {@link + * #COMPLETE} if it is well-formed (no additional input needed), or if the byte sequence is + * "incomplete", i.e. apparently terminated in the middle of a character, an opaque integer + * "state" value containing enough information to decode the character when passed to a + * subsequent invocation of a partial decoding method. + */ + public static int partialIsValidUtf8(int state, byte[] bytes, int index, int limit) { + return processor.partialIsValidUtf8(state, bytes, index, limit); + } + + private static int incompleteStateFor(int byte1) { + return (byte1 > (byte) 0xF4) ? MALFORMED : byte1; + } + + private static int incompleteStateFor(int byte1, int byte2) { + return (byte1 > (byte) 0xF4 || byte2 > (byte) 0xBF) ? MALFORMED : byte1 ^ (byte2 << 8); + } + + private static int incompleteStateFor(int byte1, int byte2, int byte3) { + return (byte1 > (byte) 0xF4 || byte2 > (byte) 0xBF || byte3 > (byte) 0xBF) + ? MALFORMED + : byte1 ^ (byte2 << 8) ^ (byte3 << 16); + } + + private static int incompleteStateFor(byte[] bytes, int index, int limit) { + int byte1 = bytes[index - 1]; + switch (limit - index) { + case 0: + return incompleteStateFor(byte1); + case 1: + return incompleteStateFor(byte1, bytes[index]); + case 2: + return incompleteStateFor(byte1, bytes[index], bytes[index + 1]); + default: + throw new AssertionError(); + } + } + + private static int incompleteStateFor( + final ByteBuffer buffer, final int byte1, final int index, final int remaining) { + switch (remaining) { + case 0: + return incompleteStateFor(byte1); + case 1: + return incompleteStateFor(byte1, buffer.get(index)); + case 2: + return incompleteStateFor(byte1, buffer.get(index), buffer.get(index + 1)); + default: + throw new AssertionError(); + } + } + + // These UTF-8 handling methods are copied from Guava's Utf8 class with a modification to throw + // a protocol buffer local exception. This exception is then caught in CodedOutputStream so it can + // fallback to more lenient behavior. + + static class UnpairedSurrogateException extends IllegalArgumentException { + UnpairedSurrogateException(int index, int length) { + super("Unpaired surrogate at index " + index + " of " + length); + } + } + + /** + * Returns the number of bytes in the UTF-8-encoded form of {@code sequence}. For a string, this + * method is equivalent to {@code string.getBytes(UTF_8).length}, but is more efficient in both + * time and space. + * + * @throws IllegalArgumentException if {@code sequence} contains ill-formed UTF-16 (unpaired + * surrogates) + */ + static int encodedLength(CharSequence sequence) { + // Warning to maintainers: this implementation is highly optimized. + int utf16Length = sequence.length(); + int utf8Length = utf16Length; + int i = 0; + + // This loop optimizes for pure ASCII. + while (i < utf16Length && sequence.charAt(i) < 0x80) { + i++; + } + + // This loop optimizes for chars less than 0x800. + for (; i < utf16Length; i++) { + char c = sequence.charAt(i); + if (c < 0x800) { + utf8Length += ((0x7f - c) >>> 31); // branch free! + } else { + utf8Length += encodedLengthGeneral(sequence, i); + break; + } + } + + if (utf8Length < utf16Length) { + // Necessary and sufficient condition for overflow because of maximum 3x expansion + throw new IllegalArgumentException( + "UTF-8 length does not fit in int: " + (utf8Length + (1L << 32))); + } + return utf8Length; + } + + private static int encodedLengthGeneral(CharSequence sequence, int start) { + int utf16Length = sequence.length(); + int utf8Length = 0; + for (int i = start; i < utf16Length; i++) { + char c = sequence.charAt(i); + if (c < 0x800) { + utf8Length += (0x7f - c) >>> 31; // branch free! + } else { + utf8Length += 2; + // jdk7+: if (Character.isSurrogate(c)) { + if (Character.MIN_SURROGATE <= c && c <= Character.MAX_SURROGATE) { + // Check that we have a well-formed surrogate pair. + int cp = Character.codePointAt(sequence, i); + if (cp < MIN_SUPPLEMENTARY_CODE_POINT) { + throw new UnpairedSurrogateException(i, utf16Length); + } + i++; + } + } + } + return utf8Length; + } + + static int encode(CharSequence in, byte[] out, int offset, int length) { + return processor.encodeUtf8(in, out, offset, length); + } + // End Guava UTF-8 methods. + + /** + * Determines if the given {@link ByteBuffer} is a valid UTF-8 string. + * + *

Selects an optimal algorithm based on the type of {@link ByteBuffer} (i.e. heap or direct) + * and the capabilities of the platform. + * + * @param buffer the buffer to check. + * @see Utf8#isValidUtf8(byte[], int, int) + */ + static boolean isValidUtf8(ByteBuffer buffer) { + return processor.isValidUtf8(buffer, buffer.position(), buffer.remaining()); + } + + /** + * Determines if the given {@link ByteBuffer} is a partially valid UTF-8 string. + * + *

Selects an optimal algorithm based on the type of {@link ByteBuffer} (i.e. heap or direct) + * and the capabilities of the platform. + * + * @param buffer the buffer to check. + * @see Utf8#partialIsValidUtf8(int, byte[], int, int) + */ + static int partialIsValidUtf8(int state, ByteBuffer buffer, int index, int limit) { + return processor.partialIsValidUtf8(state, buffer, index, limit); + } + + /** + * Decodes the given UTF-8 portion of the {@link ByteBuffer} into a {@link String}. + * + * @throws InvalidProtocolBufferException if the input is not valid UTF-8. + */ + static String decodeUtf8(ByteBuffer buffer, int index, int size) + throws InvalidProtocolBufferException { + return processor.decodeUtf8(buffer, index, size); + } + + /** + * Decodes the given UTF-8 encoded byte array slice into a {@link String}. + * + * @throws InvalidProtocolBufferException if the input is not valid UTF-8. + */ + static String decodeUtf8(byte[] bytes, int index, int size) + throws InvalidProtocolBufferException { + return processor.decodeUtf8(bytes, index, size); + } + + /** + * Encodes the given characters to the target {@link ByteBuffer} using UTF-8 encoding. + * + *

Selects an optimal algorithm based on the type of {@link ByteBuffer} (i.e. heap or direct) + * and the capabilities of the platform. + * + * @param in the source string to be encoded + * @param out the target buffer to receive the encoded string. + * @see Utf8#encode(CharSequence, byte[], int, int) + */ + static void encodeUtf8(CharSequence in, ByteBuffer out) { + processor.encodeUtf8(in, out); + } + + /** + * Counts (approximately) the number of consecutive ASCII characters in the given buffer. The byte + * order of the {@link ByteBuffer} does not matter, so performance can be improved if native byte + * order is used (i.e. no byte-swapping in {@link ByteBuffer#getLong(int)}). + * + * @param buffer the buffer to be scanned for ASCII chars + * @param index the starting index of the scan + * @param limit the limit within buffer for the scan + * @return the number of ASCII characters found. The stopping position will be at or before the + * first non-ASCII byte. + */ + private static int estimateConsecutiveAscii(ByteBuffer buffer, int index, int limit) { + int i = index; + final int lim = limit - 7; + // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). + // To speed things up further, we're reading longs instead of bytes so we use a mask to + // determine if any byte in the current long is non-ASCII. + for (; i < lim && (buffer.getLong(i) & ASCII_MASK_LONG) == 0; i += 8) {} + return i - index; + } + + /** A processor of UTF-8 strings, providing methods for checking validity and encoding. */ + // TODO(nathanmittler): Add support for Memory/MemoryBlock on Android. + abstract static class Processor { + /** + * Returns {@code true} if the given byte array slice is a well-formed UTF-8 byte sequence. The + * range of bytes to be checked extends from index {@code index}, inclusive, to {@code limit}, + * exclusive. + * + *

This is a convenience method, equivalent to {@code partialIsValidUtf8(bytes, index, limit) + * == Utf8.COMPLETE}. + */ + final boolean isValidUtf8(byte[] bytes, int index, int limit) { + return partialIsValidUtf8(COMPLETE, bytes, index, limit) == COMPLETE; + } + + /** + * Tells whether the given byte array slice is a well-formed, malformed, or incomplete UTF-8 + * byte sequence. The range of bytes to be checked extends from index {@code index}, inclusive, + * to {@code limit}, exclusive. + * + * @param state either {@link Utf8#COMPLETE} (if this is the initial decoding operation) or the + * value returned from a call to a partial decoding method for the previous bytes + * @return {@link #MALFORMED} if the partial byte sequence is definitely not well-formed, {@link + * #COMPLETE} if it is well-formed (no additional input needed), or if the byte sequence is + * "incomplete", i.e. apparently terminated in the middle of a character, an opaque integer + * "state" value containing enough information to decode the character when passed to a + * subsequent invocation of a partial decoding method. + */ + abstract int partialIsValidUtf8(int state, byte[] bytes, int index, int limit); + + /** + * Returns {@code true} if the given portion of the {@link ByteBuffer} is a well-formed UTF-8 + * byte sequence. The range of bytes to be checked extends from index {@code index}, inclusive, + * to {@code limit}, exclusive. + * + *

This is a convenience method, equivalent to {@code partialIsValidUtf8(bytes, index, limit) + * == Utf8.COMPLETE}. + */ + final boolean isValidUtf8(ByteBuffer buffer, int index, int limit) { + return partialIsValidUtf8(COMPLETE, buffer, index, limit) == COMPLETE; + } + + /** + * Indicates whether or not the given buffer contains a valid UTF-8 string. + * + * @param buffer the buffer to check. + * @return {@code true} if the given buffer contains a valid UTF-8 string. + */ + final int partialIsValidUtf8( + final int state, final ByteBuffer buffer, int index, final int limit) { + if (buffer.hasArray()) { + final int offset = buffer.arrayOffset(); + return partialIsValidUtf8(state, buffer.array(), offset + index, offset + limit); + } else if (buffer.isDirect()) { + return partialIsValidUtf8Direct(state, buffer, index, limit); + } + return partialIsValidUtf8Default(state, buffer, index, limit); + } + + /** Performs validation for direct {@link ByteBuffer} instances. */ + abstract int partialIsValidUtf8Direct( + final int state, final ByteBuffer buffer, int index, final int limit); + + /** + * Performs validation for {@link ByteBuffer} instances using the {@link ByteBuffer} API rather + * than potentially faster approaches. This first completes validation for the current character + * (provided by {@code state}) and then finishes validation for the sequence. + */ + final int partialIsValidUtf8Default( + final int state, final ByteBuffer buffer, int index, final int limit) { + if (state != COMPLETE) { + // The previous decoding operation was incomplete (or malformed). + // We look for a well-formed sequence consisting of bytes from + // the previous decoding operation (stored in state) together + // with bytes from the array slice. + // + // We expect such "straddler characters" to be rare. + + if (index >= limit) { // No bytes? No progress. + return state; + } + + byte byte1 = (byte) state; + // byte1 is never ASCII. + if (byte1 < (byte) 0xE0) { + // two-byte form + + // Simultaneously checks for illegal trailing-byte in + // leading position and overlong 2-byte form. + if (byte1 < (byte) 0xC2 + // byte2 trailing-byte test + || buffer.get(index++) > (byte) 0xBF) { + return MALFORMED; + } + } else if (byte1 < (byte) 0xF0) { + // three-byte form + + // Get byte2 from saved state or array + byte byte2 = (byte) ~(state >> 8); + if (byte2 == 0) { + byte2 = buffer.get(index++); + if (index >= limit) { + return incompleteStateFor(byte1, byte2); + } + } + if (byte2 > (byte) 0xBF + // overlong? 5 most significant bits must not all be zero + || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) + // illegal surrogate codepoint? + || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) + // byte3 trailing-byte test + || buffer.get(index++) > (byte) 0xBF) { + return MALFORMED; + } + } else { + // four-byte form + + // Get byte2 and byte3 from saved state or array + byte byte2 = (byte) ~(state >> 8); + byte byte3 = 0; + if (byte2 == 0) { + byte2 = buffer.get(index++); + if (index >= limit) { + return incompleteStateFor(byte1, byte2); + } + } else { + byte3 = (byte) (state >> 16); + } + if (byte3 == 0) { + byte3 = buffer.get(index++); + if (index >= limit) { + return incompleteStateFor(byte1, byte2, byte3); + } + } + + // If we were called with state == MALFORMED, then byte1 is 0xFF, + // which never occurs in well-formed UTF-8, and so we will return + // MALFORMED again below. + + if (byte2 > (byte) 0xBF + // Check that 1 <= plane <= 16. Tricky optimized form of: + // if (byte1 > (byte) 0xF4 || + // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || + // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) + || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 + // byte3 trailing-byte test + || byte3 > (byte) 0xBF + // byte4 trailing-byte test + || buffer.get(index++) > (byte) 0xBF) { + return MALFORMED; + } + } + } + + // Finish validation for the sequence. + return partialIsValidUtf8(buffer, index, limit); + } + + /** + * Performs validation for {@link ByteBuffer} instances using the {@link ByteBuffer} API rather + * than potentially faster approaches. + */ + private static int partialIsValidUtf8(final ByteBuffer buffer, int index, final int limit) { + index += estimateConsecutiveAscii(buffer, index, limit); + + for (; ; ) { + // Optimize for interior runs of ASCII bytes. + // TODO(nathanmittler): Consider checking 8 bytes at a time after some threshold? + // Maybe after seeing a few in a row that are ASCII, go back to fast mode? + int byte1; + do { + if (index >= limit) { + return COMPLETE; + } + } while ((byte1 = buffer.get(index++)) >= 0); + + // If we're here byte1 is not ASCII. Only need to handle 2-4 byte forms. + if (byte1 < (byte) 0xE0) { + // Two-byte form (110xxxxx 10xxxxxx) + if (index >= limit) { + // Incomplete sequence + return byte1; + } + + // Simultaneously checks for illegal trailing-byte in + // leading position and overlong 2-byte form. + if (byte1 < (byte) 0xC2 || buffer.get(index) > (byte) 0xBF) { + return MALFORMED; + } + index++; + } else if (byte1 < (byte) 0xF0) { + // Three-byte form (1110xxxx 10xxxxxx 10xxxxxx) + if (index >= limit - 1) { + // Incomplete sequence + return incompleteStateFor(buffer, byte1, index, limit - index); + } + + final byte byte2 = buffer.get(index++); + if (byte2 > (byte) 0xBF + // overlong? 5 most significant bits must not all be zero + || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) + // check for illegal surrogate codepoints + || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) + // byte3 trailing-byte test + || buffer.get(index) > (byte) 0xBF) { + return MALFORMED; + } + index++; + } else { + // Four-byte form (1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx) + if (index >= limit - 2) { + // Incomplete sequence + return incompleteStateFor(buffer, byte1, index, limit - index); + } + + // TODO(nathanmittler): Consider using getInt() to improve performance. + final int byte2 = buffer.get(index++); + if (byte2 > (byte) 0xBF + // Check that 1 <= plane <= 16. Tricky optimized form of: + // if (byte1 > (byte) 0xF4 || + // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || + // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) + || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 + // byte3 trailing-byte test + || buffer.get(index++) > (byte) 0xBF + // byte4 trailing-byte test + || buffer.get(index++) > (byte) 0xBF) { + return MALFORMED; + } + } + } + } + + /** + * Decodes the given byte array slice into a {@link String}. + * + * @throws InvalidProtocolBufferException if the byte array slice is not valid UTF-8. + */ + abstract String decodeUtf8(byte[] bytes, int index, int size) + throws InvalidProtocolBufferException; + + /** + * Decodes the given portion of the {@link ByteBuffer} into a {@link String}. + * + * @throws InvalidProtocolBufferException if the portion of the buffer is not valid UTF-8. + */ + final String decodeUtf8(ByteBuffer buffer, int index, int size) + throws InvalidProtocolBufferException { + if (buffer.hasArray()) { + final int offset = buffer.arrayOffset(); + return decodeUtf8(buffer.array(), offset + index, size); + } else if (buffer.isDirect()) { + return decodeUtf8Direct(buffer, index, size); + } + return decodeUtf8Default(buffer, index, size); + } + + /** Decodes direct {@link ByteBuffer} instances into {@link String}. */ + abstract String decodeUtf8Direct(ByteBuffer buffer, int index, int size) + throws InvalidProtocolBufferException; + + /** + * Decodes {@link ByteBuffer} instances using the {@link ByteBuffer} API rather than potentially + * faster approaches. + */ + final String decodeUtf8Default(ByteBuffer buffer, int index, int size) + throws InvalidProtocolBufferException { + // Bitwise OR combines the sign bits so any negative value fails the check. + if ((index | size | buffer.limit() - index - size) < 0) { + throw new ArrayIndexOutOfBoundsException( + String.format("buffer limit=%d, index=%d, limit=%d", buffer.limit(), index, size)); + } + + int offset = index; + final int limit = offset + size; + + // The longest possible resulting String is the same as the number of input bytes, when it is + // all ASCII. For other cases, this over-allocates and we will truncate in the end. + char[] resultArr = new char[size]; + int resultPos = 0; + + // Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this). + // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). + while (offset < limit) { + byte b = buffer.get(offset); + if (!DecodeUtil.isOneByte(b)) { + break; + } + offset++; + DecodeUtil.handleOneByte(b, resultArr, resultPos++); + } + + while (offset < limit) { + byte byte1 = buffer.get(offset++); + if (DecodeUtil.isOneByte(byte1)) { + DecodeUtil.handleOneByte(byte1, resultArr, resultPos++); + // It's common for there to be multiple ASCII characters in a run mixed in, so add an + // extra optimized loop to take care of these runs. + while (offset < limit) { + byte b = buffer.get(offset); + if (!DecodeUtil.isOneByte(b)) { + break; + } + offset++; + DecodeUtil.handleOneByte(b, resultArr, resultPos++); + } + } else if (DecodeUtil.isTwoBytes(byte1)) { + if (offset >= limit) { + throw InvalidProtocolBufferException.invalidUtf8(); + } + DecodeUtil.handleTwoBytes( + byte1, /* byte2 */ buffer.get(offset++), resultArr, resultPos++); + } else if (DecodeUtil.isThreeBytes(byte1)) { + if (offset >= limit - 1) { + throw InvalidProtocolBufferException.invalidUtf8(); + } + DecodeUtil.handleThreeBytes( + byte1, + /* byte2 */ buffer.get(offset++), + /* byte3 */ buffer.get(offset++), + resultArr, + resultPos++); + } else { + if (offset >= limit - 2) { + throw InvalidProtocolBufferException.invalidUtf8(); + } + DecodeUtil.handleFourBytes( + byte1, + /* byte2 */ buffer.get(offset++), + /* byte3 */ buffer.get(offset++), + /* byte4 */ buffer.get(offset++), + resultArr, + resultPos++); + // 4-byte case requires two chars. + resultPos++; + } + } + + return new String(resultArr, 0, resultPos); + } + + /** + * Encodes an input character sequence ({@code in}) to UTF-8 in the target array ({@code out}). + * For a string, this method is similar to + * + *

{@code
+     * byte[] a = string.getBytes(UTF_8);
+     * System.arraycopy(a, 0, bytes, offset, a.length);
+     * return offset + a.length;
+     * }
+ * + * but is more efficient in both time and space. One key difference is that this method requires + * paired surrogates, and therefore does not support chunking. While {@code + * String.getBytes(UTF_8)} replaces unpaired surrogates with the default replacement character, + * this method throws {@link UnpairedSurrogateException}. + * + *

To ensure sufficient space in the output buffer, either call {@link #encodedLength} to + * compute the exact amount needed, or leave room for {@code Utf8.MAX_BYTES_PER_CHAR * + * sequence.length()}, which is the largest possible number of bytes that any input can be + * encoded to. + * + * @param in the input character sequence to be encoded + * @param out the target array + * @param offset the starting offset in {@code bytes} to start writing at + * @param length the length of the {@code bytes}, starting from {@code offset} + * @throws UnpairedSurrogateException if {@code sequence} contains ill-formed UTF-16 (unpaired + * surrogates) + * @throws ArrayIndexOutOfBoundsException if {@code sequence} encoded in UTF-8 is longer than + * {@code bytes.length - offset} + * @return the new offset, equivalent to {@code offset + Utf8.encodedLength(sequence)} + */ + abstract int encodeUtf8(CharSequence in, byte[] out, int offset, int length); + + /** + * Encodes an input character sequence ({@code in}) to UTF-8 in the target buffer ({@code out}). + * Upon returning from this method, the {@code out} position will point to the position after + * the last encoded byte. This method requires paired surrogates, and therefore does not support + * chunking. + * + *

To ensure sufficient space in the output buffer, either call {@link #encodedLength} to + * compute the exact amount needed, or leave room for {@code Utf8.MAX_BYTES_PER_CHAR * + * in.length()}, which is the largest possible number of bytes that any input can be encoded to. + * + * @param in the source character sequence to be encoded + * @param out the target buffer + * @throws UnpairedSurrogateException if {@code in} contains ill-formed UTF-16 (unpaired + * surrogates) + * @throws ArrayIndexOutOfBoundsException if {@code in} encoded in UTF-8 is longer than {@code + * out.remaining()} + */ + final void encodeUtf8(CharSequence in, ByteBuffer out) { + if (out.hasArray()) { + final int offset = out.arrayOffset(); + int endIndex = Utf8.encode(in, out.array(), offset + out.position(), out.remaining()); + out.position(endIndex - offset); + } else if (out.isDirect()) { + encodeUtf8Direct(in, out); + } else { + encodeUtf8Default(in, out); + } + } + + /** Encodes the input character sequence to a direct {@link ByteBuffer} instance. */ + abstract void encodeUtf8Direct(CharSequence in, ByteBuffer out); + + /** + * Encodes the input character sequence to a {@link ByteBuffer} instance using the {@link + * ByteBuffer} API, rather than potentially faster approaches. + */ + final void encodeUtf8Default(CharSequence in, ByteBuffer out) { + final int inLength = in.length(); + int outIx = out.position(); + int inIx = 0; + + // Since ByteBuffer.putXXX() already checks boundaries for us, no need to explicitly check + // access. Assume the buffer is big enough and let it handle the out of bounds exception + // if it occurs. + try { + // Designed to take advantage of + // https://wiki.openjdk.java.net/display/HotSpotInternals/RangeCheckElimination + for (char c; inIx < inLength && (c = in.charAt(inIx)) < 0x80; ++inIx) { + out.put(outIx + inIx, (byte) c); + } + if (inIx == inLength) { + // Successfully encoded the entire string. + out.position(outIx + inIx); + return; + } + + outIx += inIx; + for (char c; inIx < inLength; ++inIx, ++outIx) { + c = in.charAt(inIx); + if (c < 0x80) { + // One byte (0xxx xxxx) + out.put(outIx, (byte) c); + } else if (c < 0x800) { + // Two bytes (110x xxxx 10xx xxxx) + + // Benchmarks show put performs better than putShort here (for HotSpot). + out.put(outIx++, (byte) (0xC0 | (c >>> 6))); + out.put(outIx, (byte) (0x80 | (0x3F & c))); + } else if (c < MIN_SURROGATE || MAX_SURROGATE < c) { + // Three bytes (1110 xxxx 10xx xxxx 10xx xxxx) + // Maximum single-char code point is 0xFFFF, 16 bits. + + // Benchmarks show put performs better than putShort here (for HotSpot). + out.put(outIx++, (byte) (0xE0 | (c >>> 12))); + out.put(outIx++, (byte) (0x80 | (0x3F & (c >>> 6)))); + out.put(outIx, (byte) (0x80 | (0x3F & c))); + } else { + // Four bytes (1111 xxxx 10xx xxxx 10xx xxxx 10xx xxxx) + + // Minimum code point represented by a surrogate pair is 0x10000, 17 bits, four UTF-8 + // bytes + final char low; + if (inIx + 1 == inLength || !isSurrogatePair(c, (low = in.charAt(++inIx)))) { + throw new UnpairedSurrogateException(inIx, inLength); + } + // TODO(nathanmittler): Consider using putInt() to improve performance. + int codePoint = toCodePoint(c, low); + out.put(outIx++, (byte) ((0xF << 4) | (codePoint >>> 18))); + out.put(outIx++, (byte) (0x80 | (0x3F & (codePoint >>> 12)))); + out.put(outIx++, (byte) (0x80 | (0x3F & (codePoint >>> 6)))); + out.put(outIx, (byte) (0x80 | (0x3F & codePoint))); + } + } + + // Successfully encoded the entire string. + out.position(outIx); + } catch (IndexOutOfBoundsException e) { + // TODO(nathanmittler): Consider making the API throw IndexOutOfBoundsException instead. + + // If we failed in the outer ASCII loop, outIx will not have been updated. In this case, + // use inIx to determine the bad write index. + int badWriteIndex = out.position() + Math.max(inIx, outIx - out.position() + 1); + throw new ArrayIndexOutOfBoundsException( + "Failed writing " + in.charAt(inIx) + " at index " + badWriteIndex); + } + } + } + + /** {@link Processor} implementation that does not use any {@code sun.misc.Unsafe} methods. */ + static final class SafeProcessor extends Processor { + @Override + int partialIsValidUtf8(int state, byte[] bytes, int index, int limit) { + if (state != COMPLETE) { + // The previous decoding operation was incomplete (or malformed). + // We look for a well-formed sequence consisting of bytes from + // the previous decoding operation (stored in state) together + // with bytes from the array slice. + // + // We expect such "straddler characters" to be rare. + + if (index >= limit) { // No bytes? No progress. + return state; + } + int byte1 = (byte) state; + // byte1 is never ASCII. + if (byte1 < (byte) 0xE0) { + // two-byte form + + // Simultaneously checks for illegal trailing-byte in + // leading position and overlong 2-byte form. + if (byte1 < (byte) 0xC2 + // byte2 trailing-byte test + || bytes[index++] > (byte) 0xBF) { + return MALFORMED; + } + } else if (byte1 < (byte) 0xF0) { + // three-byte form + + // Get byte2 from saved state or array + int byte2 = (byte) ~(state >> 8); + if (byte2 == 0) { + byte2 = bytes[index++]; + if (index >= limit) { + return incompleteStateFor(byte1, byte2); + } + } + if (byte2 > (byte) 0xBF + // overlong? 5 most significant bits must not all be zero + || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) + // illegal surrogate codepoint? + || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) + // byte3 trailing-byte test + || bytes[index++] > (byte) 0xBF) { + return MALFORMED; + } + } else { + // four-byte form + + // Get byte2 and byte3 from saved state or array + int byte2 = (byte) ~(state >> 8); + int byte3 = 0; + if (byte2 == 0) { + byte2 = bytes[index++]; + if (index >= limit) { + return incompleteStateFor(byte1, byte2); + } + } else { + byte3 = (byte) (state >> 16); + } + if (byte3 == 0) { + byte3 = bytes[index++]; + if (index >= limit) { + return incompleteStateFor(byte1, byte2, byte3); + } + } + + // If we were called with state == MALFORMED, then byte1 is 0xFF, + // which never occurs in well-formed UTF-8, and so we will return + // MALFORMED again below. + + if (byte2 > (byte) 0xBF + // Check that 1 <= plane <= 16. Tricky optimized form of: + // if (byte1 > (byte) 0xF4 || + // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || + // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) + || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 + // byte3 trailing-byte test + || byte3 > (byte) 0xBF + // byte4 trailing-byte test + || bytes[index++] > (byte) 0xBF) { + return MALFORMED; + } + } + } + + return partialIsValidUtf8(bytes, index, limit); + } + + @Override + int partialIsValidUtf8Direct(int state, ByteBuffer buffer, int index, int limit) { + // For safe processing, we have to use the ByteBuffer API. + return partialIsValidUtf8Default(state, buffer, index, limit); + } + + @Override + String decodeUtf8(byte[] bytes, int index, int size) throws InvalidProtocolBufferException { + // Bitwise OR combines the sign bits so any negative value fails the check. + if ((index | size | bytes.length - index - size) < 0) { + throw new ArrayIndexOutOfBoundsException( + String.format("buffer length=%d, index=%d, size=%d", bytes.length, index, size)); + } + + int offset = index; + final int limit = offset + size; + + // The longest possible resulting String is the same as the number of input bytes, when it is + // all ASCII. For other cases, this over-allocates and we will truncate in the end. + char[] resultArr = new char[size]; + int resultPos = 0; + + // Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this). + // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). + while (offset < limit) { + byte b = bytes[offset]; + if (!DecodeUtil.isOneByte(b)) { + break; + } + offset++; + DecodeUtil.handleOneByte(b, resultArr, resultPos++); + } + + while (offset < limit) { + byte byte1 = bytes[offset++]; + if (DecodeUtil.isOneByte(byte1)) { + DecodeUtil.handleOneByte(byte1, resultArr, resultPos++); + // It's common for there to be multiple ASCII characters in a run mixed in, so add an + // extra optimized loop to take care of these runs. + while (offset < limit) { + byte b = bytes[offset]; + if (!DecodeUtil.isOneByte(b)) { + break; + } + offset++; + DecodeUtil.handleOneByte(b, resultArr, resultPos++); + } + } else if (DecodeUtil.isTwoBytes(byte1)) { + if (offset >= limit) { + throw InvalidProtocolBufferException.invalidUtf8(); + } + DecodeUtil.handleTwoBytes(byte1, /* byte2 */ bytes[offset++], resultArr, resultPos++); + } else if (DecodeUtil.isThreeBytes(byte1)) { + if (offset >= limit - 1) { + throw InvalidProtocolBufferException.invalidUtf8(); + } + DecodeUtil.handleThreeBytes( + byte1, + /* byte2 */ bytes[offset++], + /* byte3 */ bytes[offset++], + resultArr, + resultPos++); + } else { + if (offset >= limit - 2) { + throw InvalidProtocolBufferException.invalidUtf8(); + } + DecodeUtil.handleFourBytes( + byte1, + /* byte2 */ bytes[offset++], + /* byte3 */ bytes[offset++], + /* byte4 */ bytes[offset++], + resultArr, + resultPos++); + // 4-byte case requires two chars. + resultPos++; + } + } + + return new String(resultArr, 0, resultPos); + } + + @Override + String decodeUtf8Direct(ByteBuffer buffer, int index, int size) + throws InvalidProtocolBufferException { + // For safe processing, we have to use the ByteBufferAPI. + return decodeUtf8Default(buffer, index, size); + } + + @Override + int encodeUtf8(CharSequence in, byte[] out, int offset, int length) { + int utf16Length = in.length(); + int j = offset; + int i = 0; + int limit = offset + length; + // Designed to take advantage of + // https://wiki.openjdk.java.net/display/HotSpotInternals/RangeCheckElimination + for (char c; i < utf16Length && i + j < limit && (c = in.charAt(i)) < 0x80; i++) { + out[j + i] = (byte) c; + } + if (i == utf16Length) { + return j + utf16Length; + } + j += i; + for (char c; i < utf16Length; i++) { + c = in.charAt(i); + if (c < 0x80 && j < limit) { + out[j++] = (byte) c; + } else if (c < 0x800 && j <= limit - 2) { // 11 bits, two UTF-8 bytes + out[j++] = (byte) ((0xF << 6) | (c >>> 6)); + out[j++] = (byte) (0x80 | (0x3F & c)); + } else if ((c < Character.MIN_SURROGATE || Character.MAX_SURROGATE < c) && j <= limit - 3) { + // Maximum single-char code point is 0xFFFF, 16 bits, three UTF-8 bytes + out[j++] = (byte) ((0xF << 5) | (c >>> 12)); + out[j++] = (byte) (0x80 | (0x3F & (c >>> 6))); + out[j++] = (byte) (0x80 | (0x3F & c)); + } else if (j <= limit - 4) { + // Minimum code point represented by a surrogate pair is 0x10000, 17 bits, + // four UTF-8 bytes + final char low; + if (i + 1 == in.length() || !Character.isSurrogatePair(c, (low = in.charAt(++i)))) { + throw new UnpairedSurrogateException((i - 1), utf16Length); + } + int codePoint = Character.toCodePoint(c, low); + out[j++] = (byte) ((0xF << 4) | (codePoint >>> 18)); + out[j++] = (byte) (0x80 | (0x3F & (codePoint >>> 12))); + out[j++] = (byte) (0x80 | (0x3F & (codePoint >>> 6))); + out[j++] = (byte) (0x80 | (0x3F & codePoint)); + } else { + // If we are surrogates and we're not a surrogate pair, always throw an + // UnpairedSurrogateException instead of an ArrayOutOfBoundsException. + if ((Character.MIN_SURROGATE <= c && c <= Character.MAX_SURROGATE) + && (i + 1 == in.length() || !Character.isSurrogatePair(c, in.charAt(i + 1)))) { + throw new UnpairedSurrogateException(i, utf16Length); + } + throw new ArrayIndexOutOfBoundsException("Failed writing " + c + " at index " + j); + } + } + return j; + } + + @Override + void encodeUtf8Direct(CharSequence in, ByteBuffer out) { + // For safe processing, we have to use the ByteBuffer API. + encodeUtf8Default(in, out); + } + + private static int partialIsValidUtf8(byte[] bytes, int index, int limit) { + // Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this). + // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). + while (index < limit && bytes[index] >= 0) { + index++; + } + + return (index >= limit) ? COMPLETE : partialIsValidUtf8NonAscii(bytes, index, limit); + } + + private static int partialIsValidUtf8NonAscii(byte[] bytes, int index, int limit) { + for (; ; ) { + int byte1; + int byte2; + + // Optimize for interior runs of ASCII bytes. + do { + if (index >= limit) { + return COMPLETE; + } + } while ((byte1 = bytes[index++]) >= 0); + + if (byte1 < (byte) 0xE0) { + // two-byte form + + if (index >= limit) { + // Incomplete sequence + return byte1; + } + + // Simultaneously checks for illegal trailing-byte in + // leading position and overlong 2-byte form. + if (byte1 < (byte) 0xC2 || bytes[index++] > (byte) 0xBF) { + return MALFORMED; + } + } else if (byte1 < (byte) 0xF0) { + // three-byte form + + if (index >= limit - 1) { // incomplete sequence + return incompleteStateFor(bytes, index, limit); + } + if ((byte2 = bytes[index++]) > (byte) 0xBF + // overlong? 5 most significant bits must not all be zero + || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) + // check for illegal surrogate codepoints + || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) + // byte3 trailing-byte test + || bytes[index++] > (byte) 0xBF) { + return MALFORMED; + } + } else { + // four-byte form + + if (index >= limit - 2) { // incomplete sequence + return incompleteStateFor(bytes, index, limit); + } + if ((byte2 = bytes[index++]) > (byte) 0xBF + // Check that 1 <= plane <= 16. Tricky optimized form of: + // if (byte1 > (byte) 0xF4 || + // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || + // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) + || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 + // byte3 trailing-byte test + || bytes[index++] > (byte) 0xBF + // byte4 trailing-byte test + || bytes[index++] > (byte) 0xBF) { + return MALFORMED; + } + } + } + } + } + + /** {@link Processor} that uses {@code sun.misc.Unsafe} where possible to improve performance. */ + static final class UnsafeProcessor extends Processor { + /** Indicates whether or not all required unsafe operations are supported on this platform. */ + static boolean isAvailable() { + return hasUnsafeArrayOperations() && hasUnsafeByteBufferOperations(); + } + + @Override + int partialIsValidUtf8(int state, byte[] bytes, final int index, final int limit) { + // Bitwise OR combines the sign bits so any negative value fails the check. + if ((index | limit | bytes.length - limit) < 0) { + throw new ArrayIndexOutOfBoundsException( + String.format("Array length=%d, index=%d, limit=%d", bytes.length, index, limit)); + } + long offset = index; + final long offsetLimit = limit; + if (state != COMPLETE) { + // The previous decoding operation was incomplete (or malformed). + // We look for a well-formed sequence consisting of bytes from + // the previous decoding operation (stored in state) together + // with bytes from the array slice. + // + // We expect such "straddler characters" to be rare. + + if (offset >= offsetLimit) { // No bytes? No progress. + return state; + } + int byte1 = (byte) state; + // byte1 is never ASCII. + if (byte1 < (byte) 0xE0) { + // two-byte form + + // Simultaneously checks for illegal trailing-byte in + // leading position and overlong 2-byte form. + if (byte1 < (byte) 0xC2 + // byte2 trailing-byte test + || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF) { + return MALFORMED; + } + } else if (byte1 < (byte) 0xF0) { + // three-byte form + + // Get byte2 from saved state or array + int byte2 = (byte) ~(state >> 8); + if (byte2 == 0) { + byte2 = UnsafeUtil.getByte(bytes, offset++); + if (offset >= offsetLimit) { + return incompleteStateFor(byte1, byte2); + } + } + if (byte2 > (byte) 0xBF + // overlong? 5 most significant bits must not all be zero + || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) + // illegal surrogate codepoint? + || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) + // byte3 trailing-byte test + || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF) { + return MALFORMED; + } + } else { + // four-byte form + + // Get byte2 and byte3 from saved state or array + int byte2 = (byte) ~(state >> 8); + int byte3 = 0; + if (byte2 == 0) { + byte2 = UnsafeUtil.getByte(bytes, offset++); + if (offset >= offsetLimit) { + return incompleteStateFor(byte1, byte2); + } + } else { + byte3 = (byte) (state >> 16); + } + if (byte3 == 0) { + byte3 = UnsafeUtil.getByte(bytes, offset++); + if (offset >= offsetLimit) { + return incompleteStateFor(byte1, byte2, byte3); + } + } + + // If we were called with state == MALFORMED, then byte1 is 0xFF, + // which never occurs in well-formed UTF-8, and so we will return + // MALFORMED again below. + + if (byte2 > (byte) 0xBF + // Check that 1 <= plane <= 16. Tricky optimized form of: + // if (byte1 > (byte) 0xF4 || + // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || + // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) + || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 + // byte3 trailing-byte test + || byte3 > (byte) 0xBF + // byte4 trailing-byte test + || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF) { + return MALFORMED; + } + } + } + + return partialIsValidUtf8(bytes, offset, (int) (offsetLimit - offset)); + } + + @Override + int partialIsValidUtf8Direct( + final int state, ByteBuffer buffer, final int index, final int limit) { + // Bitwise OR combines the sign bits so any negative value fails the check. + if ((index | limit | buffer.limit() - limit) < 0) { + throw new ArrayIndexOutOfBoundsException( + String.format("buffer limit=%d, index=%d, limit=%d", buffer.limit(), index, limit)); + } + long address = addressOffset(buffer) + index; + final long addressLimit = address + (limit - index); + if (state != COMPLETE) { + // The previous decoding operation was incomplete (or malformed). + // We look for a well-formed sequence consisting of bytes from + // the previous decoding operation (stored in state) together + // with bytes from the array slice. + // + // We expect such "straddler characters" to be rare. + + if (address >= addressLimit) { // No bytes? No progress. + return state; + } + + final int byte1 = (byte) state; + // byte1 is never ASCII. + if (byte1 < (byte) 0xE0) { + // two-byte form + + // Simultaneously checks for illegal trailing-byte in + // leading position and overlong 2-byte form. + if (byte1 < (byte) 0xC2 + // byte2 trailing-byte test + || UnsafeUtil.getByte(address++) > (byte) 0xBF) { + return MALFORMED; + } + } else if (byte1 < (byte) 0xF0) { + // three-byte form + + // Get byte2 from saved state or array + int byte2 = (byte) ~(state >> 8); + if (byte2 == 0) { + byte2 = UnsafeUtil.getByte(address++); + if (address >= addressLimit) { + return incompleteStateFor(byte1, byte2); + } + } + if (byte2 > (byte) 0xBF + // overlong? 5 most significant bits must not all be zero + || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) + // illegal surrogate codepoint? + || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) + // byte3 trailing-byte test + || UnsafeUtil.getByte(address++) > (byte) 0xBF) { + return MALFORMED; + } + } else { + // four-byte form + + // Get byte2 and byte3 from saved state or array + int byte2 = (byte) ~(state >> 8); + int byte3 = 0; + if (byte2 == 0) { + byte2 = UnsafeUtil.getByte(address++); + if (address >= addressLimit) { + return incompleteStateFor(byte1, byte2); + } + } else { + byte3 = (byte) (state >> 16); + } + if (byte3 == 0) { + byte3 = UnsafeUtil.getByte(address++); + if (address >= addressLimit) { + return incompleteStateFor(byte1, byte2, byte3); + } + } + + // If we were called with state == MALFORMED, then byte1 is 0xFF, + // which never occurs in well-formed UTF-8, and so we will return + // MALFORMED again below. + + if (byte2 > (byte) 0xBF + // Check that 1 <= plane <= 16. Tricky optimized form of: + // if (byte1 > (byte) 0xF4 || + // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || + // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) + || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 + // byte3 trailing-byte test + || byte3 > (byte) 0xBF + // byte4 trailing-byte test + || UnsafeUtil.getByte(address++) > (byte) 0xBF) { + return MALFORMED; + } + } + } + + return partialIsValidUtf8(address, (int) (addressLimit - address)); + } + + @Override + String decodeUtf8(byte[] bytes, int index, int size) throws InvalidProtocolBufferException { + if ((index | size | bytes.length - index - size) < 0) { + throw new ArrayIndexOutOfBoundsException( + String.format("buffer length=%d, index=%d, size=%d", bytes.length, index, size)); + } + + int offset = index + unsafeEstimateConsecutiveAscii(bytes, index, size); + final int limit = index + size; + + // get an "exact" consecutive ASCII + while (offset < limit) { + byte b = UnsafeUtil.getByte(bytes, offset); + if (b < 0) { + break; + } + offset++; + } + + if (offset == limit) { + // The entire byte sequence is ASCII. Don't bother copying to a char[], JVMs using + // compact strings will just turn it back into the same byte[]. + return new String(bytes, index, size, Internal.US_ASCII); + } + + // It's not all ASCII, at this point. This may over-allocate, but we will truncate in the + // end. + char[] resultArr = new char[size]; + int resultPos = 0; + + // Copy over the initial run of ASCII. + for (int i = index; i < offset; i++) { + DecodeUtil.handleOneByte(UnsafeUtil.getByte(bytes, i), resultArr, resultPos++); + } + + while (offset < limit) { + byte byte1 = UnsafeUtil.getByte(bytes, offset++); + if (DecodeUtil.isOneByte(byte1)) { + DecodeUtil.handleOneByte(byte1, resultArr, resultPos++); + + // It's common for there to be multiple ASCII characters in a run mixed in, so add an + // extra optimized loop to take care of these runs. + while (offset < limit) { + byte b = UnsafeUtil.getByte(bytes, offset); + if (!DecodeUtil.isOneByte(b)) { + break; + } + offset++; + DecodeUtil.handleOneByte(b, resultArr, resultPos++); + } + } else if (DecodeUtil.isTwoBytes(byte1)) { + if (offset >= limit) { + throw InvalidProtocolBufferException.invalidUtf8(); + } + DecodeUtil.handleTwoBytes( + byte1, /* byte2 */ UnsafeUtil.getByte(bytes, offset++), resultArr, resultPos++); + } else if (DecodeUtil.isThreeBytes(byte1)) { + if (offset >= limit - 1) { + throw InvalidProtocolBufferException.invalidUtf8(); + } + DecodeUtil.handleThreeBytes( + byte1, + /* byte2 */ UnsafeUtil.getByte(bytes, offset++), + /* byte3 */ UnsafeUtil.getByte(bytes, offset++), + resultArr, + resultPos++); + } else { + if (offset >= limit - 2) { + throw InvalidProtocolBufferException.invalidUtf8(); + } + DecodeUtil.handleFourBytes( + byte1, + /* byte2 */ UnsafeUtil.getByte(bytes, offset++), + /* byte3 */ UnsafeUtil.getByte(bytes, offset++), + /* byte4 */ UnsafeUtil.getByte(bytes, offset++), + resultArr, + resultPos++); + // 4-byte case requires two chars. + resultPos++; + } + } + + return new String(resultArr, 0, resultPos); + } + + @Override + String decodeUtf8Direct(ByteBuffer buffer, int index, int size) + throws InvalidProtocolBufferException { + // Bitwise OR combines the sign bits so any negative value fails the check. + if ((index | size | buffer.limit() - index - size) < 0) { + throw new ArrayIndexOutOfBoundsException( + String.format("buffer limit=%d, index=%d, limit=%d", buffer.limit(), index, size)); + } + long address = UnsafeUtil.addressOffset(buffer) + index; + final long addressLimit = address + size; + + // The longest possible resulting String is the same as the number of input bytes, when it is + // all ASCII. For other cases, this over-allocates and we will truncate in the end. + char[] resultArr = new char[size]; + int resultPos = 0; + + // Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this). + // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). + while (address < addressLimit) { + byte b = UnsafeUtil.getByte(address); + if (!DecodeUtil.isOneByte(b)) { + break; + } + address++; + DecodeUtil.handleOneByte(b, resultArr, resultPos++); + } + + while (address < addressLimit) { + byte byte1 = UnsafeUtil.getByte(address++); + if (DecodeUtil.isOneByte(byte1)) { + DecodeUtil.handleOneByte(byte1, resultArr, resultPos++); + // It's common for there to be multiple ASCII characters in a run mixed in, so add an + // extra optimized loop to take care of these runs. + while (address < addressLimit) { + byte b = UnsafeUtil.getByte(address); + if (!DecodeUtil.isOneByte(b)) { + break; + } + address++; + DecodeUtil.handleOneByte(b, resultArr, resultPos++); + } + } else if (DecodeUtil.isTwoBytes(byte1)) { + if (address >= addressLimit) { + throw InvalidProtocolBufferException.invalidUtf8(); + } + DecodeUtil.handleTwoBytes( + byte1, /* byte2 */ UnsafeUtil.getByte(address++), resultArr, resultPos++); + } else if (DecodeUtil.isThreeBytes(byte1)) { + if (address >= addressLimit - 1) { + throw InvalidProtocolBufferException.invalidUtf8(); + } + DecodeUtil.handleThreeBytes( + byte1, + /* byte2 */ UnsafeUtil.getByte(address++), + /* byte3 */ UnsafeUtil.getByte(address++), + resultArr, + resultPos++); + } else { + if (address >= addressLimit - 2) { + throw InvalidProtocolBufferException.invalidUtf8(); + } + DecodeUtil.handleFourBytes( + byte1, + /* byte2 */ UnsafeUtil.getByte(address++), + /* byte3 */ UnsafeUtil.getByte(address++), + /* byte4 */ UnsafeUtil.getByte(address++), + resultArr, + resultPos++); + // 4-byte case requires two chars. + resultPos++; + } + } + + return new String(resultArr, 0, resultPos); + } + + @Override + int encodeUtf8(final CharSequence in, final byte[] out, final int offset, final int length) { + long outIx = offset; + final long outLimit = outIx + length; + final int inLimit = in.length(); + if (inLimit > length || out.length - length < offset) { + // Not even enough room for an ASCII-encoded string. + throw new ArrayIndexOutOfBoundsException( + "Failed writing " + in.charAt(inLimit - 1) + " at index " + (offset + length)); + } + + // Designed to take advantage of + // https://wiki.openjdk.java.net/display/HotSpotInternals/RangeCheckElimination + int inIx = 0; + for (char c; inIx < inLimit && (c = in.charAt(inIx)) < 0x80; ++inIx) { + UnsafeUtil.putByte(out, outIx++, (byte) c); + } + if (inIx == inLimit) { + // We're done, it was ASCII encoded. + return (int) outIx; + } + + for (char c; inIx < inLimit; ++inIx) { + c = in.charAt(inIx); + if (c < 0x80 && outIx < outLimit) { + UnsafeUtil.putByte(out, outIx++, (byte) c); + } else if (c < 0x800 && outIx <= outLimit - 2L) { // 11 bits, two UTF-8 bytes + UnsafeUtil.putByte(out, outIx++, (byte) ((0xF << 6) | (c >>> 6))); + UnsafeUtil.putByte(out, outIx++, (byte) (0x80 | (0x3F & c))); + } else if ((c < MIN_SURROGATE || MAX_SURROGATE < c) && outIx <= outLimit - 3L) { + // Maximum single-char code point is 0xFFFF, 16 bits, three UTF-8 bytes + UnsafeUtil.putByte(out, outIx++, (byte) ((0xF << 5) | (c >>> 12))); + UnsafeUtil.putByte(out, outIx++, (byte) (0x80 | (0x3F & (c >>> 6)))); + UnsafeUtil.putByte(out, outIx++, (byte) (0x80 | (0x3F & c))); + } else if (outIx <= outLimit - 4L) { + // Minimum code point represented by a surrogate pair is 0x10000, 17 bits, four UTF-8 + // bytes + final char low; + if (inIx + 1 == inLimit || !isSurrogatePair(c, (low = in.charAt(++inIx)))) { + throw new UnpairedSurrogateException((inIx - 1), inLimit); + } + int codePoint = toCodePoint(c, low); + UnsafeUtil.putByte(out, outIx++, (byte) ((0xF << 4) | (codePoint >>> 18))); + UnsafeUtil.putByte(out, outIx++, (byte) (0x80 | (0x3F & (codePoint >>> 12)))); + UnsafeUtil.putByte(out, outIx++, (byte) (0x80 | (0x3F & (codePoint >>> 6)))); + UnsafeUtil.putByte(out, outIx++, (byte) (0x80 | (0x3F & codePoint))); + } else { + if ((MIN_SURROGATE <= c && c <= MAX_SURROGATE) + && (inIx + 1 == inLimit || !isSurrogatePair(c, in.charAt(inIx + 1)))) { + // We are surrogates and we're not a surrogate pair. + throw new UnpairedSurrogateException(inIx, inLimit); + } + // Not enough space in the output buffer. + throw new ArrayIndexOutOfBoundsException("Failed writing " + c + " at index " + outIx); + } + } + + // All bytes have been encoded. + return (int) outIx; + } + + @Override + void encodeUtf8Direct(CharSequence in, ByteBuffer out) { + final long address = addressOffset(out); + long outIx = address + out.position(); + final long outLimit = address + out.limit(); + final int inLimit = in.length(); + if (inLimit > outLimit - outIx) { + // Not even enough room for an ASCII-encoded string. + throw new ArrayIndexOutOfBoundsException( + "Failed writing " + in.charAt(inLimit - 1) + " at index " + out.limit()); + } + + // Designed to take advantage of + // https://wiki.openjdk.java.net/display/HotSpotInternals/RangeCheckElimination + int inIx = 0; + for (char c; inIx < inLimit && (c = in.charAt(inIx)) < 0x80; ++inIx) { + UnsafeUtil.putByte(outIx++, (byte) c); + } + if (inIx == inLimit) { + // We're done, it was ASCII encoded. + out.position((int) (outIx - address)); + return; + } + + for (char c; inIx < inLimit; ++inIx) { + c = in.charAt(inIx); + if (c < 0x80 && outIx < outLimit) { + UnsafeUtil.putByte(outIx++, (byte) c); + } else if (c < 0x800 && outIx <= outLimit - 2L) { // 11 bits, two UTF-8 bytes + UnsafeUtil.putByte(outIx++, (byte) ((0xF << 6) | (c >>> 6))); + UnsafeUtil.putByte(outIx++, (byte) (0x80 | (0x3F & c))); + } else if ((c < MIN_SURROGATE || MAX_SURROGATE < c) && outIx <= outLimit - 3L) { + // Maximum single-char code point is 0xFFFF, 16 bits, three UTF-8 bytes + UnsafeUtil.putByte(outIx++, (byte) ((0xF << 5) | (c >>> 12))); + UnsafeUtil.putByte(outIx++, (byte) (0x80 | (0x3F & (c >>> 6)))); + UnsafeUtil.putByte(outIx++, (byte) (0x80 | (0x3F & c))); + } else if (outIx <= outLimit - 4L) { + // Minimum code point represented by a surrogate pair is 0x10000, 17 bits, four UTF-8 + // bytes + final char low; + if (inIx + 1 == inLimit || !isSurrogatePair(c, (low = in.charAt(++inIx)))) { + throw new UnpairedSurrogateException((inIx - 1), inLimit); + } + int codePoint = toCodePoint(c, low); + UnsafeUtil.putByte(outIx++, (byte) ((0xF << 4) | (codePoint >>> 18))); + UnsafeUtil.putByte(outIx++, (byte) (0x80 | (0x3F & (codePoint >>> 12)))); + UnsafeUtil.putByte(outIx++, (byte) (0x80 | (0x3F & (codePoint >>> 6)))); + UnsafeUtil.putByte(outIx++, (byte) (0x80 | (0x3F & codePoint))); + } else { + if ((MIN_SURROGATE <= c && c <= MAX_SURROGATE) + && (inIx + 1 == inLimit || !isSurrogatePair(c, in.charAt(inIx + 1)))) { + // We are surrogates and we're not a surrogate pair. + throw new UnpairedSurrogateException(inIx, inLimit); + } + // Not enough space in the output buffer. + throw new ArrayIndexOutOfBoundsException("Failed writing " + c + " at index " + outIx); + } + } + + // All bytes have been encoded. + out.position((int) (outIx - address)); + } + + /** + * Counts (approximately) the number of consecutive ASCII characters starting from the given + * position, using the most efficient method available to the platform. + * + * @param bytes the array containing the character sequence + * @param offset the offset position of the index (same as index + arrayBaseOffset) + * @param maxChars the maximum number of characters to count + * @return the number of ASCII characters found. The stopping position will be at or before the + * first non-ASCII byte. + */ + private static int unsafeEstimateConsecutiveAscii( + byte[] bytes, long offset, final int maxChars) { + if (maxChars < UNSAFE_COUNT_ASCII_THRESHOLD) { + // Don't bother with small strings. + return 0; + } + + int i; + for (i = 0; i + 8 <= maxChars; i += 8) { + if ((UnsafeUtil.getLong(bytes, UnsafeUtil.BYTE_ARRAY_BASE_OFFSET + offset) + & ASCII_MASK_LONG) + != 0L) { + break; + } + offset += 8; + } + + for (; i < maxChars; i++) { + if (UnsafeUtil.getByte(bytes, offset++) < 0) { + return i; + } + } + return maxChars; + } + + /** + * Same as {@link Utf8#estimateConsecutiveAscii(ByteBuffer, int, int)} except that it uses the + * most efficient method available to the platform. + */ + private static int unsafeEstimateConsecutiveAscii(long address, final int maxChars) { + int remaining = maxChars; + if (remaining < UNSAFE_COUNT_ASCII_THRESHOLD) { + // Don't bother with small strings. + return 0; + } + + // Read bytes until 8-byte aligned so that we can read longs in the loop below. + // This is equivalent to (8-address) mod 8, the number of bytes we need to read before we're + // 8-byte aligned. + final int unaligned = (int) (-address & 7); + for (int j = unaligned; j > 0; j--) { + if (UnsafeUtil.getByte(address++) < 0) { + return unaligned - j; + } + } + + // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). + // To speed things up further, we're reading longs instead of bytes so we use a mask to + // determine if any byte in the current long is non-ASCII. + remaining -= unaligned; + for (; + remaining >= 8 && (UnsafeUtil.getLong(address) & ASCII_MASK_LONG) == 0; + address += 8, remaining -= 8) {} + return maxChars - remaining; + } + + private static int partialIsValidUtf8(final byte[] bytes, long offset, int remaining) { + // Skip past ASCII characters as quickly as possible. + final int skipped = unsafeEstimateConsecutiveAscii(bytes, offset, remaining); + remaining -= skipped; + offset += skipped; + + for (; ; ) { + // Optimize for interior runs of ASCII bytes. + // TODO(nathanmittler): Consider checking 8 bytes at a time after some threshold? + // Maybe after seeing a few in a row that are ASCII, go back to fast mode? + int byte1 = 0; + for (; remaining > 0 && (byte1 = UnsafeUtil.getByte(bytes, offset++)) >= 0; --remaining) {} + if (remaining == 0) { + return COMPLETE; + } + remaining--; + + // If we're here byte1 is not ASCII. Only need to handle 2-4 byte forms. + if (byte1 < (byte) 0xE0) { + // Two-byte form (110xxxxx 10xxxxxx) + if (remaining == 0) { + // Incomplete sequence + return byte1; + } + remaining--; + + // Simultaneously checks for illegal trailing-byte in + // leading position and overlong 2-byte form. + if (byte1 < (byte) 0xC2 || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF) { + return MALFORMED; + } + } else if (byte1 < (byte) 0xF0) { + // Three-byte form (1110xxxx 10xxxxxx 10xxxxxx) + if (remaining < 2) { + // Incomplete sequence + return unsafeIncompleteStateFor(bytes, byte1, offset, remaining); + } + remaining -= 2; + + final int byte2; + if ((byte2 = UnsafeUtil.getByte(bytes, offset++)) > (byte) 0xBF + // overlong? 5 most significant bits must not all be zero + || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) + // check for illegal surrogate codepoints + || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) + // byte3 trailing-byte test + || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF) { + return MALFORMED; + } + } else { + // Four-byte form (1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx) + if (remaining < 3) { + // Incomplete sequence + return unsafeIncompleteStateFor(bytes, byte1, offset, remaining); + } + remaining -= 3; + + final int byte2; + if ((byte2 = UnsafeUtil.getByte(bytes, offset++)) > (byte) 0xBF + // Check that 1 <= plane <= 16. Tricky optimized form of: + // if (byte1 > (byte) 0xF4 || + // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || + // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) + || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 + // byte3 trailing-byte test + || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF + // byte4 trailing-byte test + || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF) { + return MALFORMED; + } + } + } + } + + private static int partialIsValidUtf8(long address, int remaining) { + // Skip past ASCII characters as quickly as possible. + final int skipped = unsafeEstimateConsecutiveAscii(address, remaining); + address += skipped; + remaining -= skipped; + + for (; ; ) { + // Optimize for interior runs of ASCII bytes. + // TODO(nathanmittler): Consider checking 8 bytes at a time after some threshold? + // Maybe after seeing a few in a row that are ASCII, go back to fast mode? + int byte1 = 0; + for (; remaining > 0 && (byte1 = UnsafeUtil.getByte(address++)) >= 0; --remaining) {} + if (remaining == 0) { + return COMPLETE; + } + remaining--; + + if (byte1 < (byte) 0xE0) { + // Two-byte form + + if (remaining == 0) { + // Incomplete sequence + return byte1; + } + remaining--; + + // Simultaneously checks for illegal trailing-byte in + // leading position and overlong 2-byte form. + if (byte1 < (byte) 0xC2 || UnsafeUtil.getByte(address++) > (byte) 0xBF) { + return MALFORMED; + } + } else if (byte1 < (byte) 0xF0) { + // Three-byte form + + if (remaining < 2) { + // Incomplete sequence + return unsafeIncompleteStateFor(address, byte1, remaining); + } + remaining -= 2; + + final byte byte2 = UnsafeUtil.getByte(address++); + if (byte2 > (byte) 0xBF + // overlong? 5 most significant bits must not all be zero + || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) + // check for illegal surrogate codepoints + || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) + // byte3 trailing-byte test + || UnsafeUtil.getByte(address++) > (byte) 0xBF) { + return MALFORMED; + } + } else { + // Four-byte form + + if (remaining < 3) { + // Incomplete sequence + return unsafeIncompleteStateFor(address, byte1, remaining); + } + remaining -= 3; + + final byte byte2 = UnsafeUtil.getByte(address++); + if (byte2 > (byte) 0xBF + // Check that 1 <= plane <= 16. Tricky optimized form of: + // if (byte1 > (byte) 0xF4 || + // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || + // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) + || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 + // byte3 trailing-byte test + || UnsafeUtil.getByte(address++) > (byte) 0xBF + // byte4 trailing-byte test + || UnsafeUtil.getByte(address++) > (byte) 0xBF) { + return MALFORMED; + } + } + } + } + + private static int unsafeIncompleteStateFor( + byte[] bytes, int byte1, long offset, int remaining) { + switch (remaining) { + case 0: + return incompleteStateFor(byte1); + case 1: + return incompleteStateFor(byte1, UnsafeUtil.getByte(bytes, offset)); + case 2: + return incompleteStateFor( + byte1, UnsafeUtil.getByte(bytes, offset), UnsafeUtil.getByte(bytes, offset + 1)); + default: + throw new AssertionError(); + } + } + + private static int unsafeIncompleteStateFor(long address, final int byte1, int remaining) { + switch (remaining) { + case 0: + return incompleteStateFor(byte1); + case 1: + return incompleteStateFor(byte1, UnsafeUtil.getByte(address)); + case 2: + return incompleteStateFor( + byte1, UnsafeUtil.getByte(address), UnsafeUtil.getByte(address + 1)); + default: + throw new AssertionError(); + } + } + } + + /** + * Utility methods for decoding bytes into {@link String}. Callers are responsible for extracting + * bytes (possibly using Unsafe methods), and checking remaining bytes. All other UTF-8 validity + * checks and codepoint conversion happen in this class. + */ + private static class DecodeUtil { + + /** Returns whether this is a single-byte codepoint (i.e., ASCII) with the form '0XXXXXXX'. */ + private static boolean isOneByte(byte b) { + return b >= 0; + } + + /** Returns whether this is a two-byte codepoint with the form '10XXXXXX'. */ + private static boolean isTwoBytes(byte b) { + return b < (byte) 0xE0; + } + + /** Returns whether this is a three-byte codepoint with the form '110XXXXX'. */ + private static boolean isThreeBytes(byte b) { + return b < (byte) 0xF0; + } + + private static void handleOneByte(byte byte1, char[] resultArr, int resultPos) { + resultArr[resultPos] = (char) byte1; + } + + private static void handleTwoBytes(byte byte1, byte byte2, char[] resultArr, int resultPos) + throws InvalidProtocolBufferException { + // Simultaneously checks for illegal trailing-byte in leading position (<= '11000000') and + // overlong 2-byte, '11000001'. + if (byte1 < (byte) 0xC2 || isNotTrailingByte(byte2)) { + throw InvalidProtocolBufferException.invalidUtf8(); + } + resultArr[resultPos] = (char) (((byte1 & 0x1F) << 6) | trailingByteValue(byte2)); + } + + private static void handleThreeBytes( + byte byte1, byte byte2, byte byte3, char[] resultArr, int resultPos) + throws InvalidProtocolBufferException { + if (isNotTrailingByte(byte2) + // overlong? 5 most significant bits must not all be zero + || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) + // check for illegal surrogate codepoints + || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) + || isNotTrailingByte(byte3)) { + throw InvalidProtocolBufferException.invalidUtf8(); + } + resultArr[resultPos] = + (char) + (((byte1 & 0x0F) << 12) | (trailingByteValue(byte2) << 6) | trailingByteValue(byte3)); + } + + private static void handleFourBytes( + byte byte1, byte byte2, byte byte3, byte byte4, char[] resultArr, int resultPos) + throws InvalidProtocolBufferException { + if (isNotTrailingByte(byte2) + // Check that 1 <= plane <= 16. Tricky optimized form of: + // valid 4-byte leading byte? + // if (byte1 > (byte) 0xF4 || + // overlong? 4 most significant bits must not all be zero + // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || + // codepoint larger than the highest code point (U+10FFFF)? + // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) + || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 + || isNotTrailingByte(byte3) + || isNotTrailingByte(byte4)) { + throw InvalidProtocolBufferException.invalidUtf8(); + } + int codepoint = + ((byte1 & 0x07) << 18) + | (trailingByteValue(byte2) << 12) + | (trailingByteValue(byte3) << 6) + | trailingByteValue(byte4); + resultArr[resultPos] = DecodeUtil.highSurrogate(codepoint); + resultArr[resultPos + 1] = DecodeUtil.lowSurrogate(codepoint); + } + + /** Returns whether the byte is not a valid continuation of the form '10XXXXXX'. */ + private static boolean isNotTrailingByte(byte b) { + return b > (byte) 0xBF; + } + + /** Returns the actual value of the trailing byte (removes the prefix '10') for composition. */ + private static int trailingByteValue(byte b) { + return b & 0x3F; + } + + private static char highSurrogate(int codePoint) { + return (char) + ((MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT >>> 10)) + (codePoint >>> 10)); + } + + private static char lowSurrogate(int codePoint) { + return (char) (MIN_LOW_SURROGATE + (codePoint & 0x3ff)); + } + } + + private Utf8() {} +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/AnyTest.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/AnyTest.java new file mode 100644 index 0000000..ee13ef1 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/AnyTest.java @@ -0,0 +1,136 @@ +// 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. + +package com.google.protobuf; + +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; + +import any_test.AnyTestProto.TestAny; +import protobuf_unittest.UnittestProto.TestAllTypes; +import java.util.Objects; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for Any message. */ +@RunWith(JUnit4.class) +public class AnyTest { + + @Test + public void testAnyGeneratedApi() throws Exception { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + TestUtil.setAllFields(builder); + TestAllTypes message = builder.build(); + + TestAny container = TestAny.newBuilder().setValue(Any.pack(message)).build(); + + assertThat(container.getValue().is(TestAllTypes.class)).isTrue(); + assertThat(container.getValue().is(TestAny.class)).isFalse(); + + TestAllTypes result = container.getValue().unpack(TestAllTypes.class); + TestUtil.assertAllFieldsSet(result); + + + // Unpacking to a wrong type will throw an exception. + try { + container.getValue().unpack(TestAny.class); + assertWithMessage("Exception is expected.").fail(); + } catch (InvalidProtocolBufferException e) { + // expected. + } + + // Test that unpacking throws an exception if parsing fails. + TestAny.Builder containerBuilder = container.toBuilder(); + containerBuilder.getValueBuilder().setValue(ByteString.copyFrom(new byte[] {0x11})); + container = containerBuilder.build(); + try { + container.getValue().unpack(TestAllTypes.class); + assertWithMessage("Exception is expected.").fail(); + } catch (InvalidProtocolBufferException e) { + // expected. + } + } + + @Test + public void testCustomTypeUrls() throws Exception { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + TestUtil.setAllFields(builder); + TestAllTypes message = builder.build(); + + TestAny container = TestAny.newBuilder().setValue(Any.pack(message, "xxx.com")).build(); + + assertThat(container.getValue().getTypeUrl()) + .isEqualTo("xxx.com/" + TestAllTypes.getDescriptor().getFullName()); + + assertThat(container.getValue().is(TestAllTypes.class)).isTrue(); + assertThat(container.getValue().is(TestAny.class)).isFalse(); + + TestAllTypes result = container.getValue().unpack(TestAllTypes.class); + TestUtil.assertAllFieldsSet(result); + + container = TestAny.newBuilder().setValue(Any.pack(message, "yyy.com/")).build(); + + assertThat(container.getValue().getTypeUrl()) + .isEqualTo("yyy.com/" + TestAllTypes.getDescriptor().getFullName()); + + assertThat(container.getValue().is(TestAllTypes.class)).isTrue(); + assertThat(container.getValue().is(TestAny.class)).isFalse(); + + result = container.getValue().unpack(TestAllTypes.class); + TestUtil.assertAllFieldsSet(result); + + container = TestAny.newBuilder().setValue(Any.pack(message, "")).build(); + + assertThat(container.getValue().getTypeUrl()) + .isEqualTo("/" + TestAllTypes.getDescriptor().getFullName()); + + assertThat(container.getValue().is(TestAllTypes.class)).isTrue(); + assertThat(container.getValue().is(TestAny.class)).isFalse(); + + result = container.getValue().unpack(TestAllTypes.class); + TestUtil.assertAllFieldsSet(result); + } + + @Test + public void testCachedUnpackResult() throws Exception { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + TestUtil.setAllFields(builder); + TestAllTypes message = builder.build(); + + TestAny container = TestAny.newBuilder().setValue(Any.pack(message)).build(); + + assertThat(container.getValue().is(TestAllTypes.class)).isTrue(); + + TestAllTypes result1 = container.getValue().unpack(TestAllTypes.class); + TestAllTypes result2 = container.getValue().unpack(TestAllTypes.class); + assertThat(Objects.equals(result1, result2)).isTrue(); + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java new file mode 100644 index 0000000..2050507 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java @@ -0,0 +1,586 @@ +// 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. + +package com.google.protobuf; + +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; +import static java.util.Arrays.asList; + +import com.google.protobuf.Internal.BooleanList; +import java.util.Collections; +import java.util.ConcurrentModificationException; +import java.util.Iterator; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for {@link BooleanArrayList}. */ +@RunWith(JUnit4.class) +public class BooleanArrayListTest { + + private static final BooleanArrayList UNARY_LIST = newImmutableBooleanArrayList(true); + private static final BooleanArrayList TERTIARY_LIST = + newImmutableBooleanArrayList(true, false, true); + + private BooleanArrayList list; + + @Before + public void setUp() throws Exception { + list = new BooleanArrayList(); + } + + @Test + public void testEmptyListReturnsSameInstance() { + assertThat(BooleanArrayList.emptyList()).isSameInstanceAs(BooleanArrayList.emptyList()); + } + + @Test + public void testEmptyListIsImmutable() { + assertImmutable(BooleanArrayList.emptyList()); + } + + @Test + public void testMakeImmutable() { + list.addBoolean(true); + list.addBoolean(false); + list.addBoolean(true); + list.addBoolean(true); + list.makeImmutable(); + assertImmutable(list); + } + + @Test + public void testModificationWithIteration() { + list.addAll(asList(true, false, true, false)); + Iterator iterator = list.iterator(); + assertThat(list).hasSize(4); + assertThat((boolean) list.get(0)).isEqualTo(true); + assertThat((boolean) iterator.next()).isEqualTo(true); + list.set(0, true); + assertThat((boolean) iterator.next()).isEqualTo(false); + + list.remove(0); + try { + iterator.next(); + assertWithMessage("expected exception").fail(); + } catch (ConcurrentModificationException e) { + // expected + } + + iterator = list.iterator(); + list.add(0, false); + try { + iterator.next(); + assertWithMessage("expected exception").fail(); + } catch (ConcurrentModificationException e) { + // expected + } + } + + @Test + public void testGet() { + assertThat((boolean) TERTIARY_LIST.get(0)).isEqualTo(true); + assertThat((boolean) TERTIARY_LIST.get(1)).isEqualTo(false); + assertThat((boolean) TERTIARY_LIST.get(2)).isEqualTo(true); + + try { + TERTIARY_LIST.get(-1); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + TERTIARY_LIST.get(3); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + @Test + public void testGetBoolean() { + assertThat(TERTIARY_LIST.getBoolean(0)).isEqualTo(true); + assertThat(TERTIARY_LIST.getBoolean(1)).isEqualTo(false); + assertThat(TERTIARY_LIST.getBoolean(2)).isEqualTo(true); + + try { + TERTIARY_LIST.get(-1); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + TERTIARY_LIST.get(3); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + @Test + public void testIndexOf_nullElement() { + assertThat(TERTIARY_LIST.indexOf(null)).isEqualTo(-1); + } + + @Test + public void testIndexOf_incompatibleElementType() { + assertThat(TERTIARY_LIST.indexOf(new Object())).isEqualTo(-1); + } + + @Test + public void testIndexOf_notInList() { + assertThat(UNARY_LIST.indexOf(false)).isEqualTo(-1); + } + + @Test + public void testIndexOf_notInListWithDuplicates() { + BooleanArrayList listWithDupes = newImmutableBooleanArrayList(true, true); + assertThat(listWithDupes.indexOf(false)).isEqualTo(-1); + } + + @Test + public void testIndexOf_inList() { + assertThat(TERTIARY_LIST.indexOf(false)).isEqualTo(1); + } + + @Test + public void testIndexOf_inListWithDuplicates_matchAtHead() { + BooleanArrayList listWithDupes = newImmutableBooleanArrayList(true, true, false); + assertThat(listWithDupes.indexOf(true)).isEqualTo(0); + } + + @Test + public void testIndexOf_inListWithDuplicates_matchMidList() { + BooleanArrayList listWithDupes = newImmutableBooleanArrayList(false, true, true, false); + assertThat(listWithDupes.indexOf(true)).isEqualTo(1); + } + + @Test + public void testContains_nullElement() { + assertThat(TERTIARY_LIST).doesNotContain(null); + } + + @Test + public void testContains_incompatibleElementType() { + assertThat(TERTIARY_LIST).doesNotContain(new Object()); + } + + @Test + public void testContains_notInList() { + assertThat(UNARY_LIST).doesNotContain(false); + } + + @Test + public void testContains_notInListWithDuplicates() { + BooleanArrayList listWithDupes = newImmutableBooleanArrayList(true, true); + assertThat(listWithDupes).doesNotContain(false); + } + + @Test + public void testContains_inList() { + assertThat(TERTIARY_LIST).contains(false); + } + + @Test + public void testContains_inListWithDuplicates_matchAtHead() { + BooleanArrayList listWithDupes = newImmutableBooleanArrayList(true, true, false); + assertThat(listWithDupes).contains(true); + } + + @Test + public void testContains_inListWithDuplicates_matchMidList() { + BooleanArrayList listWithDupes = newImmutableBooleanArrayList(false, true, true, false); + assertThat(listWithDupes).contains(true); + } + + @Test + public void testSize() { + assertThat(BooleanArrayList.emptyList()).isEmpty(); + assertThat(UNARY_LIST).hasSize(1); + assertThat(TERTIARY_LIST).hasSize(3); + + list.addBoolean(true); + list.addBoolean(false); + list.addBoolean(false); + list.addBoolean(false); + assertThat(list).hasSize(4); + + list.remove(0); + assertThat(list).hasSize(3); + + list.add(true); + assertThat(list).hasSize(4); + } + + @Test + public void testSet() { + list.addBoolean(false); + list.addBoolean(false); + + assertThat((boolean) list.set(0, true)).isEqualTo(false); + assertThat(list.getBoolean(0)).isEqualTo(true); + + assertThat((boolean) list.set(1, false)).isEqualTo(false); + assertThat(list.getBoolean(1)).isEqualTo(false); + + try { + list.set(-1, false); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + list.set(2, false); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + @Test + public void testSetBoolean() { + list.addBoolean(true); + list.addBoolean(true); + + assertThat(list.setBoolean(0, false)).isEqualTo(true); + assertThat(list.getBoolean(0)).isEqualTo(false); + + assertThat(list.setBoolean(1, false)).isEqualTo(true); + assertThat(list.getBoolean(1)).isEqualTo(false); + + try { + list.setBoolean(-1, false); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + list.setBoolean(2, false); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + @Test + public void testAdd() { + assertThat(list).isEmpty(); + + assertThat(list.add(false)).isTrue(); + assertThat(list).containsExactly(false); + + assertThat(list.add(true)).isTrue(); + list.add(0, false); + assertThat(list).containsExactly(false, false, true).inOrder(); + + list.add(0, true); + list.add(0, false); + // Force a resize by getting up to 11 elements. + for (int i = 0; i < 6; i++) { + list.add(i % 2 == 0); + } + assertThat(list) + .containsExactly(false, true, false, false, true, true, false, true, false, true, false) + .inOrder(); + + try { + list.add(-1, true); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + list.add(4, true); + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + @Test + public void testAddBoolean() { + assertThat(list).isEmpty(); + + list.addBoolean(false); + assertThat(list).containsExactly(false); + + list.addBoolean(true); + assertThat(list).containsExactly(false, true).inOrder(); + } + + @Test + public void testAddAll() { + assertThat(list).isEmpty(); + + assertThat(list.addAll(Collections.singleton(true))).isTrue(); + assertThat(list).hasSize(1); + assertThat((boolean) list.get(0)).isEqualTo(true); + assertThat(list.getBoolean(0)).isEqualTo(true); + + assertThat(list.addAll(asList(false, true, false, true, false))).isTrue(); + assertThat(list).containsExactly(true, false, true, false, true, false).inOrder(); + + assertThat(list.addAll(TERTIARY_LIST)).isTrue(); + assertThat(list) + .containsExactly(true, false, true, false, true, false, true, false, true) + .inOrder(); + + assertThat(list.addAll(Collections.emptyList())).isFalse(); + assertThat(list.addAll(BooleanArrayList.emptyList())).isFalse(); + } + + @Test + public void testEquals() { + BooleanArrayList list1 = new BooleanArrayList(); + BooleanArrayList list2 = new BooleanArrayList(); + + assertThat(list1).isEqualTo(list2); + } + + @Test + public void testRemove() { + list.addAll(TERTIARY_LIST); + assertThat((boolean) list.remove(0)).isEqualTo(true); + assertThat(list).containsExactly(false, true).inOrder(); + + assertThat(list.remove(Boolean.TRUE)).isTrue(); + assertThat(list).containsExactly(false); + + assertThat(list.remove(Boolean.TRUE)).isFalse(); + assertThat(list).containsExactly(false); + + assertThat((boolean) list.remove(0)).isEqualTo(false); + assertThat(list).isEmpty(); + + try { + list.remove(-1); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + + try { + list.remove(0); + assertWithMessage("expected exception").fail(); + } catch (IndexOutOfBoundsException e) { + // expected + } + } + + @Test + public void testRemoveEnd_listAtCapacity() { + BooleanList toRemove = BooleanArrayList.emptyList().mutableCopyWithCapacity(1); + toRemove.addBoolean(true); + toRemove.remove(0); + assertThat(toRemove).isEmpty(); + } + + @Test + public void testRemove_listAtCapacity() { + BooleanList toRemove = BooleanArrayList.emptyList().mutableCopyWithCapacity(2); + toRemove.addBoolean(true); + toRemove.addBoolean(false); + toRemove.remove(0); + assertThat(toRemove).hasSize(1); + assertThat((boolean) toRemove.get(0)).isEqualTo(false); + } + + @Test + public void testSublistRemoveEndOfCapacity() { + BooleanList toRemove = BooleanArrayList.emptyList().mutableCopyWithCapacity(1); + toRemove.addBoolean(true); + toRemove.subList(0, 1).clear(); + assertThat(toRemove).isEmpty(); + } + + private void assertImmutable(BooleanList list) { + + try { + list.add(true); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.add(0, true); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addAll(Collections.emptyList()); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addAll(Collections.singletonList(true)); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addAll(new BooleanArrayList()); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addAll(UNARY_LIST); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addAll(0, Collections.singleton(true)); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addAll(0, UNARY_LIST); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addAll(0, Collections.emptyList()); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.addBoolean(false); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.clear(); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.remove(1); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.remove(new Object()); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.removeAll(Collections.emptyList()); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.removeAll(Collections.singleton(Boolean.TRUE)); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.removeAll(UNARY_LIST); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.retainAll(Collections.emptyList()); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.removeAll(Collections.singleton(Boolean.TRUE)); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.retainAll(UNARY_LIST); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.set(0, false); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + + try { + list.setBoolean(0, false); + assertWithMessage("expected exception").fail(); + } catch (UnsupportedOperationException e) { + // expected + } + } + + private static BooleanArrayList newImmutableBooleanArrayList(boolean... elements) { + BooleanArrayList list = new BooleanArrayList(); + for (boolean element : elements) { + list.addBoolean(element); + } + list.makeImmutable(); + return list; + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/ExperimentalTestDataProvider.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/ExperimentalTestDataProvider.java new file mode 100644 index 0000000..3ef93ac --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/ExperimentalTestDataProvider.java @@ -0,0 +1,189 @@ +// 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. + +package com.google.protobuf; + +import java.util.Random; + +/** Utility class that provides data primitives for filling out protobuf messages. */ +public final class ExperimentalTestDataProvider { + private static final Random RANDOM = new Random(100); + + private final Varint32Provider varint32s = new Varint32Provider(); + private final Varint64Provider varint64s = new Varint64Provider(); + private final int stringLength; + + public ExperimentalTestDataProvider(int stringLength) { + this.stringLength = stringLength; + } + + public double getDouble() { + double value = 0.0; + while (Double.compare(0.0, value) == 0) { + value = RANDOM.nextDouble(); + } + return value; + } + + public float getFloat() { + float value = 0.0f; + while (Float.compare(0.0f, value) == 0) { + value = RANDOM.nextFloat(); + } + return value; + } + + public long getLong() { + return varint64s.getLong(); + } + + public int getInt() { + return varint32s.getInt(); + } + + public boolean getBool() { + return true; + } + + public int getEnum() { + return Math.abs(getInt()) % 3; + } + + public String getString() { + StringBuilder builder = new StringBuilder(stringLength); + for (int i = 0; i < stringLength; ++i) { + builder.append((char) (RANDOM.nextInt('z' - 'a') + 'a')); + } + return builder.toString(); + } + + public ByteString getBytes() { + return ByteString.copyFromUtf8(getString()); + } + + /** + * Iterator over integer values. Uses a simple distribution over 32-bit varints (generally + * favoring smaller values). + */ + private static final class Varint32Provider { + private static final int[][] VALUES = { + new int[] {1, 50, 100, 127}, // 1 byte values + new int[] {128, 500, 10000, 16383}, // 2 bytes values + new int[] {16384, 50000, 1000000, 2097151}, // 3 bytes values + new int[] {2097152, 10000000, 200000000, 268435455}, // 4 bytes values + new int[] {268435456, 0x30000000, 0x7FFFFFFF, 0xFFFFFFFF} // 5 bytes values + }; + + /** Number of samples that should be taken from each value array. */ + private static final int[] NUM_SAMPLES = {3, 2, 1, 1, 2}; + + /** + * The index into the {@link #VALUES} array that identifies the list of samples currently being + * iterated over. + */ + private int listIndex; + + /** The index of the next sample within a list. */ + private int sampleIndex; + + /** The number of successive samples that have been taken from the current list. */ + private int samplesTaken; + + public int getInt() { + if (samplesTaken++ > NUM_SAMPLES[listIndex]) { + // Done taking samples from this list. Go to the next one. + listIndex = (listIndex + 1) % VALUES.length; + sampleIndex = 0; + samplesTaken = 0; + } + + int value = VALUES[listIndex][sampleIndex]; + + // All lists are exactly 4 long (i.e. power of 2), so we can optimize the mod operation + // with masking. + sampleIndex = (sampleIndex + 1) & 3; + + return value; + } + } + + /** + * Iterator over integer values. Uses a simple distribution over 64-bit varints (generally + * favoring smaller values). + */ + private static final class Varint64Provider { + private static final long[][] VALUES = { + new long[] {1, 50, 100, 127}, + new long[] {128, 500, 10000, 16383}, + new long[] {16384, 50000, 1000000, 2097151}, + new long[] {2097152, 10000000, 200000000, 268435455}, + new long[] {268435456, 0x30000000, 0x7FFFFFFF, 34359738367L}, + new long[] {34359738368L, 2000000000000L, 4000000000000L, 4398046511103L}, + new long[] {4398046511104L, 200000000000000L, 500000000000000L, 562949953421311L}, + new long[] {0x4000000000000L, 0x5000000000000L, 0x6000000000000L, 0x0FFFFFFFFFFFFFFL}, + new long[] {0x100000000000000L, 0x3FFFFFFFFFFFFFFFL, 0x5FFFFFFFFFFFFFFL, 0x7FFFFFFFFFFFFFFFL}, + new long[] { + 0xFFFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFFFL + } + }; + + /** Number of samples that should be taken from each value array. */ + private static final int[] NUM_SAMPLES = {4, 2, 2, 1, 1, 1, 1, 2, 2, 4}; + + /** + * The index into the {@link #VALUES} array that identifies the list of samples currently being + * iterated over. + */ + private int listIndex; + + /** The index of the next sample within a list. */ + private int sampleIndex; + + /** The number of successive samples that have been taken from the current list. */ + private int samplesTaken; + + public long getLong() { + if (samplesTaken++ > NUM_SAMPLES[listIndex]) { + // Done taking samples from this list. Go to the next one. + listIndex = (listIndex + 1) % VALUES.length; + sampleIndex = 0; + samplesTaken = 0; + } + + long value = VALUES[listIndex][sampleIndex]; + + // All lists are exactly 4 long (i.e. power of 2), so we can optimize the mod operation + // with masking. + sampleIndex = (sampleIndex + 1) & 3; + + return value; + } + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java new file mode 100644 index 0000000..f1a6711 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java @@ -0,0 +1,322 @@ +// 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. + +package com.google.protobuf; + +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; + +import java.lang.ref.SoftReference; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Random; + +/** + * Shared testing code for {@link IsValidUtf8Test} and {@link IsValidUtf8FourByteTest}. + * + * @author jonp@google.com (Jon Perlow) + * @author martinrb@google.com (Martin Buchholz) + */ +final class IsValidUtf8TestUtil { + private IsValidUtf8TestUtil() {} + + static interface ByteStringFactory { + ByteString newByteString(byte[] bytes); + } + + static final ByteStringFactory LITERAL_FACTORY = + new ByteStringFactory() { + @Override + public ByteString newByteString(byte[] bytes) { + return ByteString.wrap(bytes); + } + }; + + static final ByteStringFactory HEAP_NIO_FACTORY = + new ByteStringFactory() { + @Override + public ByteString newByteString(byte[] bytes) { + return new NioByteString(ByteBuffer.wrap(bytes)); + } + }; + + private static final ThreadLocal> directBuffer = new ThreadLocal<>(); + + /** + * Factory for direct {@link ByteBuffer} instances. To reduce direct memory usage, this uses a + * thread local direct buffer. This means that each call will overwrite the buffer's contents from + * the previous call, so the calling code must be careful not to continue using a buffer returned + * from a previous invocation. + */ + static final ByteStringFactory DIRECT_NIO_FACTORY = + new ByteStringFactory() { + @Override + public ByteString newByteString(byte[] bytes) { + SoftReference ref = directBuffer.get(); + ByteBuffer buffer = ref == null ? null : ref.get(); + if (buffer == null || buffer.capacity() < bytes.length) { + buffer = ByteBuffer.allocateDirect(bytes.length); + directBuffer.set(new SoftReference(buffer)); + } + buffer.clear(); + buffer.put(bytes); + buffer.flip(); + return new NioByteString(buffer); + } + }; + + static final ByteStringFactory ROPE_FACTORY = + new ByteStringFactory() { + // Seed the random number generator with 0 so that the tests are deterministic. + private final Random random = new Random(0); + + @Override + public ByteString newByteString(byte[] bytes) { + // We split the byte array into three pieces (some possibly empty) by choosing two random + // cut points i and j. + int i = random.nextInt(bytes.length); + int j = random.nextInt(bytes.length); + if (j < i) { + int tmp = i; + i = j; + j = tmp; + } + return RopeByteString.newInstanceForTest( + ByteString.wrap(bytes, 0, i), + RopeByteString.newInstanceForTest( + ByteString.wrap(bytes, i, j - i), ByteString.wrap(bytes, j, bytes.length - j))); + } + }; + + // 128 - [chars 0x0000 to 0x007f] + static final long ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS = 0x007f - 0x0000 + 1; + + // 128 + static final long EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT = ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS; + + // 1920 [chars 0x0080 to 0x07FF] + static final long TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS = 0x07FF - 0x0080 + 1; + + // 18,304 + static final long EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT = + // Both bytes are one byte characters + (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 2) + + + // The possible number of two byte characters + TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS; + + // 2048 + static final long THREE_BYTE_SURROGATES = 2 * 1024; + + // 61,440 [chars 0x0800 to 0xFFFF, minus surrogates] + static final long THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS = + 0xFFFF - 0x0800 + 1 - THREE_BYTE_SURROGATES; + + // 2,650,112 + static final long EXPECTED_THREE_BYTE_ROUNDTRIPPABLE_COUNT = + // All one byte characters + (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 3) + + + // One two byte character and a one byte character + 2 * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS + + + // Three byte characters + THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS; + + // 1,048,576 [chars 0x10000L to 0x10FFFF] + static final long FOUR_BYTE_ROUNDTRIPPABLE_CHARACTERS = 0x10FFFF - 0x10000L + 1; + + // 289,571,839 + static final long EXPECTED_FOUR_BYTE_ROUNDTRIPPABLE_COUNT = + // All one byte characters + (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 4) + + + // One and three byte characters + 2 * THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS + + + // Two two byte characters + TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS + + + // Permutations of one and two byte characters + 3 + * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS + * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS + * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS + + + // Four byte characters + FOUR_BYTE_ROUNDTRIPPABLE_CHARACTERS; + + static final class Shard { + final long index; + final long start; + final long lim; + final long expected; + + public Shard(long index, long start, long lim, long expected) { + assertThat(start).isLessThan(lim); + this.index = index; + this.start = start; + this.lim = lim; + this.expected = expected; + } + } + + static final long[] FOUR_BYTE_SHARDS_EXPECTED_ROUNTRIPPABLES = + generateFourByteShardsExpectedRunnables(); + + private static long[] generateFourByteShardsExpectedRunnables() { + long[] expected = new long[128]; + + // 0-63 are all 5300224 + for (int i = 0; i <= 63; i++) { + expected[i] = 5300224; + } + + // 97-111 are all 2342912 + for (int i = 97; i <= 111; i++) { + expected[i] = 2342912; + } + + // 113-117 are all 1048576 + for (int i = 113; i <= 117; i++) { + expected[i] = 1048576; + } + + // One offs + expected[112] = 786432; + expected[118] = 786432; + expected[119] = 1048576; + expected[120] = 458752; + expected[121] = 524288; + expected[122] = 65536; + + // Anything not assigned was the default 0. + return expected; + } + + static final List FOUR_BYTE_SHARDS = + generateFourByteShards(128, FOUR_BYTE_SHARDS_EXPECTED_ROUNTRIPPABLES); + + private static List generateFourByteShards(int numShards, long[] expected) { + assertThat(expected).hasLength(numShards); + List shards = new ArrayList<>(numShards); + long lim = 1L << 32; + long increment = lim / numShards; + assertThat(lim % numShards).isEqualTo(0); + for (int i = 0; i < numShards; i++) { + shards.add(new Shard(i, increment * i, increment * (i + 1), expected[i])); + } + return shards; + } + + /** + * Helper to run the loop to test all the permutations for the number of bytes specified. + * + * @param factory the factory for {@link ByteString} instances. + * @param numBytes the number of bytes in the byte array + * @param expectedCount the expected number of roundtrippable permutations + */ + static void testBytes(ByteStringFactory factory, int numBytes, long expectedCount) { + testBytes(factory, numBytes, expectedCount, 0, -1); + } + + /** + * Helper to run the loop to test all the permutations for the number of bytes specified. This + * overload is useful for debugging to get the loop to start at a certain character. + * + * @param factory the factory for {@link ByteString} instances. + * @param numBytes the number of bytes in the byte array + * @param expectedCount the expected number of roundtrippable permutations + * @param start the starting bytes encoded as a long as big-endian + * @param lim the limit of bytes to process encoded as a long as big-endian, or -1 to mean the max + * limit for numBytes + */ + static void testBytes( + ByteStringFactory factory, int numBytes, long expectedCount, long start, long lim) { + byte[] bytes = new byte[numBytes]; + + if (lim == -1) { + lim = 1L << (numBytes * 8); + } + long countRoundTripped = 0; + for (long byteChar = start; byteChar < lim; byteChar++) { + long tmpByteChar = byteChar; + for (int i = 0; i < numBytes; i++) { + bytes[bytes.length - i - 1] = (byte) tmpByteChar; + tmpByteChar = tmpByteChar >> 8; + } + ByteString bs = factory.newByteString(bytes); + boolean isRoundTrippable = bs.isValidUtf8(); + String s = new String(bytes, Internal.UTF_8); + byte[] bytesReencoded = s.getBytes(Internal.UTF_8); + boolean bytesEqual = Arrays.equals(bytes, bytesReencoded); + + if (bytesEqual != isRoundTrippable) { + outputFailure(byteChar, bytes, bytesReencoded); + } + + // Check agreement with Utf8.isValidUtf8. + assertThat(Utf8.isValidUtf8(bytes)).isEqualTo(isRoundTrippable); + + if (isRoundTrippable) { + countRoundTripped++; + } + } + assertThat(countRoundTripped).isEqualTo(expectedCount); + } + + private static void outputFailure(long byteChar, byte[] bytes, byte[] after) { + outputFailure(byteChar, bytes, after, after.length); + } + + private static void outputFailure(long byteChar, byte[] bytes, byte[] after, int len) { + assertWithMessage("Failure: (%s) %s => %s", + Long.toHexString(byteChar), toHexString(bytes), toHexString(after, len)).fail(); + } + + private static String toHexString(byte[] b) { + return toHexString(b, b.length); + } + + private static String toHexString(byte[] b, int len) { + StringBuilder s = new StringBuilder(); + s.append("\""); + for (int i = 0; i < len; i++) { + if (i > 0) { + s.append(" "); + } + s.append(String.format("%02x", b[i] & 0xFF)); + } + s.append("\""); + return s.toString(); + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/LazyFieldLiteTest.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/LazyFieldLiteTest.java new file mode 100644 index 0000000..98cee80 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/LazyFieldLiteTest.java @@ -0,0 +1,266 @@ +// 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. + +package com.google.protobuf; + +import static com.google.common.truth.Truth.assertThat; +import static protobuf_unittest.UnittestProto.optionalInt32Extension; + +import protobuf_unittest.UnittestProto.TestAllExtensions; +import protobuf_unittest.UnittestProto.TestAllTypes; +import java.io.IOException; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit test for {@link LazyFieldLite}. */ +@RunWith(JUnit4.class) +public class LazyFieldLiteTest { + + @Test + public void testGetValue() { + MessageLite message = TestUtil.getAllSet(); + LazyFieldLite lazyField = createLazyFieldLiteFromMessage(message); + assertThat(message).isEqualTo(lazyField.getValue(TestAllTypes.getDefaultInstance())); + changeValue(lazyField); + assertNotEqual(message, lazyField.getValue(TestAllTypes.getDefaultInstance())); + } + + @Test + public void testGetValueEx() throws Exception { + TestAllExtensions message = TestUtil.getAllExtensionsSet(); + LazyFieldLite lazyField = createLazyFieldLiteFromMessage(message); + assertThat(message).isEqualTo(lazyField.getValue(TestAllExtensions.getDefaultInstance())); + changeValue(lazyField); + assertNotEqual(message, lazyField.getValue(TestAllExtensions.getDefaultInstance())); + } + + @Test + public void testSetValue() { + MessageLite message = TestUtil.getAllSet(); + LazyFieldLite lazyField = createLazyFieldLiteFromMessage(message); + changeValue(lazyField); + assertNotEqual(message, lazyField.getValue(TestAllTypes.getDefaultInstance())); + message = lazyField.getValue(TestAllTypes.getDefaultInstance()); + changeValue(lazyField); + assertThat(message).isEqualTo(lazyField.getValue(TestAllTypes.getDefaultInstance())); + } + + @Test + public void testSetValueEx() throws Exception { + TestAllExtensions message = TestUtil.getAllExtensionsSet(); + LazyFieldLite lazyField = createLazyFieldLiteFromMessage(message); + changeValue(lazyField); + assertNotEqual(message, lazyField.getValue(TestAllExtensions.getDefaultInstance())); + MessageLite value = lazyField.getValue(TestAllExtensions.getDefaultInstance()); + changeValue(lazyField); + assertThat(value).isEqualTo(lazyField.getValue(TestAllExtensions.getDefaultInstance())); + } + + @Test + public void testGetSerializedSize() { + MessageLite message = TestUtil.getAllSet(); + LazyFieldLite lazyField = createLazyFieldLiteFromMessage(message); + assertThat(message.getSerializedSize()).isEqualTo(lazyField.getSerializedSize()); + changeValue(lazyField); + assertNotEqual(message.getSerializedSize(), lazyField.getSerializedSize()); + } + + @Test + public void testGetSerializedSizeEx() throws Exception { + TestAllExtensions message = TestUtil.getAllExtensionsSet(); + LazyFieldLite lazyField = createLazyFieldLiteFromMessage(message); + assertThat(message.getSerializedSize()).isEqualTo(lazyField.getSerializedSize()); + changeValue(lazyField); + assertNotEqual(message.getSerializedSize(), lazyField.getSerializedSize()); + } + + @Test + public void testGetByteString() { + MessageLite message = TestUtil.getAllSet(); + LazyFieldLite lazyField = createLazyFieldLiteFromMessage(message); + assertThat(message.toByteString()).isEqualTo(lazyField.toByteString()); + changeValue(lazyField); + assertNotEqual(message.toByteString(), lazyField.toByteString()); + } + + @Test + public void testGetByteStringEx() throws Exception { + TestAllExtensions message = TestUtil.getAllExtensionsSet(); + LazyFieldLite lazyField = createLazyFieldLiteFromMessage(message); + assertThat(message.toByteString()).isEqualTo(lazyField.toByteString()); + changeValue(lazyField); + assertNotEqual(message.toByteString(), lazyField.toByteString()); + } + + @Test + public void testMergeExtensions() throws Exception { + TestAllExtensions message = TestUtil.getAllExtensionsSet(); + LazyFieldLite original = createLazyFieldLiteFromMessage(message); + LazyFieldLite merged = new LazyFieldLite(); + merged.merge(original); + TestAllExtensions value = + (TestAllExtensions) merged.getValue(TestAllExtensions.getDefaultInstance()); + assertThat(message).isEqualTo(value); + } + + @Test + public void testEmptyLazyField() throws Exception { + LazyFieldLite field = new LazyFieldLite(); + assertThat(field.getSerializedSize()).isEqualTo(0); + assertThat(field.toByteString()).isEqualTo(ByteString.EMPTY); + } + + @Test + public void testInvalidProto() throws Exception { + // Silently fails and uses the default instance. + LazyFieldLite field = + new LazyFieldLite(TestUtil.getExtensionRegistry(), ByteString.copyFromUtf8("invalid")); + assertThat( + field.getValue(TestAllTypes.getDefaultInstance())) + .isEqualTo(TestAllTypes.getDefaultInstance()); + assertThat(field.getSerializedSize()).isEqualTo(0); + assertThat(field.toByteString()).isEqualTo(ByteString.EMPTY); + } + + @Test + public void testMergeBeforeParsing() throws Exception { + TestAllTypes message1 = TestAllTypes.newBuilder().setOptionalInt32(1).build(); + LazyFieldLite field1 = createLazyFieldLiteFromMessage(message1); + TestAllTypes message2 = TestAllTypes.newBuilder().setOptionalInt64(2).build(); + LazyFieldLite field2 = createLazyFieldLiteFromMessage(message2); + + field1.merge(field2); + TestAllTypes expected = + TestAllTypes.newBuilder().setOptionalInt32(1).setOptionalInt64(2).build(); + assertThat(field1.getValue(TestAllTypes.getDefaultInstance())).isEqualTo(expected); + } + + @Test + public void testMergeOneNotParsed() throws Exception { + // Test a few different paths that involve one message that was not parsed. + TestAllTypes message1 = TestAllTypes.newBuilder().setOptionalInt32(1).build(); + TestAllTypes message2 = TestAllTypes.newBuilder().setOptionalInt64(2).build(); + TestAllTypes expected = + TestAllTypes.newBuilder().setOptionalInt32(1).setOptionalInt64(2).build(); + + LazyFieldLite field1 = LazyFieldLite.fromValue(message1); + field1.getValue(TestAllTypes.getDefaultInstance()); // Force parsing. + LazyFieldLite field2 = createLazyFieldLiteFromMessage(message2); + field1.merge(field2); + assertThat(field1.getValue(TestAllTypes.getDefaultInstance())).isEqualTo(expected); + + // Now reverse which one is parsed first. + field1 = LazyFieldLite.fromValue(message1); + field2 = createLazyFieldLiteFromMessage(message2); + field2.getValue(TestAllTypes.getDefaultInstance()); // Force parsing. + field1.merge(field2); + assertThat(field1.getValue(TestAllTypes.getDefaultInstance())).isEqualTo(expected); + } + + @Test + public void testMergeInvalid() throws Exception { + // Test a few different paths that involve one message that was not parsed. + TestAllTypes message = TestAllTypes.newBuilder().setOptionalInt32(1).build(); + LazyFieldLite valid = LazyFieldLite.fromValue(message); + LazyFieldLite invalid = + new LazyFieldLite(TestUtil.getExtensionRegistry(), ByteString.copyFromUtf8("invalid")); + invalid.merge(valid); + + // We swallow the exception and just use the set field. + assertThat(invalid.getValue(TestAllTypes.getDefaultInstance())).isEqualTo(message); + } + + @Test + public void testMergeKeepsExtensionsWhenPossible() throws Exception { + // In this test we attempt to only use the empty registry, which will strip out all extensions + // when serializing and then parsing. We verify that each code path will attempt to not + // serialize and parse a message that was set directly without going through the + // extensionRegistry. + TestAllExtensions messageWithExtensions = + TestAllExtensions.newBuilder().setExtension(optionalInt32Extension, 42).build(); + TestAllExtensions emptyMessage = TestAllExtensions.getDefaultInstance(); + + ExtensionRegistryLite emptyRegistry = ExtensionRegistryLite.getEmptyRegistry(); + + LazyFieldLite field = LazyFieldLite.fromValue(messageWithExtensions); + field.merge(createLazyFieldLiteFromMessage(emptyRegistry, emptyMessage)); + assertThat(field.getValue(TestAllExtensions.getDefaultInstance())) + .isEqualTo(messageWithExtensions); + + // Now reverse the order of the merging. + field = createLazyFieldLiteFromMessage(emptyRegistry, emptyMessage); + field.merge(LazyFieldLite.fromValue(messageWithExtensions)); + assertThat(field.getValue(TestAllExtensions.getDefaultInstance())) + .isEqualTo(messageWithExtensions); + + // Now try parsing the empty field first. + field = LazyFieldLite.fromValue(messageWithExtensions); + LazyFieldLite other = createLazyFieldLiteFromMessage(emptyRegistry, emptyMessage); + other.getValue(TestAllExtensions.getDefaultInstance()); // Force parsing. + field.merge(other); + assertThat(field.getValue(TestAllExtensions.getDefaultInstance())) + .isEqualTo(messageWithExtensions); + + // And again reverse. + field = createLazyFieldLiteFromMessage(emptyRegistry, emptyMessage); + field.getValue(TestAllExtensions.getDefaultInstance()); // Force parsing. + other = LazyFieldLite.fromValue(messageWithExtensions); + field.merge(other); + assertThat(field.getValue(TestAllExtensions.getDefaultInstance())) + .isEqualTo(messageWithExtensions); + } + + + // Help methods. + + private LazyFieldLite createLazyFieldLiteFromMessage(MessageLite message) { + return createLazyFieldLiteFromMessage(TestUtil.getExtensionRegistry(), message); + } + + private LazyFieldLite createLazyFieldLiteFromMessage( + ExtensionRegistryLite extensionRegistry, MessageLite message) { + ByteString bytes = message.toByteString(); + return new LazyFieldLite(extensionRegistry, bytes); + } + + private void changeValue(LazyFieldLite lazyField) { + TestAllTypes.Builder builder = TestUtil.getAllSet().toBuilder(); + builder.addRepeatedBool(true); + MessageLite newMessage = builder.build(); + lazyField.setValue(newMessage); + } + + private void assertNotEqual(Object unexpected, Object actual) { + assertThat(unexpected).isNotSameInstanceAs(actual); + assertThat((unexpected != null && unexpected.equals(actual))).isFalse(); + } + +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/PackedFieldTest.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/PackedFieldTest.java new file mode 100644 index 0000000..ce77baa --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/PackedFieldTest.java @@ -0,0 +1,242 @@ +// 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. + +package com.google.protobuf; + +import static com.google.common.truth.Truth.assertThat; + +import com.google.protobuf.PackedFieldTestProto.TestAllTypes; +import com.google.protobuf.PackedFieldTestProto.TestAllTypes.NestedEnum; +import com.google.protobuf.PackedFieldTestProto.TestUnpackedTypes; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests primitive repeated fields in proto3 are packed in wire format. */ +@RunWith(JUnit4.class) +public class PackedFieldTest { + static final ByteString expectedPackedRawBytes = + ByteString.copyFrom( + new byte[] { + (byte) 0xFA, + 0x01, + 0x01, + 0x01, // repeated int32 + (byte) 0x82, + 0x02, + 0x01, + 0x01, // repeated int64 + (byte) 0x8A, + 0x02, + 0x01, + 0x01, // repeated uint32 + (byte) 0x92, + 0x02, + 0x01, + 0x01, // repeated uint64 + (byte) 0x9A, + 0x02, + 0x01, + 0x02, // repeated sint32 + (byte) 0xA2, + 0x02, + 0x01, + 0x02, // repeated sint64 + (byte) 0xAA, + 0x02, + 0x04, + 0x01, + 0x00, + 0x00, + 0x00, // repeated fixed32 + (byte) 0xB2, + 0x02, + 0x08, + 0x01, + 0x00, + 0x00, + 0x00, // repeated fixed64 + 0x00, + 0x00, + 0x00, + 0x00, + (byte) 0xBA, + 0x02, + 0x04, + 0x01, + 0x00, + 0x00, + 0x00, // repeated sfixed32 + (byte) 0xC2, + 0x02, + 0x08, + 0x01, + 0x00, + 0x00, + 0x00, // repeated sfixed64 + 0x00, + 0x00, + 0x00, + 0x00, + (byte) 0xCA, + 0x02, + 0x04, + 0x00, + 0x00, + (byte) 0x80, + 0x3f, // repeated float + (byte) 0xD2, + 0x02, + 0x08, + 0x00, + 0x00, + 0x00, + 0x00, // repeated double + 0x00, + 0x00, + (byte) 0xf0, + 0x3f, + (byte) 0xDA, + 0x02, + 0x01, + 0x01, // repeated bool + (byte) 0x9A, + 0x03, + 0x01, + 0x01 // repeated nested enum + }); + + static final ByteString expectedUnpackedRawBytes = + ByteString.copyFrom( + new byte[] { + 0x08, + 0x01, // repeated int32 + 0x10, + 0x01, // repeated int64 + 0x18, + 0x01, // repeated uint32 + 0x20, + 0x01, // repeated uint64 + 0x28, + 0x02, // repeated sint32 + 0x30, + 0x02, // repeated sint64 + 0x3D, + 0x01, + 0x00, + 0x00, + 0x00, // repeated fixed32 + 0x41, + 0x01, + 0x00, + 0x00, + 0x00, // repeated fixed64 + 0x00, + 0x00, + 0x00, + 0x00, + 0x4D, + 0x01, + 0x00, + 0x00, + 0x00, // repeated sfixed32 + 0x51, + 0x01, + 0x00, + 0x00, + 0x00, // repeated sfixed64 + 0x00, + 0x00, + 0x00, + 0x00, + 0x5D, + 0x00, + 0x00, + (byte) 0x80, + 0x3f, // repeated float + 0x61, + 0x00, + 0x00, + 0x00, + 0x00, // repeated double + 0x00, + 0x00, + (byte) 0xf0, + 0x3f, + 0x68, + 0x01, // repeated bool + 0x70, + 0x01, // repeated nested enum + }); + + @Test + public void testPackedGeneratedMessage() throws Exception { + TestAllTypes message = TestAllTypes.parseFrom(expectedPackedRawBytes); + assertThat(message.toByteString()).isEqualTo(expectedPackedRawBytes); + } + + @Test + public void testPackedDynamicMessageSerialize() throws Exception { + DynamicMessage message = + DynamicMessage.parseFrom(TestAllTypes.getDescriptor(), expectedPackedRawBytes); + assertThat(message.toByteString()).isEqualTo(expectedPackedRawBytes); + } + + @Test + public void testUnpackedGeneratedMessage() throws Exception { + TestUnpackedTypes message = TestUnpackedTypes.parseFrom(expectedUnpackedRawBytes); + assertThat(message.toByteString()).isEqualTo(expectedUnpackedRawBytes); + } + + @Test + public void testUnPackedDynamicMessageSerialize() throws Exception { + DynamicMessage message = + DynamicMessage.parseFrom(TestUnpackedTypes.getDescriptor(), expectedUnpackedRawBytes); + assertThat(message.toByteString()).isEqualTo(expectedUnpackedRawBytes); + } + + // Make sure we haven't screwed up the code generation for packing fields by default. + @Test + public void testPackedSerialization() throws Exception { + TestAllTypes message = + TestAllTypes.newBuilder() + .addRepeatedInt32(1234) + .addRepeatedNestedEnum(NestedEnum.BAR) + .build(); + + CodedInputStream in = CodedInputStream.newInstance(message.toByteArray()); + + while (!in.isAtEnd()) { + int tag = in.readTag(); + assertThat(WireFormat.getTagWireType(tag)).isEqualTo(WireFormat.WIRETYPE_LENGTH_DELIMITED); + in.skipField(tag); + } + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/Proto2ExtensionLookupSchemaTest.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/Proto2ExtensionLookupSchemaTest.java new file mode 100644 index 0000000..07864a9 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/Proto2ExtensionLookupSchemaTest.java @@ -0,0 +1,168 @@ +// 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. + +package com.google.protobuf; + +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; + +import com.google.protobuf.testing.Proto2Testing; +import com.google.protobuf.testing.Proto2Testing.Proto2Message; +import com.google.protobuf.testing.Proto2Testing.Proto2Message.TestEnum; +import com.google.protobuf.testing.Proto2Testing.Proto2MessageWithExtensions; +import java.util.List; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class Proto2ExtensionLookupSchemaTest { + private byte[] data; + private ExtensionRegistry extensionRegistry; + + @Before + public void setup() { + TestSchemas.registerGenericProto2Schemas(); + + Protobuf.getInstance().schemaFor(Proto2MessageWithExtensions.class); + data = new Proto2MessageFactory(10, 20, 1, 1).newMessage().toByteArray(); + extensionRegistry = ExtensionRegistry.newInstance(); + Proto2Testing.registerAllExtensions(extensionRegistry); + } + + @Test + public void testExtensions() throws Exception { + Proto2MessageWithExtensions base = + Proto2MessageWithExtensions.parseFrom(data, extensionRegistry); + + Proto2MessageWithExtensions message = + ExperimentalSerializationUtil.fromByteArray( + data, Proto2MessageWithExtensions.class, extensionRegistry); + assertThat(message).isEqualTo(base); + + Proto2MessageWithExtensions roundtripMessage = + ExperimentalSerializationUtil.fromByteArray( + ExperimentalSerializationUtil.toByteArray(message), + Proto2MessageWithExtensions.class, + extensionRegistry); + assertThat(roundtripMessage).isEqualTo(base); + } + + @Test + public void testUnknownEnum() throws Exception { + // Use unknown fields to hold invalid enum values. + UnknownFieldSetLite unknowns = UnknownFieldSetLite.newInstance(); + final int outOfRange = 1000; + assertThat(TestEnum.forNumber(outOfRange)).isNull(); + unknowns.storeField( + WireFormat.makeTag(Proto2Message.FIELD_ENUM_13_FIELD_NUMBER, WireFormat.WIRETYPE_VARINT), + (long) outOfRange); + unknowns.storeField( + WireFormat.makeTag( + Proto2Message.FIELD_ENUM_LIST_30_FIELD_NUMBER, WireFormat.WIRETYPE_VARINT), + (long) TestEnum.ONE_VALUE); + unknowns.storeField( + WireFormat.makeTag( + Proto2Message.FIELD_ENUM_LIST_30_FIELD_NUMBER, WireFormat.WIRETYPE_VARINT), + (long) outOfRange); + unknowns.storeField( + WireFormat.makeTag( + Proto2Message.FIELD_ENUM_LIST_30_FIELD_NUMBER, WireFormat.WIRETYPE_VARINT), + (long) TestEnum.TWO_VALUE); + + { + // Construct a packed enum list. + int packedSize = + CodedOutputStream.computeUInt32SizeNoTag(TestEnum.ONE_VALUE) + + CodedOutputStream.computeUInt32SizeNoTag(outOfRange) + + CodedOutputStream.computeUInt32SizeNoTag(TestEnum.ONE_VALUE); + ByteString.CodedBuilder packedBuilder = ByteString.newCodedBuilder(packedSize); + CodedOutputStream packedOut = packedBuilder.getCodedOutput(); + packedOut.writeEnumNoTag(TestEnum.ONE_VALUE); + packedOut.writeEnumNoTag(outOfRange); + packedOut.writeEnumNoTag(TestEnum.TWO_VALUE); + unknowns.storeField( + WireFormat.makeTag( + Proto2Message.FIELD_ENUM_LIST_PACKED_44_FIELD_NUMBER, + WireFormat.WIRETYPE_LENGTH_DELIMITED), + packedBuilder.build()); + } + int size = unknowns.getSerializedSize(); + byte[] output = new byte[size]; + CodedOutputStream codedOutput = CodedOutputStream.newInstance(output); + unknowns.writeTo(codedOutput); + codedOutput.flush(); + + Proto2MessageWithExtensions parsed = + ExperimentalSerializationUtil.fromByteArray( + output, Proto2MessageWithExtensions.class, extensionRegistry); + assertWithMessage("out-of-range singular enum should not be in message") + .that(parsed.hasExtension(Proto2Testing.fieldEnum13)) + .isFalse(); + { + List singularEnum = + parsed + .getUnknownFields() + .getField(Proto2Message.FIELD_ENUM_13_FIELD_NUMBER) + .getVarintList(); + assertThat(singularEnum).hasSize(1); + assertThat(singularEnum.get(0)).isEqualTo((Long) (long) outOfRange); + } + { + List repeatedEnum = + parsed + .getUnknownFields() + .getField(Proto2Message.FIELD_ENUM_LIST_30_FIELD_NUMBER) + .getVarintList(); + assertThat(repeatedEnum).hasSize(1); + assertThat(repeatedEnum.get(0)).isEqualTo((Long) (long) outOfRange); + } + { + List packedRepeatedEnum = + parsed + .getUnknownFields() + .getField(Proto2Message.FIELD_ENUM_LIST_PACKED_44_FIELD_NUMBER) + .getVarintList(); + assertThat(packedRepeatedEnum).hasSize(1); + assertThat(packedRepeatedEnum.get(0)).isEqualTo((Long) (long) outOfRange); + } + assertWithMessage("out-of-range repeated enum should not be in message") + .that(parsed.getExtension(Proto2Testing.fieldEnumList30).size()) + .isEqualTo(2); + assertThat(parsed.getExtension(Proto2Testing.fieldEnumList30, 0)).isEqualTo(TestEnum.ONE); + assertThat(parsed.getExtension(Proto2Testing.fieldEnumList30, 1)).isEqualTo(TestEnum.TWO); + assertWithMessage("out-of-range packed repeated enum should not be in message") + .that(parsed.getExtension(Proto2Testing.fieldEnumListPacked44).size()) + .isEqualTo(2); + assertThat(parsed.getExtension(Proto2Testing.fieldEnumListPacked44, 0)).isEqualTo(TestEnum.ONE); + assertThat(parsed.getExtension(Proto2Testing.fieldEnumListPacked44, 1)).isEqualTo(TestEnum.TWO); + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/Proto3SchemaTest.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/Proto3SchemaTest.java new file mode 100644 index 0000000..5cd145b --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/Proto3SchemaTest.java @@ -0,0 +1,48 @@ +// 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. + +package com.google.protobuf; + +import com.google.protobuf.testing.Proto3Testing.Proto3Message; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class Proto3SchemaTest extends AbstractProto3SchemaTest { + @Override + protected void registerSchemas() { + TestSchemas.registerGenericProto3Schemas(); + } + + @Override + protected Schema schema() { + return TestSchemas.genericProto3Schema; + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java new file mode 100644 index 0000000..bb95e2a --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java @@ -0,0 +1,191 @@ +// 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. + +package com.google.protobuf; + +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; + +import protobuf_unittest.UnittestProto.TestAllTypes; +import protobuf_unittest.UnittestProto.TestAllTypesOrBuilder; +import java.util.Collections; +import java.util.List; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for {@link RepeatedFieldBuilderV3}. This tests basic functionality. More extensive testing is + * provided via other tests that exercise the builder. + */ +@RunWith(JUnit4.class) +public class RepeatedFieldBuilderV3Test { + + @Test + public void testBasicUse() { + TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent(); + RepeatedFieldBuilderV3 builder = + newRepeatedFieldBuilderV3(mockParent); + builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(0).build()); + builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build()); + assertThat(builder.getMessage(0).getOptionalInt32()).isEqualTo(0); + assertThat(builder.getMessage(1).getOptionalInt32()).isEqualTo(1); + + List list = builder.build(); + assertThat(list).hasSize(2); + assertThat(list.get(0).getOptionalInt32()).isEqualTo(0); + assertThat(list.get(1).getOptionalInt32()).isEqualTo(1); + assertIsUnmodifiable(list); + + // Make sure it doesn't change. + List list2 = builder.build(); + assertThat(list).isSameInstanceAs(list2); + assertThat(mockParent.getInvalidationCount()).isEqualTo(0); + } + + @Test + public void testGoingBackAndForth() { + TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent(); + RepeatedFieldBuilderV3 builder = + newRepeatedFieldBuilderV3(mockParent); + builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(0).build()); + builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build()); + assertThat(builder.getMessage(0).getOptionalInt32()).isEqualTo(0); + assertThat(builder.getMessage(1).getOptionalInt32()).isEqualTo(1); + + // Convert to list + List list = builder.build(); + assertThat(list).hasSize(2); + assertThat(list.get(0).getOptionalInt32()).isEqualTo(0); + assertThat(list.get(1).getOptionalInt32()).isEqualTo(1); + assertIsUnmodifiable(list); + + // Update 0th item + assertThat(mockParent.getInvalidationCount()).isEqualTo(0); + builder.getBuilder(0).setOptionalString("foo"); + assertThat(mockParent.getInvalidationCount()).isEqualTo(1); + list = builder.build(); + assertThat(list).hasSize(2); + assertThat(list.get(0).getOptionalInt32()).isEqualTo(0); + assertThat(list.get(0).getOptionalString()).isEqualTo("foo"); + assertThat(list.get(1).getOptionalInt32()).isEqualTo(1); + assertIsUnmodifiable(list); + assertThat(mockParent.getInvalidationCount()).isEqualTo(1); + } + + @Test + public void testVariousMethods() { + TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent(); + RepeatedFieldBuilderV3 builder = + newRepeatedFieldBuilderV3(mockParent); + builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build()); + builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(2).build()); + builder.addBuilder(0, TestAllTypes.getDefaultInstance()).setOptionalInt32(0); + builder.addBuilder(TestAllTypes.getDefaultInstance()).setOptionalInt32(3); + + assertThat(builder.getMessage(0).getOptionalInt32()).isEqualTo(0); + assertThat(builder.getMessage(1).getOptionalInt32()).isEqualTo(1); + assertThat(builder.getMessage(2).getOptionalInt32()).isEqualTo(2); + assertThat(builder.getMessage(3).getOptionalInt32()).isEqualTo(3); + + assertThat(mockParent.getInvalidationCount()).isEqualTo(0); + List messages = builder.build(); + assertThat(messages).hasSize(4); + assertThat(messages).isSameInstanceAs(builder.build()); // expect same list + + // Remove a message. + builder.remove(2); + assertThat(mockParent.getInvalidationCount()).isEqualTo(1); + assertThat(builder.getCount()).isEqualTo(3); + assertThat(builder.getMessage(0).getOptionalInt32()).isEqualTo(0); + assertThat(builder.getMessage(1).getOptionalInt32()).isEqualTo(1); + assertThat(builder.getMessage(2).getOptionalInt32()).isEqualTo(3); + + // Remove a builder. + builder.remove(0); + assertThat(mockParent.getInvalidationCount()).isEqualTo(1); + assertThat(builder.getCount()).isEqualTo(2); + assertThat(builder.getMessage(0).getOptionalInt32()).isEqualTo(1); + assertThat(builder.getMessage(1).getOptionalInt32()).isEqualTo(3); + + // Test clear. + builder.clear(); + assertThat(mockParent.getInvalidationCount()).isEqualTo(1); + assertThat(builder.getCount()).isEqualTo(0); + assertThat(builder.isEmpty()).isTrue(); + } + + @Test + public void testLists() { + TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent(); + RepeatedFieldBuilderV3 builder = + newRepeatedFieldBuilderV3(mockParent); + builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build()); + builder.addMessage(0, TestAllTypes.newBuilder().setOptionalInt32(0).build()); + assertThat(builder.getMessage(0).getOptionalInt32()).isEqualTo(0); + assertThat(builder.getMessage(1).getOptionalInt32()).isEqualTo(1); + + // Use list of builders. + List builders = builder.getBuilderList(); + assertThat(builders.get(0).getOptionalInt32()).isEqualTo(0); + assertThat(builders.get(1).getOptionalInt32()).isEqualTo(1); + builders.get(0).setOptionalInt32(10); + builders.get(1).setOptionalInt32(11); + + // Use list of protos + List protos = builder.getMessageList(); + assertThat(protos.get(0).getOptionalInt32()).isEqualTo(10); + assertThat(protos.get(1).getOptionalInt32()).isEqualTo(11); + + // Add an item to the builders and verify it's updated in both + builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(12).build()); + assertThat(builders).hasSize(3); + assertThat(protos).hasSize(3); + } + + private void assertIsUnmodifiable(List list) { + if (list == Collections.emptyList()) { + // OKAY -- Need to check this b/c EmptyList allows you to call clear. + } else { + try { + list.clear(); + assertWithMessage("List wasn't immutable").fail(); + } catch (UnsupportedOperationException e) { + // good + } + } + } + + private RepeatedFieldBuilderV3 + newRepeatedFieldBuilderV3(AbstractMessage.BuilderParent parent) { + return new RepeatedFieldBuilderV3( + Collections.emptyList(), false, parent, false); + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java new file mode 100644 index 0000000..ab32e2a --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java @@ -0,0 +1,93 @@ +// 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. + +package com.google.protobuf; + +import static com.google.common.truth.Truth.assertThat; + +import junit.framework.TestCase; + +/** + * Tests that proto2 api generation doesn't cause compile errors when compiling protocol buffers + * that have names that would otherwise conflict if not fully qualified (like @Deprecated + * and @Override). + * + *

Forked from {@link TestBadIdentifiers}. + * + * @author jonp@google.com (Jon Perlow) + */ +public final class TestBadIdentifiersLite extends TestCase { + + public void testCompilation() { + // If this compiles, it means the generation was correct. + TestBadIdentifiersProto.Deprecated.Builder builder1 = + TestBadIdentifiersProto.Deprecated.newBuilder(); + TestBadIdentifiersProto.Override.Builder builder2 = + TestBadIdentifiersProto.Override.newBuilder(); + } + + public void testConflictingFieldNames() throws Exception { + TestBadIdentifiersProto.TestConflictingFieldNames message = + TestBadIdentifiersProto.TestConflictingFieldNames.getDefaultInstance(); + // Make sure generated accessors are properly named. + assertThat(message.getInt32Field1Count()).isEqualTo(0); + assertThat(message.getEnumField2Count()).isEqualTo(0); + assertThat(message.getStringField3Count()).isEqualTo(0); + assertThat(message.getBytesField4Count()).isEqualTo(0); + assertThat(message.getMessageField5Count()).isEqualTo(0); + + assertThat(message.getInt32FieldCount11()).isEqualTo(0); + assertThat(message.getEnumFieldCount12().getNumber()).isEqualTo(0); + assertThat(message.getStringFieldCount13()).isEmpty(); + assertThat(message.getBytesFieldCount14()).isEqualTo(ByteString.EMPTY); + assertThat(message.getMessageFieldCount15().getSerializedSize()).isEqualTo(0); + + assertThat(message.getInt32Field21Count()).isEqualTo(0); + assertThat(message.getEnumField22Count()).isEqualTo(0); + assertThat(message.getStringField23Count()).isEqualTo(0); + assertThat(message.getBytesField24Count()).isEqualTo(0); + assertThat(message.getMessageField25Count()).isEqualTo(0); + + assertThat(message.getInt32Field1List()).isEmpty(); + assertThat(message.getInt32FieldList31()).isEqualTo(0); + + assertThat(message.getInt64FieldCount()).isEqualTo(0); + assertThat( + message + .getExtension(TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldCount) + .longValue()) + .isEqualTo(0L); + assertThat( + message + .getExtension(TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldList) + .longValue()) + .isEqualTo(0L); + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/TestSchemas.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/TestSchemas.java new file mode 100644 index 0000000..ab0ced4 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/TestSchemas.java @@ -0,0 +1,94 @@ +// 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. + +package com.google.protobuf; + +import com.google.protobuf.testing.Proto2Testing; +import com.google.protobuf.testing.Proto2Testing.Proto2Empty; +import com.google.protobuf.testing.Proto2Testing.Proto2Message; +import com.google.protobuf.testing.Proto2Testing.Proto2MessageWithExtensions; +import com.google.protobuf.testing.Proto2Testing.Proto2MessageWithMaps; +import com.google.protobuf.testing.Proto3Testing.Proto3Empty; +import com.google.protobuf.testing.Proto3Testing.Proto3Message; +import com.google.protobuf.testing.Proto3Testing.Proto3MessageWithMaps; + +/** Schemas to support testing. */ +public class TestSchemas { + public static final Schema genericProto2Schema = + new ManifestSchemaFactory().createSchema(Proto2Message.class); + public static final Schema genericProto3Schema = + new ManifestSchemaFactory().createSchema(Proto3Message.class); + + public static void registerGenericProto2Schemas() { + registerProto2Schemas(); + } + + public static void registerGenericProto3Schemas() { + registerProto3Schemas(); + } + + private static void registerProto2Schemas() { + Protobuf protobuf = Protobuf.getInstance(); + ManifestSchemaFactory factory = new ManifestSchemaFactory(); + protobuf.registerSchemaOverride(Proto2Message.class, factory.createSchema(Proto2Message.class)); + protobuf.registerSchemaOverride( + Proto2Message.FieldGroup49.class, factory.createSchema(Proto2Message.FieldGroup49.class)); + protobuf.registerSchemaOverride( + Proto2Message.FieldGroupList51.class, + factory.createSchema(Proto2Message.FieldGroupList51.class)); + protobuf.registerSchemaOverride( + Proto2Message.FieldGroup69.class, factory.createSchema(Proto2Message.FieldGroup69.class)); + protobuf.registerSchemaOverride( + Proto2Message.RequiredNestedMessage.class, + factory.createSchema(Proto2Message.RequiredNestedMessage.class)); + protobuf.registerSchemaOverride( + Proto2Message.FieldRequiredGroup88.class, + factory.createSchema(Proto2Message.FieldRequiredGroup88.class)); + protobuf.registerSchemaOverride(Proto2Empty.class, factory.createSchema(Proto2Empty.class)); + protobuf.registerSchemaOverride( + Proto2MessageWithExtensions.class, factory.createSchema(Proto2MessageWithExtensions.class)); + protobuf.registerSchemaOverride( + Proto2Testing.FieldGroup49.class, factory.createSchema(Proto2Testing.FieldGroup49.class)); + protobuf.registerSchemaOverride( + Proto2Testing.FieldGroupList51.class, + factory.createSchema(Proto2Testing.FieldGroupList51.class)); + protobuf.registerSchemaOverride( + Proto2MessageWithMaps.class, factory.createSchema(Proto2MessageWithMaps.class)); + } + + private static void registerProto3Schemas() { + Protobuf protobuf = Protobuf.getInstance(); + ManifestSchemaFactory factory = new ManifestSchemaFactory(); + protobuf.registerSchemaOverride(Proto3Message.class, factory.createSchema(Proto3Message.class)); + protobuf.registerSchemaOverride(Proto3Empty.class, factory.createSchema(Proto3Empty.class)); + protobuf.registerSchemaOverride( + Proto3MessageWithMaps.class, factory.createSchema(Proto3MessageWithMaps.class)); + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/TypeRegistryTest.java b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/TypeRegistryTest.java new file mode 100644 index 0000000..c9defb3 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/java/com/google/protobuf/TypeRegistryTest.java @@ -0,0 +1,69 @@ +// 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. + +package com.google.protobuf; + +import static com.google.common.truth.Truth.assertThat; + +import com.google.protobuf.Descriptors.Descriptor; +import protobuf_unittest.UnittestProto; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public final class TypeRegistryTest { + + @Test + public void findDescriptorByFullName() throws Exception { + Descriptor descriptor = UnittestProto.TestAllTypes.getDescriptor(); + assertThat(TypeRegistry.getEmptyTypeRegistry().find(descriptor.getFullName())).isNull(); + + assertThat(TypeRegistry.newBuilder().add(descriptor).build().find(descriptor.getFullName())) + .isSameInstanceAs(descriptor); + } + + @Test + public void findDescriptorByTypeUrl() throws Exception { + Descriptor descriptor = UnittestProto.TestAllTypes.getDescriptor(); + assertThat( + TypeRegistry.getEmptyTypeRegistry() + .getDescriptorForTypeUrl("type.googleapis.com/" + descriptor.getFullName())) + .isNull(); + + assertThat( + TypeRegistry.newBuilder() + .add(descriptor) + .build() + .getDescriptorForTypeUrl("type.googleapis.com/" + descriptor.getFullName())) + .isSameInstanceAs(descriptor); + } + +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto new file mode 100644 index 0000000..4ec9688 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto @@ -0,0 +1,130 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto2"; + + +option java_outer_classname = "MapForProto2TestProto"; + +message TestMap { + message MessageValue { + optional int32 value = 1; + } + enum EnumValue { + FOO = 0; + BAR = 1; + BAZ = 2; + QUX = 3; + } + + map int32_to_int32_field = 1; + map int32_to_string_field = 2; + map int32_to_bytes_field = 3; + map int32_to_enum_field = 4; + map int32_to_message_field = 5; + map string_to_int32_field = 6; + + message MessageWithRequiredFields { + required int32 value = 1; + } + map required_message_map = 11; +} + +message TestUnknownEnumValue { + // Wire-compatible with TestMap.int32_to_enum_field so we can test the + // parsing behavior of TestMap regarding unknown enum values. + map int32_to_int32_field = 4; +} + +// Test that the maps initialization code works correctly when the map field +// references the containing message. +message TestRecursiveMap { + optional int32 value = 1; + map recursive_map_field = 2; +} + +// a decoy of TestMap for testing parsing errors +message BizarroTestMap { + // same key type, different value + map int32_to_int32_field = 1; + // different key and value types + map int32_to_string_field = 2; + // different key types, same value + map int32_to_bytes_field = 3; + // different key and value types + map int32_to_enum_field = 4; + // different key and value types + map int32_to_message_field = 5; + // same key type, different value + map string_to_int32_field = 6; +} + +// Used to test that java reserved words can be used as protobuf field names +// Not all reserved words are tested (to avoid bloat) but instead an arbitrary +// subset of them chosen to cover various keyword categories like +// type, modifier, declaration, etc. +message ReservedAsMapField { + map if = 1; + map const = 2; + map private = 3; + map class = 4; + map int = 5; + map void = 6; + // These are also proto keywords + map string = 7; + map package = 8; + // Most recent Java reserved word + map enum = 9; + // null is not a 'reserved word' per se but as a literal needs similar care + map null = 10; +} + +message ReservedAsMapFieldWithEnumValue { + enum SampleEnum { + A = 0; + B = 1; + } + map if = 1; + map const = 2; + map private = 3; + map class = 4; + map int = 5; + map void = 6; + // These are also proto keywords + map string = 7; + map package = 8; + // Most recent Java reserved word + map enum = 9; + // null is not a 'reserved word' per se but as a literal needs similar care + map null = 10; +} +package map_for_proto2_lite_test; +option java_package = "map_lite_test"; +option optimize_for = LITE_RUNTIME; diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/proto/com/google/protobuf/nested_extension.proto b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/proto/com/google/protobuf/nested_extension.proto new file mode 100644 index 0000000..2da6d08 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/proto/com/google/protobuf/nested_extension.proto @@ -0,0 +1,48 @@ +// 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: Darick Tong (darick@google.com) +// +// A proto file with nested extensions. Note that this must be defined in +// a separate file to properly test the initialization of the outer class. + +syntax = "proto2"; + +package protobuf_unittest; + +import "com/google/protobuf/non_nested_extension.proto"; + + +message MyNestedExtension { + extend MessageToBeExtended { + optional MessageToBeExtended recursiveExtension = 2; + optional int32 default = 2002; + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/proto/com/google/protobuf/nested_extension_lite.proto b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/proto/com/google/protobuf/nested_extension_lite.proto new file mode 100644 index 0000000..024097c --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/proto/com/google/protobuf/nested_extension_lite.proto @@ -0,0 +1,50 @@ +// 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: Darick Tong (darick@google.com) +// +// A proto file with nested extensions for a MessageLite messages. Note that +// this must be defined in a separate file to properly test the initialization +// of the outer class. + +syntax = "proto2"; + +package protobuf_unittest; + +import "com/google/protobuf/non_nested_extension_lite.proto"; + +option optimize_for = LITE_RUNTIME; + +message MyNestedExtensionLite { + extend MessageLiteToBeExtended { + optional MessageLiteToBeExtended recursiveExtensionLite = 3; + optional double private = 2004; + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/proto/com/google/protobuf/non_nested_extension.proto b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/proto/com/google/protobuf/non_nested_extension.proto new file mode 100644 index 0000000..45395a3 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/proto/com/google/protobuf/non_nested_extension.proto @@ -0,0 +1,49 @@ +// 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: Darick Tong (darick@google.com) +// +// A proto file with extensions. + +syntax = "proto2"; + +package protobuf_unittest; + + +message MessageToBeExtended { + extensions 1 to max; +} + +message MyNonNestedExtension {} + +extend MessageToBeExtended { + optional MyNonNestedExtension nonNestedExtension = 1; + optional string if = 2000; +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/proto/com/google/protobuf/proto3_message_lite.proto b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/proto/com/google/protobuf/proto3_message_lite.proto new file mode 100644 index 0000000..4a378b5 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/core/src/test/proto/com/google/protobuf/proto3_message_lite.proto @@ -0,0 +1,320 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package protobuf.experimental; + +option java_package = "com.google.protobuf.testing"; +option java_outer_classname = "Proto3TestingLite"; + +message Proto3MessageLite { + enum TestEnum { + ZERO = 0; + ONE = 1; + TWO = 2; + } + + double field_double_1 = 1; + float field_float_2 = 2; + int64 field_int64_3 = 3; + uint64 field_uint64_4 = 4; + int32 field_int32_5 = 5; + fixed64 field_fixed64_6 = 6; + fixed32 field_fixed32_7 = 7; + bool field_bool_8 = 8; + string field_string_9 = 9; + Proto3MessageLite field_message_10 = 10; + bytes field_bytes_11 = 11; + uint32 field_uint32_12 = 12; + TestEnum field_enum_13 = 13; + sfixed32 field_sfixed32_14 = 14; + sfixed64 field_sfixed64_15 = 15; + sint32 field_sint32_16 = 16; + sint64 field_sint64_17 = 17; + repeated double field_double_list_18 = 18 [packed = false]; + repeated float field_float_list_19 = 19 [packed = false]; + repeated int64 field_int64_list_20 = 20 [packed = false]; + repeated uint64 field_uint64_list_21 = 21 [packed = false]; + repeated int32 field_int32_list_22 = 22 [packed = false]; + repeated fixed64 field_fixed64_list_23 = 23 [packed = false]; + repeated fixed32 field_fixed32_list_24 = 24 [packed = false]; + repeated bool field_bool_list_25 = 25 [packed = false]; + repeated string field_string_list_26 = 26 [packed = false]; + repeated Proto3MessageLite field_message_list_27 = 27 [packed = false]; + repeated bytes field_bytes_list_28 = 28 [packed = false]; + repeated uint32 field_uint32_list_29 = 29 [packed = false]; + repeated TestEnum field_enum_list_30 = 30 [packed = false]; + repeated sfixed32 field_sfixed32_list_31 = 31 [packed = false]; + repeated sfixed64 field_sfixed64_list_32 = 32 [packed = false]; + repeated sint32 field_sint32_list_33 = 33 [packed = false]; + repeated sint64 field_sint64_list_34 = 34 [packed = false]; + repeated double field_double_list_packed_35 = 35 [packed = true]; + repeated float field_float_list_packed_36 = 36 [packed = true]; + repeated int64 field_int64_list_packed_37 = 37 [packed = true]; + repeated uint64 field_uint64_list_packed_38 = 38 [packed = true]; + repeated int32 field_int32_list_packed_39 = 39 [packed = true]; + repeated fixed64 field_fixed64_list_packed_40 = 40 [packed = true]; + repeated fixed32 field_fixed32_list_packed_41 = 41 [packed = true]; + repeated bool field_bool_list_packed_42 = 42 [packed = true]; + repeated uint32 field_uint32_list_packed_43 = 43 [packed = true]; + repeated TestEnum field_enum_list_packed_44 = 44 [packed = true]; + repeated sfixed32 field_sfixed32_list_packed_45 = 45 [packed = true]; + repeated sfixed64 field_sfixed64_list_packed_46 = 46 [packed = true]; + repeated sint32 field_sint32_list_packed_47 = 47 [packed = true]; + repeated sint64 field_sint64_list_packed_48 = 48 [packed = true]; + oneof test_oneof { + double field_double_53 = 53; + float field_float_54 = 54; + int64 field_int64_55 = 55; + uint64 field_uint64_56 = 56; + int32 field_int32_57 = 57; + fixed64 field_fixed64_58 = 58; + fixed32 field_fixed32_59 = 59; + bool field_bool_60 = 60; + string field_string_61 = 61; + Proto3MessageLite field_message_62 = 62; + bytes field_bytes_63 = 63; + uint32 field_uint32_64 = 64; + sfixed32 field_sfixed32_65 = 65; + sfixed64 field_sfixed64_66 = 66; + sint32 field_sint32_67 = 67; + sint64 field_sint64_68 = 68; + } +} + +message Proto3EmptyLite {} + +message Proto3MessageLiteWithMaps { + map field_map_bool_bool_1 = 1; + map field_map_bool_bytes_2 = 2; + map field_map_bool_double_3 = 3; + map field_map_bool_enum_4 = 4; + map field_map_bool_fixed32_5 = 5; + map field_map_bool_fixed64_6 = 6; + map field_map_bool_float_7 = 7; + map field_map_bool_int32_8 = 8; + map field_map_bool_int64_9 = 9; + map field_map_bool_message_10 = 10; + map field_map_bool_sfixed32_11 = 11; + map field_map_bool_sfixed64_12 = 12; + map field_map_bool_sint32_13 = 13; + map field_map_bool_sint64_14 = 14; + map field_map_bool_string_15 = 15; + map field_map_bool_uint32_16 = 16; + map field_map_bool_uint64_17 = 17; + map field_map_fixed32_bool_18 = 18; + map field_map_fixed32_bytes_19 = 19; + map field_map_fixed32_double_20 = 20; + map field_map_fixed32_enum_21 = 21; + map field_map_fixed32_fixed32_22 = 22; + map field_map_fixed32_fixed64_23 = 23; + map field_map_fixed32_float_24 = 24; + map field_map_fixed32_int32_25 = 25; + map field_map_fixed32_int64_26 = 26; + map field_map_fixed32_message_27 = 27; + map field_map_fixed32_sfixed32_28 = 28; + map field_map_fixed32_sfixed64_29 = 29; + map field_map_fixed32_sint32_30 = 30; + map field_map_fixed32_sint64_31 = 31; + map field_map_fixed32_string_32 = 32; + map field_map_fixed32_uint32_33 = 33; + map field_map_fixed32_uint64_34 = 34; + map field_map_fixed64_bool_35 = 35; + map field_map_fixed64_bytes_36 = 36; + map field_map_fixed64_double_37 = 37; + map field_map_fixed64_enum_38 = 38; + map field_map_fixed64_fixed32_39 = 39; + map field_map_fixed64_fixed64_40 = 40; + map field_map_fixed64_float_41 = 41; + map field_map_fixed64_int32_42 = 42; + map field_map_fixed64_int64_43 = 43; + map field_map_fixed64_message_44 = 44; + map field_map_fixed64_sfixed32_45 = 45; + map field_map_fixed64_sfixed64_46 = 46; + map field_map_fixed64_sint32_47 = 47; + map field_map_fixed64_sint64_48 = 48; + map field_map_fixed64_string_49 = 49; + map field_map_fixed64_uint32_50 = 50; + map field_map_fixed64_uint64_51 = 51; + map field_map_int32_bool_52 = 52; + map field_map_int32_bytes_53 = 53; + map field_map_int32_double_54 = 54; + map field_map_int32_enum_55 = 55; + map field_map_int32_fixed32_56 = 56; + map field_map_int32_fixed64_57 = 57; + map field_map_int32_float_58 = 58; + map field_map_int32_int32_59 = 59; + map field_map_int32_int64_60 = 60; + map field_map_int32_message_61 = 61; + map field_map_int32_sfixed32_62 = 62; + map field_map_int32_sfixed64_63 = 63; + map field_map_int32_sint32_64 = 64; + map field_map_int32_sint64_65 = 65; + map field_map_int32_string_66 = 66; + map field_map_int32_uint32_67 = 67; + map field_map_int32_uint64_68 = 68; + map field_map_int64_bool_69 = 69; + map field_map_int64_bytes_70 = 70; + map field_map_int64_double_71 = 71; + map field_map_int64_enum_72 = 72; + map field_map_int64_fixed32_73 = 73; + map field_map_int64_fixed64_74 = 74; + map field_map_int64_float_75 = 75; + map field_map_int64_int32_76 = 76; + map field_map_int64_int64_77 = 77; + map field_map_int64_message_78 = 78; + map field_map_int64_sfixed32_79 = 79; + map field_map_int64_sfixed64_80 = 80; + map field_map_int64_sint32_81 = 81; + map field_map_int64_sint64_82 = 82; + map field_map_int64_string_83 = 83; + map field_map_int64_uint32_84 = 84; + map field_map_int64_uint64_85 = 85; + map field_map_sfixed32_bool_86 = 86; + map field_map_sfixed32_bytes_87 = 87; + map field_map_sfixed32_double_88 = 88; + map field_map_sfixed32_enum_89 = 89; + map field_map_sfixed32_fixed32_90 = 90; + map field_map_sfixed32_fixed64_91 = 91; + map field_map_sfixed32_float_92 = 92; + map field_map_sfixed32_int32_93 = 93; + map field_map_sfixed32_int64_94 = 94; + map field_map_sfixed32_message_95 = 95; + map field_map_sfixed32_sfixed32_96 = 96; + map field_map_sfixed32_sfixed64_97 = 97; + map field_map_sfixed32_sint32_98 = 98; + map field_map_sfixed32_sint64_99 = 99; + map field_map_sfixed32_string_100 = 100; + map field_map_sfixed32_uint32_101 = 101; + map field_map_sfixed32_uint64_102 = 102; + map field_map_sfixed64_bool_103 = 103; + map field_map_sfixed64_bytes_104 = 104; + map field_map_sfixed64_double_105 = 105; + map field_map_sfixed64_enum_106 = 106; + map field_map_sfixed64_fixed32_107 = 107; + map field_map_sfixed64_fixed64_108 = 108; + map field_map_sfixed64_float_109 = 109; + map field_map_sfixed64_int32_110 = 110; + map field_map_sfixed64_int64_111 = 111; + map field_map_sfixed64_message_112 = 112; + map field_map_sfixed64_sfixed32_113 = 113; + map field_map_sfixed64_sfixed64_114 = 114; + map field_map_sfixed64_sint32_115 = 115; + map field_map_sfixed64_sint64_116 = 116; + map field_map_sfixed64_string_117 = 117; + map field_map_sfixed64_uint32_118 = 118; + map field_map_sfixed64_uint64_119 = 119; + map field_map_sint32_bool_120 = 120; + map field_map_sint32_bytes_121 = 121; + map field_map_sint32_double_122 = 122; + map field_map_sint32_enum_123 = 123; + map field_map_sint32_fixed32_124 = 124; + map field_map_sint32_fixed64_125 = 125; + map field_map_sint32_float_126 = 126; + map field_map_sint32_int32_127 = 127; + map field_map_sint32_int64_128 = 128; + map field_map_sint32_message_129 = 129; + map field_map_sint32_sfixed32_130 = 130; + map field_map_sint32_sfixed64_131 = 131; + map field_map_sint32_sint32_132 = 132; + map field_map_sint32_sint64_133 = 133; + map field_map_sint32_string_134 = 134; + map field_map_sint32_uint32_135 = 135; + map field_map_sint32_uint64_136 = 136; + map field_map_sint64_bool_137 = 137; + map field_map_sint64_bytes_138 = 138; + map field_map_sint64_double_139 = 139; + map field_map_sint64_enum_140 = 140; + map field_map_sint64_fixed32_141 = 141; + map field_map_sint64_fixed64_142 = 142; + map field_map_sint64_float_143 = 143; + map field_map_sint64_int32_144 = 144; + map field_map_sint64_int64_145 = 145; + map field_map_sint64_message_146 = 146; + map field_map_sint64_sfixed32_147 = 147; + map field_map_sint64_sfixed64_148 = 148; + map field_map_sint64_sint32_149 = 149; + map field_map_sint64_sint64_150 = 150; + map field_map_sint64_string_151 = 151; + map field_map_sint64_uint32_152 = 152; + map field_map_sint64_uint64_153 = 153; + map field_map_string_bool_154 = 154; + map field_map_string_bytes_155 = 155; + map field_map_string_double_156 = 156; + map field_map_string_enum_157 = 157; + map field_map_string_fixed32_158 = 158; + map field_map_string_fixed64_159 = 159; + map field_map_string_float_160 = 160; + map field_map_string_int32_161 = 161; + map field_map_string_int64_162 = 162; + map field_map_string_message_163 = 163; + map field_map_string_sfixed32_164 = 164; + map field_map_string_sfixed64_165 = 165; + map field_map_string_sint32_166 = 166; + map field_map_string_sint64_167 = 167; + map field_map_string_string_168 = 168; + map field_map_string_uint32_169 = 169; + map field_map_string_uint64_170 = 170; + map field_map_uint32_bool_171 = 171; + map field_map_uint32_bytes_172 = 172; + map field_map_uint32_double_173 = 173; + map field_map_uint32_enum_174 = 174; + map field_map_uint32_fixed32_175 = 175; + map field_map_uint32_fixed64_176 = 176; + map field_map_uint32_float_177 = 177; + map field_map_uint32_int32_178 = 178; + map field_map_uint32_int64_179 = 179; + map field_map_uint32_message_180 = 180; + map field_map_uint32_sfixed32_181 = 181; + map field_map_uint32_sfixed64_182 = 182; + map field_map_uint32_sint32_183 = 183; + map field_map_uint32_sint64_184 = 184; + map field_map_uint32_string_185 = 185; + map field_map_uint32_uint32_186 = 186; + map field_map_uint32_uint64_187 = 187; + map field_map_uint64_bool_188 = 188; + map field_map_uint64_bytes_189 = 189; + map field_map_uint64_double_190 = 190; + map field_map_uint64_enum_191 = 191; + map field_map_uint64_fixed32_192 = 192; + map field_map_uint64_fixed64_193 = 193; + map field_map_uint64_float_194 = 194; + map field_map_uint64_int32_195 = 195; + map field_map_uint64_int64_196 = 196; + map field_map_uint64_message_197 = 197; + map field_map_uint64_sfixed32_198 = 198; + map field_map_uint64_sfixed64_199 = 199; + map field_map_uint64_sint32_200 = 200; + map field_map_uint64_sint64_201 = 201; + map field_map_uint64_string_202 = 202; + map field_map_uint64_uint32_203 = 203; + map field_map_uint64_uint64_204 = 204; +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/kotlin-lite/lite.awk b/tools/go-generator/cmd/generator/_protobuf/java/kotlin-lite/lite.awk new file mode 100644 index 0000000..b22d965 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/kotlin-lite/lite.awk @@ -0,0 +1,25 @@ +# Remove code enclosed by "BEGIN FULL-RUNTIME" and "END FULL-RUNTIME" to +# create the lite-only version of a test file. + +BEGIN { + in_full_runtime = 0; +} + +/BEGIN FULL-RUNTIME/ { + in_full_runtime = 1; + next; +} + +/END FULL-RUNTIME/ { + in_full_runtime = 0; + next; +} + +in_full_runtime { + # Skip full runtime code path. + next; +} + +{ + print; +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/kotlin/src/main/kotlin/com/google/protobuf/OnlyForUseByGeneratedProtoCode.kt b/tools/go-generator/cmd/generator/_protobuf/java/kotlin/src/main/kotlin/com/google/protobuf/OnlyForUseByGeneratedProtoCode.kt new file mode 100644 index 0000000..c8ed63d --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/kotlin/src/main/kotlin/com/google/protobuf/OnlyForUseByGeneratedProtoCode.kt @@ -0,0 +1,48 @@ +// 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. + +package com.google.protobuf.kotlin + +/** + * Opt-in annotation to make it difficult to accidentally use APIs only intended for use by proto + * generated code. See https://kotlinlang.org/docs/reference/opt-in-requirements.html for details + * on how this API works. + */ +@RequiresOptIn( + message = + """ + This API is only intended for use by generated protobuf code, the code generator, and their own + tests. If this does not describe your code, you should not be using this API. + """, + level = RequiresOptIn.Level.ERROR +) +@Retention(AnnotationRetention.BINARY) +@Target(AnnotationTarget.CONSTRUCTOR, AnnotationTarget.ANNOTATION_CLASS) +annotation class OnlyForUseByGeneratedProtoCode diff --git a/tools/go-generator/cmd/generator/_protobuf/java/kotlin/src/test/kotlin/com/google/protobuf/DslMapTest.kt b/tools/go-generator/cmd/generator/_protobuf/java/kotlin/src/test/kotlin/com/google/protobuf/DslMapTest.kt new file mode 100644 index 0000000..e7f7a19 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/kotlin/src/test/kotlin/com/google/protobuf/DslMapTest.kt @@ -0,0 +1,194 @@ +// 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. + +package com.google.protobuf.kotlin + +import com.google.common.testing.EqualsTester +import com.google.common.truth.Truth.assertThat +import kotlin.test.assertFailsWith +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +@RunWith(JUnit4::class) +@OptIn(OnlyForUseByGeneratedProtoCode::class) +class DslMapTest { + class DummyProxy private constructor() : DslProxy() + + @Test + fun matchesMap() { + assertThat(DslMap(mapOf(1 to -1, 2 to -2))) + .containsExactly(1, -1, 2, -2) + } + + @Test + fun reflectsChangesInMap() { + val mutableMap = mutableMapOf(1 to -1, 2 to -2) + val dslMap = DslMap(mutableMap) + mutableMap[3] = -3 + assertThat(dslMap).containsExactly(1, -1, 2, -2, 3, -3).inOrder() + } + + @Test + fun dslMapIsNotMutable() { + val dslMap = DslMap(mutableMapOf(1 to -1)) + assertThat(dslMap is MutableMap<*, *>).isFalse() + } + + @Test + fun dslMapKeysAreNotMutable() { + val dslMap = DslMap(mutableMapOf(1 to -1)) + assertThat(dslMap.keys is MutableSet<*>).isFalse() + } + + @Test + fun dslMapValuesAreNotMutable() { + val dslMap = DslMap(mutableMapOf(1 to -1)) + assertThat(dslMap.values is MutableSet<*>).isFalse() + } + + @Test + fun dslMapEntriesAreNotMutable() { + val dslMap = DslMap(mutableMapOf(1 to -1)) + assertThat(dslMap.entries is MutableSet<*>).isFalse() + } + + @Test + fun dslMapEntryObjectsAreNotMutable() { + val dslMap = DslMap(mutableMapOf(1 to -1)) + assertThat(dslMap.entries.single() is MutableMap.MutableEntry<*, *>).isFalse() + } + + @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "UNCHECKED_CAST") + @Test + fun dslMapIsNotEvenSecretlyMutable() { + val dslMap = DslMap(mutableMapOf(1 to -1)) + val dslMapAsJavaUtilMap = dslMap as java.util.Map + assertFailsWith { + dslMapAsJavaUtilMap.put(2, -2) + } + } + + @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "UNCHECKED_CAST") + @Test + fun dslMapKeysAreNotEvenSecretlyMutable() { + val dslMap = DslMap(mutableMapOf(1 to -1)) + val dslMapKeysAsJavaUtilSet = dslMap.keys as java.util.Set + assertFailsWith { + dslMapKeysAsJavaUtilSet.remove(1) + } + } + + @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "UNCHECKED_CAST") + @Test + fun dslMapKeysIteratorIsNotEvenSecretlyMutable() { + val dslMap = DslMap(mutableMapOf(1 to -1)) + val dslMapKeysAsJavaUtilSet = dslMap.keys as java.util.Set + val itr = dslMapKeysAsJavaUtilSet.iterator() + itr.next() + assertFailsWith { + itr.remove() + } + } + + @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "UNCHECKED_CAST") + @Test + fun dslMapValuesAreNotEvenSecretlyMutable() { + val dslMap = DslMap(mutableMapOf(1 to -1)) + val dslMapValuesAsJavaUtilCollection = dslMap.values as java.util.Collection + assertFailsWith { + dslMapValuesAsJavaUtilCollection.remove(1) + } + } + + @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "UNCHECKED_CAST") + @Test + fun dslMapValuesIteratorIsNotEvenSecretlyMutable() { + val dslMap = DslMap(mutableMapOf(1 to -1)) + val dslMapValuesAsJavaUtilCollection = dslMap.values as java.util.Collection + val itr = dslMapValuesAsJavaUtilCollection.iterator() + itr.next() + assertFailsWith { + itr.remove() + } + } + + @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "UNCHECKED_CAST") + @Test + fun dslMapEntriesAreNotEvenSecretlyMutable() { + val dslMap = DslMap(mutableMapOf(1 to -1)) + val dslMapEntriesAsJavaUtilSet = dslMap.entries as java.util.Set> + val entry = dslMap.entries.single() + assertFailsWith { + dslMapEntriesAsJavaUtilSet.remove(entry) + } + } + + @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "UNCHECKED_CAST") + @Test + fun dslMapEntriesIteratorIsNotEvenSecretlyMutable() { + val dslMap = DslMap(mutableMapOf(1 to -1)) + val dslMapEntriesAsJavaUtilSet = dslMap.entries as java.util.Set> + val itr = dslMapEntriesAsJavaUtilSet.iterator() + itr.next() + assertFailsWith { + itr.remove() + } + } + + @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "UNCHECKED_CAST") + @Test + fun dslMapEntryObjectsAreNotEvenSecretlyMutable() { + val dslMap = DslMap(mutableMapOf(1 to -1)) + val dslMapEntryAsJavaUtilMapEntry = dslMap.entries.single() as java.util.Map.Entry + assertFailsWith { + dslMapEntryAsJavaUtilMapEntry.value = 2 + } + } + + @Test + fun expectedToString() { + assertThat(DslMap(mapOf(1 to 2, 2 to 3)).toString()) + .isEqualTo("{1=2, 2=3}") + } + + @Test + fun equality() { + EqualsTester() + .addEqualityGroup(DslMap(mapOf(1 to 2, 2 to 3)), mapOf(1 to 2, 2 to 3)) + .addEqualityGroup(DslMap(mapOf(1 to 3, 2 to 3)), mapOf(1 to 3, 2 to 3)) + .addEqualityGroup( + DslMap(emptyMap()), + DslMap(emptyMap()), + emptyMap() + ) + .testEquals() + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/java/pom.xml b/tools/go-generator/cmd/generator/_protobuf/java/pom.xml new file mode 100644 index 0000000..e102597 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/pom.xml @@ -0,0 +1,287 @@ + + + 4.0.0 + + com.google.protobuf + protobuf-parent + 3.19.4 + pom + + Protocol Buffers [Parent] + 2008 + https://developers.google.com/protocol-buffers/ + + Protocol Buffers are a way of encoding structured data in an efficient yet + extensible format. + + + + + haon + Hao Nguyen + haon@google.com + Google + https://cloud.google.com + America/Los_Angeles + + + + + UTF-8 + UTF-8 + + + ${project.basedir}/../.. + ${protobuf.basedir}/src + ${protobuf.source.dir}/protoc + src/test/proto + ${project.build.directory}/generated-sources + ${project.build.directory}/generated-test-sources + + + + + BSD-3-Clause + https://opensource.org/licenses/BSD-3-Clause + repo + + + + + https://github.com/protocolbuffers/protobuf + scm:git:https://github.com/protocolbuffers/protobuf.git + + + + + sonatype-nexus-staging + https://oss.sonatype.org/content/repositories/snapshots + + + sonatype-nexus-staging + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + + + + + com.google.protobuf + protobuf-bom + ${project.version} + pom + import + + + junit + junit + 4.13.2 + test + + + org.easymock + easymock + 3.2 + test + + + com.google.guava + guava + 30.1.1-android + + + com.google.guava + guava-testlib + 30.1.1-android + test + + + com.google.truth + truth + 1.1.2 + test + + + + + + + + + maven-compiler-plugin + 3.6.1 + + 1.7 + 1.7 + + + + maven-source-plugin + 2.4 + + + attach-sources + + jar-no-fork + + + + + + maven-javadoc-plugin + 2.10.3 + + + attach-javadocs + + jar + + + false + + + + + + maven-jar-plugin + 2.6 + + + org.codehaus.mojo + build-helper-maven-plugin + 1.10 + + + org.apache.felix + maven-bundle-plugin + 3.0.1 + + + maven-antrun-plugin + 3.0.0 + + + maven-surefire-plugin + 3.0.0-M5 + + + org.codehaus.mojo + animal-sniffer-maven-plugin + 1.20 + + + + + + + org.codehaus.mojo + animal-sniffer-maven-plugin + + + net.sf.androidscents.signature + android-api-level-14 + 4.0_r4 + + + sun.misc.Unsafe + + + + + android + test + + check + + + + + + + + + + release + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.3 + + + attach-javadocs + + jar + + + false + + + + + + maven-gpg-plugin + 1.6 + + + sign-artifacts + verify + + sign + + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.6 + true + + sonatype-nexus-staging + https://oss.sonatype.org/ + false + + + + org.jetbrains.dokka + dokka-maven-plugin + 1.4.32 + + + prepare-package + + javadocJar + + + + + + + + + + + bom + lite + core + util + kotlin + kotlin-lite + + + diff --git a/tools/go-generator/cmd/generator/_protobuf/java/util/src/main/java/com/google/protobuf/util/Structs.java b/tools/go-generator/cmd/generator/_protobuf/java/util/src/main/java/com/google/protobuf/util/Structs.java new file mode 100644 index 0000000..b1696ec --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/java/util/src/main/java/com/google/protobuf/util/Structs.java @@ -0,0 +1,65 @@ +// 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. + +package com.google.protobuf.util; + +import com.google.protobuf.Struct; +import com.google.protobuf.Value; + +/** Utilities to help create {@code google.protobuf.Struct} messages. */ +public final class Structs { + + /** + * Returns a struct containing the key-value pair. + */ + public static Struct of(String k1, Value v1) { + return Struct.newBuilder().putFields(k1, v1).build(); + } + + /** + * Returns a struct containing each of the key-value pairs. + * + *

Providing duplicate keys is undefined behavior. + */ + public static Struct of(String k1, Value v1, String k2, Value v2) { + return Struct.newBuilder().putFields(k1, v1).putFields(k2, v2).build(); + } + + /** + * Returns a struct containing each of the key-value pairs. + * + *

Providing duplicate keys is undefined behavior. + */ + public static Struct of(String k1, Value v1, String k2, Value v2, String k3, Value v3) { + return Struct.newBuilder().putFields(k1, v1).putFields(k2, v2).putFields(k3, v3).build(); + } + + private Structs() {} +} diff --git a/tools/go-generator/cmd/generator/_protobuf/js/commonjs/jasmine.json b/tools/go-generator/cmd/generator/_protobuf/js/commonjs/jasmine.json new file mode 100644 index 0000000..666b8ed --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/js/commonjs/jasmine.json @@ -0,0 +1,9 @@ +{ + "spec_dir": "", + "spec_files": [ + "*_test.js", + "binary/proto_test.js" + ], + "helpers": [ + ] +} diff --git a/tools/go-generator/cmd/generator/_protobuf/js/commonjs/test6/test6.proto b/tools/go-generator/cmd/generator/_protobuf/js/commonjs/test6/test6.proto new file mode 100644 index 0000000..a060925 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/js/commonjs/test6/test6.proto @@ -0,0 +1,40 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2016 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +option java_package = "com.google.apps.jspb.proto"; +option java_multiple_files = true; + +package jspb.test.importing; + +message ImportedMessage { + string string_value = 1; +} diff --git a/tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.0.0/commonjs/import_test.js b/tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.0.0/commonjs/import_test.js new file mode 100644 index 0000000..ffa34fe --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.0.0/commonjs/import_test.js @@ -0,0 +1,52 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2016 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. + +// Test suite is written using Jasmine -- see http://jasmine.github.io/ + + + +var googleProtobuf = require('google-protobuf'); +var asserts = require('closure_asserts_commonjs'); +var global = Function('return this')(); + +// Bring asserts into the global namespace. +googleProtobuf.object.extend(global, asserts); +googleProtobuf.exportSymbol('jspb.Message', googleProtobuf.Message, global); + +var test7_pb = require('./test7/test7_pb'); +googleProtobuf.exportSymbol('proto.jspb.test.framing.FramingMessage', test7_pb.FramingMessage, global); + +describe('Import test suite', function() { + it('testImportedMessage', function() { + var framing1 = new proto.jspb.test.framing.FramingMessage([]); + var framing2 = new proto.jspb.test.framing.FramingMessage([]); + assertObjectEquals(framing1.toObject(), framing2.toObject()); + }); +}); diff --git a/tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.0.0/message_test.js b/tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.0.0/message_test.js new file mode 100644 index 0000000..79a12e0 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.0.0/message_test.js @@ -0,0 +1,1081 @@ +// 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. + +// Test suite is written using Jasmine -- see http://jasmine.github.io/ + +goog.setTestOnly(); + +goog.require('goog.json'); +goog.require('goog.testing.asserts'); +goog.require('goog.userAgent'); + +// CommonJS-LoadFromFile: google-protobuf jspb +goog.require('jspb.Message'); + +// CommonJS-LoadFromFile: test5_pb proto.jspb.exttest.beta +goog.require('proto.jspb.exttest.beta.floatingStrField'); + +// CommonJS-LoadFromFile: test3_pb proto.jspb.exttest +goog.require('proto.jspb.exttest.floatingMsgField'); + +// CommonJS-LoadFromFile: test4_pb proto.jspb.exttest +goog.require('proto.jspb.exttest.floatingMsgFieldTwo'); + +// CommonJS-LoadFromFile: test_pb proto.jspb.test +goog.require('proto.jspb.test.CloneExtension'); +goog.require('proto.jspb.test.Complex'); +goog.require('proto.jspb.test.DefaultValues'); +goog.require('proto.jspb.test.Empty'); +goog.require('proto.jspb.test.EnumContainer'); +goog.require('proto.jspb.test.floatingMsgField'); +goog.require('proto.jspb.test.FloatingPointFields'); +goog.require('proto.jspb.test.floatingStrField'); +goog.require('proto.jspb.test.HasExtensions'); +goog.require('proto.jspb.test.IndirectExtension'); +goog.require('proto.jspb.test.IsExtension'); +goog.require('proto.jspb.test.OptionalFields'); +goog.require('proto.jspb.test.OuterEnum'); +goog.require('proto.jspb.test.OuterMessage.Complex'); +goog.require('proto.jspb.test.Simple1'); +goog.require('proto.jspb.test.Simple2'); +goog.require('proto.jspb.test.SpecialCases'); +goog.require('proto.jspb.test.TestClone'); +goog.require('proto.jspb.test.TestEndsWithBytes'); +goog.require('proto.jspb.test.TestGroup'); +goog.require('proto.jspb.test.TestGroup1'); +goog.require('proto.jspb.test.TestMessageWithOneof'); +goog.require('proto.jspb.test.TestReservedNames'); +goog.require('proto.jspb.test.TestReservedNamesExtension'); + +// CommonJS-LoadFromFile: test2_pb proto.jspb.test +goog.require('proto.jspb.test.ExtensionMessage'); +goog.require('proto.jspb.test.TestExtensionsMessage'); + + + + +describe('Message test suite', function() { + it('testEmptyProto', function() { + var empty1 = new proto.jspb.test.Empty([]); + var empty2 = new proto.jspb.test.Empty([]); + assertObjectEquals({}, empty1.toObject()); + assertObjectEquals('Message should not be corrupted:', empty2, empty1); + }); + + it('testTopLevelEnum', function() { + var response = new proto.jspb.test.EnumContainer([]); + response.setOuterEnum(proto.jspb.test.OuterEnum.FOO); + assertEquals(proto.jspb.test.OuterEnum.FOO, response.getOuterEnum()); + }); + + it('testByteStrings', function() { + var data = new proto.jspb.test.DefaultValues([]); + data.setBytesField('some_bytes'); + assertEquals('some_bytes', data.getBytesField()); + }); + + it('testComplexConversion', function() { + var data1 = ['a',,, [, 11], [[, 22], [, 33]],, ['s1', 's2'],, 1]; + var data2 = ['a',,, [, 11], [[, 22], [, 33]],, ['s1', 's2'],, 1]; + var foo = new proto.jspb.test.Complex(data1); + var bar = new proto.jspb.test.Complex(data2); + var result = foo.toObject(); + assertObjectEquals({ + aString: 'a', + anOutOfOrderBool: 1, + aNestedMessage: { + anInt: 11 + }, + aRepeatedMessageList: [{anInt: 22}, {anInt: 33}], + aRepeatedStringList: ['s1', 's2'] + }, result); + + // Now test with the jspb instances included. + result = foo.toObject(true /* opt_includeInstance */); + assertObjectEquals({ + aString: 'a', + anOutOfOrderBool: 1, + aNestedMessage: { + anInt: 11, + $jspbMessageInstance: foo.getANestedMessage() + }, + aRepeatedMessageList: [ + {anInt: 22, $jspbMessageInstance: foo.getARepeatedMessageList()[0]}, + {anInt: 33, $jspbMessageInstance: foo.getARepeatedMessageList()[1]} + ], + aRepeatedStringList: ['s1', 's2'], + $jspbMessageInstance: foo + }, result); + + }); + + it('testMissingFields', function() { + var foo = new proto.jspb.test.Complex([ + undefined, undefined, undefined, [], + undefined, undefined, undefined, undefined]); + var bar = new proto.jspb.test.Complex([ + undefined, undefined, undefined, [], + undefined, undefined, undefined, undefined]); + var result = foo.toObject(); + assertObjectEquals({ + aString: undefined, + anOutOfOrderBool: undefined, + aNestedMessage: { + anInt: undefined + }, + // Note: JsPb converts undefined repeated fields to empty arrays. + aRepeatedMessageList: [], + aRepeatedStringList: [] + }, result); + + }); + + it('testNestedComplexMessage', function() { + // Instantiate the message and set a unique field, just to ensure that we + // are not getting jspb.test.Complex instead. + var msg = new proto.jspb.test.OuterMessage.Complex(); + msg.setInnerComplexField(5); + }); + + it('testSpecialCases', function() { + // Note: Some property names are reserved in JavaScript. + // These names are converted to the Js property named pb_. + var special = + new proto.jspb.test.SpecialCases(['normal', 'default', 'function', + 'var']); + var result = special.toObject(); + assertObjectEquals({ + normal: 'normal', + pb_default: 'default', + pb_function: 'function', + pb_var: 'var' + }, result); + }); + + it('testDefaultValues', function() { + var defaultString = "default<>\'\"abc"; + var response = new proto.jspb.test.DefaultValues(); + + // Test toObject + var expectedObject = { + stringField: defaultString, + boolField: true, + intField: 11, + enumField: 13, + emptyField: '', + bytesField: 'bW9v' + }; + assertObjectEquals(expectedObject, response.toObject()); + + + // Test getters + response = new proto.jspb.test.DefaultValues(); + assertEquals(defaultString, response.getStringField()); + assertEquals(true, response.getBoolField()); + assertEquals(11, response.getIntField()); + assertEquals(13, response.getEnumField()); + assertEquals('', response.getEmptyField()); + assertEquals('bW9v', response.getBytesField()); + + function makeDefault(values) { + return new proto.jspb.test.DefaultValues(values); + } + + // Test with undefined values, + // Use push to workaround IE treating undefined array elements as holes. + response = makeDefault([undefined, undefined, undefined, undefined]); + assertEquals(defaultString, response.getStringField()); + assertEquals(true, response.getBoolField()); + assertEquals(11, response.getIntField()); + assertEquals(13, response.getEnumField()); + assertFalse(response.hasStringField()); + assertFalse(response.hasBoolField()); + assertFalse(response.hasIntField()); + assertFalse(response.hasEnumField()); + + // Test with null values, as would be returned by a JSON serializer. + response = makeDefault([null, null, null, null]); + assertEquals(defaultString, response.getStringField()); + assertEquals(true, response.getBoolField()); + assertEquals(11, response.getIntField()); + assertEquals(13, response.getEnumField()); + assertFalse(response.hasStringField()); + assertFalse(response.hasBoolField()); + assertFalse(response.hasIntField()); + assertFalse(response.hasEnumField()); + + // Test with false-like values. + response = makeDefault(['', false, 0, 0]); + assertEquals('', response.getStringField()); + assertEquals(false, response.getBoolField()); + assertEquals(true, response.getIntField() == 0); + assertEquals(true, response.getEnumField() == 0); + assertTrue(response.hasStringField()); + assertTrue(response.hasBoolField()); + assertTrue(response.hasIntField()); + assertTrue(response.hasEnumField()); + + // Test that clearing the values reverts them to the default state. + response = makeDefault(['blah', false, 111, 77]); + response.clearStringField(); response.clearBoolField(); + response.clearIntField(); response.clearEnumField(); + assertEquals(defaultString, response.getStringField()); + assertEquals(true, response.getBoolField()); + assertEquals(11, response.getIntField()); + assertEquals(13, response.getEnumField()); + assertFalse(response.hasStringField()); + assertFalse(response.hasBoolField()); + assertFalse(response.hasIntField()); + assertFalse(response.hasEnumField()); + + // Test that setFoo(null) clears the values. + response = makeDefault(['blah', false, 111, 77]); + response.setStringField(null); response.setBoolField(null); + response.setIntField(undefined); response.setEnumField(undefined); + assertEquals(defaultString, response.getStringField()); + assertEquals(true, response.getBoolField()); + assertEquals(11, response.getIntField()); + assertEquals(13, response.getEnumField()); + assertFalse(response.hasStringField()); + assertFalse(response.hasBoolField()); + assertFalse(response.hasIntField()); + assertFalse(response.hasEnumField()); + }); + + it('testMessageRegistration', function() { + // goog.require(SomeResponse) will include its library, which will in + // turn add SomeResponse to the message registry. + assertEquals(jspb.Message.registry_['res'], proto.jspb.test.SomeResponse); + }); + + it('testClearFields', function() { + var data = ['str', true, [11], [[22], [33]], ['s1', 's2']]; + var foo = new proto.jspb.test.OptionalFields(data); + foo.clearAString(); + foo.clearABool(); + foo.clearANestedMessage(); + foo.clearARepeatedMessageList(); + foo.clearARepeatedStringList(); + assertEquals('', foo.getAString()); + assertEquals(false, foo.getABool()); + assertUndefined(foo.getANestedMessage()); + assertFalse(foo.hasAString()); + assertFalse(foo.hasABool()); + assertObjectEquals([], foo.getARepeatedMessageList()); + assertObjectEquals([], foo.getARepeatedStringList()); + // NOTE: We want the missing fields in 'expected' to be undefined, + // but we actually get a sparse array instead. We could use something + // like [1,undefined,2] to avoid this, except that this is still + // sparse on IE. No comment... + var expected = [,,, [], []]; + expected[0] = expected[1] = expected[2] = undefined; + assertObjectEquals(expected, foo.toArray()); + + // Test set(null). We could deprecated this in favor of clear(), but + // it's also convenient to have. + data = ['str', true, [11], [[22], [33]], ['s1', 's2']]; + foo = new proto.jspb.test.OptionalFields(data); + foo.setAString(null); + foo.setABool(null); + foo.setANestedMessage(null); + foo.setARepeatedMessageList(null); + foo.setARepeatedStringList(null); + assertEquals('', foo.getAString()); + assertEquals(false, foo.getABool()); + assertNull(foo.getANestedMessage()); + assertFalse(foo.hasAString()); + assertFalse(foo.hasABool()); + assertObjectEquals([], foo.getARepeatedMessageList()); + assertObjectEquals([], foo.getARepeatedStringList()); + assertObjectEquals([null, null, null, [], []], foo.toArray()); + + // Test set(undefined). Again, not something we really need, and not + // supported directly by our typing, but it should 'do the right thing'. + data = ['str', true, [11], [[22], [33]], ['s1', 's2']]; + foo = new proto.jspb.test.OptionalFields(data); + foo.setAString(undefined); + foo.setABool(undefined); + foo.setANestedMessage(undefined); + foo.setARepeatedMessageList(undefined); + foo.setARepeatedStringList(undefined); + assertEquals('', foo.getAString()); + assertEquals(false, foo.getABool()); + assertUndefined(foo.getANestedMessage()); + assertFalse(foo.hasAString()); + assertFalse(foo.hasABool()); + assertObjectEquals([], foo.getARepeatedMessageList()); + assertObjectEquals([], foo.getARepeatedStringList()); + expected = [,,, [], []]; + expected[0] = expected[1] = expected[2] = undefined; + assertObjectEquals(expected, foo.toArray()); + }); + + it('testDifferenceRawObject', function() { + var p1 = new proto.jspb.test.HasExtensions(['hi', 'diff', {}]); + var p2 = new proto.jspb.test.HasExtensions(['hi', 'what', + {1000: 'unique'}]); + var diff = /** @type {proto.jspb.test.HasExtensions} */ + (jspb.Message.difference(p1, p2)); + assertEquals('', diff.getStr1()); + assertEquals('what', diff.getStr2()); + assertEquals('', diff.getStr3()); + assertEquals('unique', diff.extensionObject_[1000]); + }); + + it('testEqualsSimple', function() { + var s1 = new proto.jspb.test.Simple1(['hi']); + assertTrue(jspb.Message.equals(s1, new proto.jspb.test.Simple1(['hi']))); + assertFalse(jspb.Message.equals(s1, new proto.jspb.test.Simple1(['bye']))); + var s1b = new proto.jspb.test.Simple1(['hi', ['hello']]); + assertTrue(jspb.Message.equals(s1b, + new proto.jspb.test.Simple1(['hi', ['hello']]))); + assertTrue(jspb.Message.equals(s1b, + new proto.jspb.test.Simple1(['hi', ['hello', undefined, + undefined, undefined]]))); + assertFalse(jspb.Message.equals(s1b, + new proto.jspb.test.Simple1(['no', ['hello']]))); + // Test with messages of different types + var s2 = new proto.jspb.test.Simple2(['hi']); + assertFalse(jspb.Message.equals(s1, s2)); + }); + + it('testEquals_softComparison', function() { + var s1 = new proto.jspb.test.Simple1(['hi', [], null]); + assertTrue(jspb.Message.equals(s1, + new proto.jspb.test.Simple1(['hi', []]))); + + var s1b = new proto.jspb.test.Simple1(['hi', [], true]); + assertTrue(jspb.Message.equals(s1b, + new proto.jspb.test.Simple1(['hi', [], 1]))); + }); + + it('testEqualsComplex', function() { + var data1 = ['a',,, [, 11], [[, 22], [, 33]],, ['s1', 's2'],, 1]; + var data2 = ['a',,, [, 11], [[, 22], [, 34]],, ['s1', 's2'],, 1]; + var data3 = ['a',,, [, 11], [[, 22]],, ['s1', 's2'],, 1]; + var data4 = ['hi']; + var c1a = new proto.jspb.test.Complex(data1); + var c1b = new proto.jspb.test.Complex(data1); + var c2 = new proto.jspb.test.Complex(data2); + var c3 = new proto.jspb.test.Complex(data3); + var s1 = new proto.jspb.test.Simple1(data4); + + assertTrue(jspb.Message.equals(c1a, c1b)); + assertFalse(jspb.Message.equals(c1a, c2)); + assertFalse(jspb.Message.equals(c2, c3)); + assertFalse(jspb.Message.equals(c1a, s1)); + }); + + it('testEqualsExtensionsConstructed', function() { + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions([]), + new proto.jspb.test.HasExtensions([{}]) + )); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]) + )); + assertFalse(jspb.Message.equals( + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'b'}]}]) + )); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}]) + )); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions([,,, {100: [{200: 'a'}]}]) + )); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions([,,, {100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}]) + )); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions(['hi',,, {100: [{200: 'a'}]}]) + )); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions(['hi',,, {100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]) + )); + }); + + it('testEqualsExtensionsUnconstructed', function() { + assertTrue(jspb.Message.compareFields([], [{}])); + assertTrue(jspb.Message.compareFields([,,, {}], [])); + assertTrue(jspb.Message.compareFields([,,, {}], [,, {}])); + assertTrue(jspb.Message.compareFields( + ['hi', {100: [{200: 'a'}]}], ['hi', {100: [{200: 'a'}]}])); + assertFalse(jspb.Message.compareFields( + ['hi', {100: [{200: 'a'}]}], ['hi', {100: [{200: 'b'}]}])); + assertTrue(jspb.Message.compareFields( + [{100: [{200: 'a'}]}], [{100: [{200: 'a'}]}])); + assertTrue(jspb.Message.compareFields( + [{100: [{200: 'a'}]}], [,,, {100: [{200: 'a'}]}])); + assertTrue(jspb.Message.compareFields( + [,,, {100: [{200: 'a'}]}], [{100: [{200: 'a'}]}])); + assertTrue(jspb.Message.compareFields( + ['hi', {100: [{200: 'a'}]}], ['hi',,, {100: [{200: 'a'}]}])); + assertTrue(jspb.Message.compareFields( + ['hi',,, {100: [{200: 'a'}]}], ['hi', {100: [{200: 'a'}]}])); + }); + + it('testToMap', function() { + var p1 = new proto.jspb.test.Simple1(['k', ['v']]); + var p2 = new proto.jspb.test.Simple1(['k1', ['v1', 'v2']]); + var soymap = jspb.Message.toMap([p1, p2], + proto.jspb.test.Simple1.prototype.getAString, + proto.jspb.test.Simple1.prototype.toObject); + assertEquals('k', soymap['k'].aString); + assertArrayEquals(['v'], soymap['k'].aRepeatedStringList); + var protomap = jspb.Message.toMap([p1, p2], + proto.jspb.test.Simple1.prototype.getAString); + assertEquals('k', protomap['k'].getAString()); + assertArrayEquals(['v'], protomap['k'].getARepeatedStringList()); + }); + + it('testClone', function() { + var supportsUint8Array = + !goog.userAgent.IE || goog.userAgent.isVersionOrHigher('10'); + var original = new proto.jspb.test.TestClone(); + original.setStr('v1'); + var simple1 = new proto.jspb.test.Simple1(['x1', ['y1', 'z1']]); + var simple2 = new proto.jspb.test.Simple1(['x2', ['y2', 'z2']]); + var simple3 = new proto.jspb.test.Simple1(['x3', ['y3', 'z3']]); + original.setSimple1(simple1); + original.setSimple2List([simple2, simple3]); + var bytes1 = supportsUint8Array ? new Uint8Array([1, 2, 3]) : '123'; + original.setBytesField(bytes1); + var extension = new proto.jspb.test.CloneExtension(); + extension.setExt('e1'); + original.setExtension(proto.jspb.test.IsExtension.extField, extension); + var clone = original.cloneMessage(); + assertArrayEquals(['v1',, ['x1', ['y1', 'z1']],, + [['x2', ['y2', 'z2']], ['x3', ['y3', 'z3']]], bytes1,, { 100: [, 'e1'] }], + clone.toArray()); + clone.setStr('v2'); + var simple4 = new proto.jspb.test.Simple1(['a1', ['b1', 'c1']]); + var simple5 = new proto.jspb.test.Simple1(['a2', ['b2', 'c2']]); + var simple6 = new proto.jspb.test.Simple1(['a3', ['b3', 'c3']]); + clone.setSimple1(simple4); + clone.setSimple2List([simple5, simple6]); + if (supportsUint8Array) { + clone.getBytesField()[0] = 4; + assertObjectEquals(bytes1, original.getBytesField()); + } + var bytes2 = supportsUint8Array ? new Uint8Array([4, 5, 6]) : '456'; + clone.setBytesField(bytes2); + var newExtension = new proto.jspb.test.CloneExtension(); + newExtension.setExt('e2'); + clone.setExtension(proto.jspb.test.CloneExtension.extField, newExtension); + assertArrayEquals(['v2',, ['a1', ['b1', 'c1']],, + [['a2', ['b2', 'c2']], ['a3', ['b3', 'c3']]], bytes2,, { 100: [, 'e2'] }], + clone.toArray()); + assertArrayEquals(['v1',, ['x1', ['y1', 'z1']],, + [['x2', ['y2', 'z2']], ['x3', ['y3', 'z3']]], bytes1,, { 100: [, 'e1'] }], + original.toArray()); + }); + + it('testCopyInto', function() { + var supportsUint8Array = + !goog.userAgent.IE || goog.userAgent.isVersionOrHigher('10'); + var original = new proto.jspb.test.TestClone(); + original.setStr('v1'); + var dest = new proto.jspb.test.TestClone(); + dest.setStr('override'); + var simple1 = new proto.jspb.test.Simple1(['x1', ['y1', 'z1']]); + var simple2 = new proto.jspb.test.Simple1(['x2', ['y2', 'z2']]); + var simple3 = new proto.jspb.test.Simple1(['x3', ['y3', 'z3']]); + var destSimple1 = new proto.jspb.test.Simple1(['ox1', ['oy1', 'oz1']]); + var destSimple2 = new proto.jspb.test.Simple1(['ox2', ['oy2', 'oz2']]); + var destSimple3 = new proto.jspb.test.Simple1(['ox3', ['oy3', 'oz3']]); + original.setSimple1(simple1); + original.setSimple2List([simple2, simple3]); + dest.setSimple1(destSimple1); + dest.setSimple2List([destSimple2, destSimple3]); + var bytes1 = supportsUint8Array ? new Uint8Array([1, 2, 3]) : '123'; + var bytes2 = supportsUint8Array ? new Uint8Array([4, 5, 6]) : '456'; + original.setBytesField(bytes1); + dest.setBytesField(bytes2); + var extension = new proto.jspb.test.CloneExtension(); + extension.setExt('e1'); + original.setExtension(proto.jspb.test.CloneExtension.extField, extension); + + jspb.Message.copyInto(original, dest); + assertArrayEquals(original.toArray(), dest.toArray()); + assertEquals('x1', dest.getSimple1().getAString()); + assertEquals('e1', + dest.getExtension(proto.jspb.test.CloneExtension.extField).getExt()); + dest.getSimple1().setAString('new value'); + assertNotEquals(dest.getSimple1().getAString(), + original.getSimple1().getAString()); + if (supportsUint8Array) { + dest.getBytesField()[0] = 7; + assertObjectEquals(bytes1, original.getBytesField()); + assertObjectEquals(new Uint8Array([7, 2, 3]), dest.getBytesField()); + } else { + dest.setBytesField('789'); + assertObjectEquals(bytes1, original.getBytesField()); + assertObjectEquals('789', dest.getBytesField()); + } + dest.getExtension(proto.jspb.test.CloneExtension.extField). + setExt('new value'); + assertNotEquals( + dest.getExtension(proto.jspb.test.CloneExtension.extField).getExt(), + original.getExtension( + proto.jspb.test.CloneExtension.extField).getExt()); + }); + + it('testCopyInto_notSameType', function() { + var a = new proto.jspb.test.TestClone(); + var b = new proto.jspb.test.Simple1(['str', ['s1', 's2']]); + + var e = assertThrows(function() { + jspb.Message.copyInto(a, b); + }); + assertContains('should have the same type', e.message); + }); + + it('testExtensions', function() { + var extension1 = new proto.jspb.test.IsExtension(['ext1field']); + var extension2 = new proto.jspb.test.Simple1(['str', ['s1', 's2']]); + var extendable = new proto.jspb.test.HasExtensions(['v1', 'v2', 'v3']); + extendable.setExtension(proto.jspb.test.IsExtension.extField, extension1); + extendable.setExtension(proto.jspb.test.IndirectExtension.simple, + extension2); + extendable.setExtension(proto.jspb.test.IndirectExtension.str, 'xyzzy'); + extendable.setExtension(proto.jspb.test.IndirectExtension.repeatedStrList, + ['a', 'b']); + var s1 = new proto.jspb.test.Simple1(['foo', ['s1', 's2']]); + var s2 = new proto.jspb.test.Simple1(['bar', ['t1', 't2']]); + extendable.setExtension( + proto.jspb.test.IndirectExtension.repeatedSimpleList, + [s1, s2]); + assertObjectEquals(extension1, + extendable.getExtension(proto.jspb.test.IsExtension.extField)); + assertObjectEquals(extension2, + extendable.getExtension(proto.jspb.test.IndirectExtension.simple)); + assertObjectEquals('xyzzy', + extendable.getExtension(proto.jspb.test.IndirectExtension.str)); + assertObjectEquals(['a', 'b'], extendable.getExtension( + proto.jspb.test.IndirectExtension.repeatedStrList)); + assertObjectEquals([s1, s2], extendable.getExtension( + proto.jspb.test.IndirectExtension.repeatedSimpleList)); + // Not supported yet, but it should work... + extendable.setExtension(proto.jspb.test.IndirectExtension.simple, null); + assertNull( + extendable.getExtension(proto.jspb.test.IndirectExtension.simple)); + extendable.setExtension(proto.jspb.test.IndirectExtension.str, null); + assertNull(extendable.getExtension(proto.jspb.test.IndirectExtension.str)); + + + // Extension fields with jspb.ignore = true are ignored. + assertUndefined(proto.jspb.test.IndirectExtension['ignored']); + assertUndefined(proto.jspb.test.HasExtensions['ignoredFloating']); + }); + + it('testFloatingExtensions', function() { + // From an autogenerated container. + var extendable = new proto.jspb.test.HasExtensions(['v1', 'v2', 'v3']); + var extension = new proto.jspb.test.Simple1(['foo', ['s1', 's2']]); + extendable.setExtension(proto.jspb.test.simple1, extension); + assertObjectEquals(extension, + extendable.getExtension(proto.jspb.test.simple1)); + + // From _lib mode. + extension = new proto.jspb.test.ExtensionMessage(['s1']); + extendable = new proto.jspb.test.TestExtensionsMessage([16]); + extendable.setExtension(proto.jspb.test.floatingMsgField, extension); + extendable.setExtension(proto.jspb.test.floatingStrField, 's2'); + assertObjectEquals(extension, + extendable.getExtension(proto.jspb.test.floatingMsgField)); + assertObjectEquals('s2', + extendable.getExtension(proto.jspb.test.floatingStrField)); + assertNotUndefined(proto.jspb.exttest.floatingMsgField); + assertNotUndefined(proto.jspb.exttest.floatingMsgFieldTwo); + assertNotUndefined(proto.jspb.exttest.beta.floatingStrField); + }); + + it('testToObject_extendedObject', function() { + var extension1 = new proto.jspb.test.IsExtension(['ext1field']); + var extension2 = new proto.jspb.test.Simple1(['str', ['s1', 's2'], true]); + var extendable = new proto.jspb.test.HasExtensions(['v1', 'v2', 'v3']); + extendable.setExtension(proto.jspb.test.IsExtension.extField, extension1); + extendable.setExtension(proto.jspb.test.IndirectExtension.simple, + extension2); + extendable.setExtension(proto.jspb.test.IndirectExtension.str, 'xyzzy'); + extendable.setExtension(proto.jspb.test.IndirectExtension.repeatedStrList, + ['a', 'b']); + var s1 = new proto.jspb.test.Simple1(['foo', ['s1', 's2'], true]); + var s2 = new proto.jspb.test.Simple1(['bar', ['t1', 't2'], false]); + extendable.setExtension( + proto.jspb.test.IndirectExtension.repeatedSimpleList, + [s1, s2]); + assertObjectEquals({ + str1: 'v1', str2: 'v2', str3: 'v3', + extField: { ext1: 'ext1field' }, + simple: { + aString: 'str', aRepeatedStringList: ['s1', 's2'], aBoolean: true + }, + str: 'xyzzy', + repeatedStrList: ['a', 'b'], + repeatedSimpleList: [ + { aString: 'foo', aRepeatedStringList: ['s1', 's2'], aBoolean: true}, + { aString: 'bar', aRepeatedStringList: ['t1', 't2'], aBoolean: false} + ] + }, extendable.toObject()); + + // Now, with instances included. + assertObjectEquals({ + str1: 'v1', str2: 'v2', str3: 'v3', + extField: { + ext1: 'ext1field', + $jspbMessageInstance: + extendable.getExtension(proto.jspb.test.IsExtension.extField) + }, + simple: { + aString: 'str', + aRepeatedStringList: ['s1', 's2'], + aBoolean: true, + $jspbMessageInstance: + extendable.getExtension(proto.jspb.test.IndirectExtension.simple) + }, + str: 'xyzzy', + repeatedStrList: ['a', 'b'], + repeatedSimpleList: [{ + aString: 'foo', + aRepeatedStringList: ['s1', 's2'], + aBoolean: true, + $jspbMessageInstance: s1 + }, { + aString: 'bar', + aRepeatedStringList: ['t1', 't2'], + aBoolean: false, + $jspbMessageInstance: s2 + }], + $jspbMessageInstance: extendable + }, extendable.toObject(true /* opt_includeInstance */)); + }); + + it('testInitialization_emptyArray', function() { + var msg = new proto.jspb.test.HasExtensions([]); + if (jspb.Message.MINIMIZE_MEMORY_ALLOCATIONS) { + assertArrayEquals([], msg.toArray()); + } else { + // Extension object is created past all regular fields. + assertArrayEquals([,,, {}], msg.toArray()); + } + }); + + it('testInitialization_justExtensionObject', function() { + var msg = new proto.jspb.test.Empty([{1: 'hi'}]); + // The extensionObject is not moved from its original location. + assertArrayEquals([{1: 'hi'}], msg.toArray()); + }); + + it('testInitialization_incompleteList', function() { + var msg = new proto.jspb.test.Empty([1, {4: 'hi'}]); + // The extensionObject is not moved from its original location. + assertArrayEquals([1, {4: 'hi'}], msg.toArray()); + }); + + it('testInitialization_forwardCompatible', function() { + var msg = new proto.jspb.test.Empty([1, 2, 3, {1: 'hi'}]); + assertArrayEquals([1, 2, 3, {1: 'hi'}], msg.toArray()); + }); + + it('testExtendedMessageEnsureObject', function() { + var data = new proto.jspb.test.HasExtensions(['str1', + {'a_key': 'an_object'}]); + assertEquals('an_object', data.extensionObject_['a_key']); + }); + + it('testToObject_hasExtensionField', function() { + var data = new proto.jspb.test.HasExtensions(['str1', {100: ['ext1']}]); + var obj = data.toObject(); + assertEquals('str1', obj.str1); + assertEquals('ext1', obj.extField.ext1); + }); + + it('testGetExtension', function() { + var data = new proto.jspb.test.HasExtensions(['str1', {100: ['ext1']}]); + assertEquals('str1', data.getStr1()); + var extension = data.getExtension(proto.jspb.test.IsExtension.extField); + assertNotNull(extension); + assertEquals('ext1', extension.getExt1()); + }); + + it('testSetExtension', function() { + var data = new proto.jspb.test.HasExtensions(); + var extensionMessage = new proto.jspb.test.IsExtension(['is_extension']); + data.setExtension(proto.jspb.test.IsExtension.extField, extensionMessage); + var obj = data.toObject(); + assertNotNull( + data.getExtension(proto.jspb.test.IsExtension.extField)); + assertEquals('is_extension', obj.extField.ext1); + }); + + /** + * Note that group is long deprecated, we only support it because JsPb has + * a goal of being able to generate JS classes for all proto descriptors. + */ + it('testGroups', function() { + var group = new proto.jspb.test.TestGroup(); + var someGroup = new proto.jspb.test.TestGroup.RepeatedGroup(); + someGroup.setId('g1'); + someGroup.setSomeBoolList([true, false]); + group.setRepeatedGroupList([someGroup]); + var groups = group.getRepeatedGroupList(); + assertEquals('g1', groups[0].getId()); + assertObjectEquals([true, false], groups[0].getSomeBoolList()); + assertObjectEquals({id: 'g1', someBoolList: [true, false]}, + groups[0].toObject()); + assertObjectEquals({ + repeatedGroupList: [{id: 'g1', someBoolList: [true, false]}], + requiredGroup: {id: undefined}, + optionalGroup: undefined, + requiredSimple: {aRepeatedStringList: [], aString: undefined}, + optionalSimple: undefined, + id: undefined + }, group.toObject()); + var group1 = new proto.jspb.test.TestGroup1(); + group1.setGroup(someGroup); + assertEquals(someGroup, group1.getGroup()); + }); + + it('testNonExtensionFieldsAfterExtensionRange', function() { + var data = [{'1': 'a_string'}]; + var message = new proto.jspb.test.Complex(data); + assertArrayEquals([], message.getARepeatedStringList()); + }); + + it('testReservedGetterNames', function() { + var message = new proto.jspb.test.TestReservedNames(); + message.setExtension$(11); + message.setExtension(proto.jspb.test.TestReservedNamesExtension.foo, 12); + assertEquals(11, message.getExtension$()); + assertEquals(12, message.getExtension( + proto.jspb.test.TestReservedNamesExtension.foo)); + assertObjectEquals({extension: 11, foo: 12}, message.toObject()); + }); + + it('testInitializeMessageWithUnsetOneof', function() { + var message = new proto.jspb.test.TestMessageWithOneof([]); + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase. + PARTIAL_ONEOF_NOT_SET, + message.getPartialOneofCase()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.RecursiveOneofCase. + RECURSIVE_ONEOF_NOT_SET, + message.getRecursiveOneofCase()); + }); + + it('testInitializeMessageWithSingleValueSetInOneof', function() { + var message = new proto.jspb.test.TestMessageWithOneof([,, 'x']); + + assertEquals('x', message.getPone()); + assertEquals('', message.getPthree()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PONE, + message.getPartialOneofCase()); + }); + + it('testKeepsLastWireValueSetInUnion_multipleValues', function() { + var message = new proto.jspb.test.TestMessageWithOneof([,, 'x',, 'y']); + + assertEquals('', message.getPone()); + assertEquals('y', message.getPthree()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PTHREE, + message.getPartialOneofCase()); + }); + + it('testSettingOneofFieldClearsOthers', function() { + var message = new proto.jspb.test.TestMessageWithOneof; + assertEquals('', message.getPone()); + assertEquals('', message.getPthree()); + assertFalse(message.hasPone()); + assertFalse(message.hasPthree()); + + message.setPone('hi'); + assertEquals('hi', message.getPone()); + assertEquals('', message.getPthree()); + assertTrue(message.hasPone()); + assertFalse(message.hasPthree()); + + message.setPthree('bye'); + assertEquals('', message.getPone()); + assertEquals('bye', message.getPthree()); + assertFalse(message.hasPone()); + assertTrue(message.hasPthree()); + }); + + it('testSettingOneofFieldDoesNotClearFieldsFromOtherUnions', function() { + var other = new proto.jspb.test.TestMessageWithOneof; + var message = new proto.jspb.test.TestMessageWithOneof; + assertEquals('', message.getPone()); + assertEquals('', message.getPthree()); + assertUndefined(message.getRone()); + assertFalse(message.hasPone()); + assertFalse(message.hasPthree()); + + message.setPone('hi'); + message.setRone(other); + assertEquals('hi', message.getPone()); + assertEquals('', message.getPthree()); + assertEquals(other, message.getRone()); + assertTrue(message.hasPone()); + assertFalse(message.hasPthree()); + + message.setPthree('bye'); + assertEquals('', message.getPone()); + assertEquals('bye', message.getPthree()); + assertEquals(other, message.getRone()); + assertFalse(message.hasPone()); + assertTrue(message.hasPthree()); + }); + + it('testUnsetsOneofCaseWhenFieldIsCleared', function() { + var message = new proto.jspb.test.TestMessageWithOneof; + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase. + PARTIAL_ONEOF_NOT_SET, + message.getPartialOneofCase()); + + message.setPone('hi'); + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PONE, + message.getPartialOneofCase()); + + message.clearPone(); + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase. + PARTIAL_ONEOF_NOT_SET, + message.getPartialOneofCase()); + }); + + it('testMessageWithDefaultOneofValues', function() { + var message = new proto.jspb.test.TestMessageWithOneof; + assertEquals(1234, message.getAone()); + assertEquals(0, message.getAtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofACase + .DEFAULT_ONEOF_A_NOT_SET, + message.getDefaultOneofACase()); + + message.setAone(567); + assertEquals(567, message.getAone()); + assertEquals(0, message.getAtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.AONE, + message.getDefaultOneofACase()); + + message.setAtwo(890); + assertEquals(1234, message.getAone()); + assertEquals(890, message.getAtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.ATWO, + message.getDefaultOneofACase()); + + message.clearAtwo(); + assertEquals(1234, message.getAone()); + assertEquals(0, message.getAtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofACase + .DEFAULT_ONEOF_A_NOT_SET, + message.getDefaultOneofACase()); + }); + + it('testMessageWithDefaultOneofValues_defaultNotOnFirstField', function() { + var message = new proto.jspb.test.TestMessageWithOneof; + assertEquals(0, message.getBone()); + assertEquals(1234, message.getBtwo()); + assertFalse(message.hasBone()); + assertFalse(message.hasBtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase + .DEFAULT_ONEOF_B_NOT_SET, + message.getDefaultOneofBCase()); + + message.setBone(2); + assertEquals(2, message.getBone()); + assertEquals(1234, message.getBtwo()); + assertTrue(message.hasBone()); + assertFalse(message.hasBtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BONE, + message.getDefaultOneofBCase()); + + message.setBtwo(3); + assertEquals(0, message.getBone()); + assertFalse(message.hasBone()); + assertTrue(message.hasBtwo()); + assertEquals(3, message.getBtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BTWO, + message.getDefaultOneofBCase()); + + message.clearBtwo(); + assertEquals(0, message.getBone()); + assertFalse(message.hasBone()); + assertFalse(message.hasBtwo()); + assertEquals(1234, message.getBtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase + .DEFAULT_ONEOF_B_NOT_SET, + message.getDefaultOneofBCase()); + }); + + it('testInitializeMessageWithOneofDefaults', function() { + var message = + new proto.jspb.test.TestMessageWithOneof(new Array(9).concat(567)); + assertEquals(567, message.getAone()); + assertEquals(0, message.getAtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.AONE, + message.getDefaultOneofACase()); + + message = + new proto.jspb.test.TestMessageWithOneof(new Array(10).concat(890)); + assertEquals(1234, message.getAone()); + assertEquals(890, message.getAtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.ATWO, + message.getDefaultOneofACase()); + + message = + new proto.jspb.test.TestMessageWithOneof(new Array(9).concat(567, 890)); + assertEquals(1234, message.getAone()); + assertEquals(890, message.getAtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.ATWO, + message.getDefaultOneofACase()); + }); + + it('testInitializeMessageWithOneofDefaults_defaultNotSetOnFirstField', + function() { + var message; + + message = + new proto.jspb.test.TestMessageWithOneof(new Array(11).concat(567)); + assertEquals(567, message.getBone()); + assertEquals(1234, message.getBtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BONE, + message.getDefaultOneofBCase()); + + message = + new proto.jspb.test.TestMessageWithOneof(new Array(12).concat(890)); + assertEquals(0, message.getBone()); + assertEquals(890, message.getBtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BTWO, + message.getDefaultOneofBCase()); + + message = new proto.jspb.test.TestMessageWithOneof( + new Array(11).concat(567, 890)); + assertEquals(0, message.getBone()); + assertEquals(890, message.getBtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BTWO, + message.getDefaultOneofBCase()); + }); + + it('testOneofContainingAnotherMessage', function() { + var message = new proto.jspb.test.TestMessageWithOneof; + assertEquals( + proto.jspb.test.TestMessageWithOneof.RecursiveOneofCase. + RECURSIVE_ONEOF_NOT_SET, + message.getRecursiveOneofCase()); + + var other = new proto.jspb.test.TestMessageWithOneof; + message.setRone(other); + assertEquals(other, message.getRone()); + assertEquals('', message.getRtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.RecursiveOneofCase.RONE, + message.getRecursiveOneofCase()); + + message.setRtwo('hi'); + assertUndefined(message.getRone()); + assertEquals('hi', message.getRtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.RecursiveOneofCase.RTWO, + message.getRecursiveOneofCase()); + }); + + it('testQueryingOneofCaseEnsuresOnlyOneFieldIsSetInUnderlyingArray', + function() { + var message = new proto.jspb.test.TestMessageWithOneof; + message.setPone('x'); + assertEquals('x', message.getPone()); + assertEquals('', message.getPthree()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PONE, + message.getPartialOneofCase()); + + var array = message.toArray(); + assertEquals('x', array[2]); + assertUndefined(array[4]); + array[4] = 'y'; + + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PTHREE, + message.getPartialOneofCase()); + assertUndefined(array[2]); + assertEquals('y', array[4]); + }); + + it('testFloatingPointFieldsSupportNan', function() { + var assertNan = function(x) { + assertTrue( + 'Expected ' + x + ' (' + goog.typeOf(x) + ') to be NaN.', + typeof x === 'number' && isNaN(x)); + }; + + var message = new proto.jspb.test.FloatingPointFields([ + 'NaN', 'NaN', ['NaN', 'NaN'], 'NaN', + 'NaN', 'NaN', ['NaN', 'NaN'], 'NaN' + ]); + assertNan(message.getOptionalFloatField()); + assertNan(message.getRequiredFloatField()); + assertNan(message.getRepeatedFloatFieldList()[0]); + assertNan(message.getRepeatedFloatFieldList()[1]); + assertNan(message.getDefaultFloatField()); + assertNan(message.getOptionalDoubleField()); + assertNan(message.getRequiredDoubleField()); + assertNan(message.getRepeatedDoubleFieldList()[0]); + assertNan(message.getRepeatedDoubleFieldList()[1]); + assertNan(message.getDefaultDoubleField()); + }); + +}); diff --git a/tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.0.0/proto3_test.proto b/tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.0.0/proto3_test.proto new file mode 100644 index 0000000..acb6716 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.0.0/proto3_test.proto @@ -0,0 +1,89 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +import "testbinary.proto"; + +package jspb.test; + +message TestProto3 { + int32 optional_int32 = 1; + int64 optional_int64 = 2; + uint32 optional_uint32 = 3; + uint64 optional_uint64 = 4; + sint32 optional_sint32 = 5; + sint64 optional_sint64 = 6; + fixed32 optional_fixed32 = 7; + fixed64 optional_fixed64 = 8; + sfixed32 optional_sfixed32 = 9; + sfixed64 optional_sfixed64 = 10; + float optional_float = 11; + double optional_double = 12; + bool optional_bool = 13; + string optional_string = 14; + bytes optional_bytes = 15; + + ForeignMessage optional_foreign_message = 19; + Proto3Enum optional_foreign_enum = 22; + + repeated int32 repeated_int32 = 31; + repeated int64 repeated_int64 = 32; + repeated uint32 repeated_uint32 = 33; + repeated uint64 repeated_uint64 = 34; + repeated sint32 repeated_sint32 = 35; + repeated sint64 repeated_sint64 = 36; + repeated fixed32 repeated_fixed32 = 37; + repeated fixed64 repeated_fixed64 = 38; + repeated sfixed32 repeated_sfixed32 = 39; + repeated sfixed64 repeated_sfixed64 = 40; + repeated float repeated_float = 41; + repeated double repeated_double = 42; + repeated bool repeated_bool = 43; + repeated string repeated_string = 44; + repeated bytes repeated_bytes = 45; + + repeated ForeignMessage repeated_foreign_message = 49; + repeated Proto3Enum repeated_foreign_enum = 52; + + + oneof oneof_field { + uint32 oneof_uint32 = 111; + ForeignMessage oneof_foreign_message = 112; + string oneof_string = 113; + bytes oneof_bytes = 114; + } +} + +enum Proto3Enum { + PROTO3_FOO = 0; + PROTO3_BAR = 1; + PROTO3_BAZ = 2; +} diff --git a/tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.1.0/binary/proto_test.js b/tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.1.0/binary/proto_test.js new file mode 100644 index 0000000..ff9d972 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.1.0/binary/proto_test.js @@ -0,0 +1,628 @@ +// 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. + +// Test suite is written using Jasmine -- see http://jasmine.github.io/ + +goog.require('goog.crypt.base64'); +goog.require('goog.testing.asserts'); +goog.require('jspb.Message'); + +// CommonJS-LoadFromFile: ../testbinary_pb proto.jspb.test +goog.require('proto.jspb.test.ExtendsWithMessage'); +goog.require('proto.jspb.test.ForeignEnum'); +goog.require('proto.jspb.test.ForeignMessage'); +goog.require('proto.jspb.test.TestAllTypes'); +goog.require('proto.jspb.test.TestExtendable'); +goog.require('proto.jspb.test.extendOptionalBool'); +goog.require('proto.jspb.test.extendOptionalBytes'); +goog.require('proto.jspb.test.extendOptionalDouble'); +goog.require('proto.jspb.test.extendOptionalFixed32'); +goog.require('proto.jspb.test.extendOptionalFixed64'); +goog.require('proto.jspb.test.extendOptionalFloat'); +goog.require('proto.jspb.test.extendOptionalForeignEnum'); +goog.require('proto.jspb.test.extendOptionalInt32'); +goog.require('proto.jspb.test.extendOptionalInt64'); +goog.require('proto.jspb.test.extendOptionalSfixed32'); +goog.require('proto.jspb.test.extendOptionalSfixed64'); +goog.require('proto.jspb.test.extendOptionalSint32'); +goog.require('proto.jspb.test.extendOptionalSint64'); +goog.require('proto.jspb.test.extendOptionalString'); +goog.require('proto.jspb.test.extendOptionalUint32'); +goog.require('proto.jspb.test.extendOptionalUint64'); +goog.require('proto.jspb.test.extendPackedRepeatedBoolList'); +goog.require('proto.jspb.test.extendPackedRepeatedDoubleList'); +goog.require('proto.jspb.test.extendPackedRepeatedFixed32List'); +goog.require('proto.jspb.test.extendPackedRepeatedFixed64List'); +goog.require('proto.jspb.test.extendPackedRepeatedFloatList'); +goog.require('proto.jspb.test.extendPackedRepeatedForeignEnumList'); +goog.require('proto.jspb.test.extendPackedRepeatedInt32List'); +goog.require('proto.jspb.test.extendPackedRepeatedInt64List'); +goog.require('proto.jspb.test.extendPackedRepeatedSfixed32List'); +goog.require('proto.jspb.test.extendPackedRepeatedSfixed64List'); +goog.require('proto.jspb.test.extendPackedRepeatedSint32List'); +goog.require('proto.jspb.test.extendPackedRepeatedSint64List'); +goog.require('proto.jspb.test.extendPackedRepeatedUint32List'); +goog.require('proto.jspb.test.extendPackedRepeatedUint64List'); +goog.require('proto.jspb.test.extendRepeatedBoolList'); +goog.require('proto.jspb.test.extendRepeatedBytesList'); +goog.require('proto.jspb.test.extendRepeatedDoubleList'); +goog.require('proto.jspb.test.extendRepeatedFixed32List'); +goog.require('proto.jspb.test.extendRepeatedFixed64List'); +goog.require('proto.jspb.test.extendRepeatedFloatList'); +goog.require('proto.jspb.test.extendRepeatedForeignEnumList'); +goog.require('proto.jspb.test.extendRepeatedInt32List'); +goog.require('proto.jspb.test.extendRepeatedInt64List'); +goog.require('proto.jspb.test.extendRepeatedSfixed32List'); +goog.require('proto.jspb.test.extendRepeatedSfixed64List'); +goog.require('proto.jspb.test.extendRepeatedSint32List'); +goog.require('proto.jspb.test.extendRepeatedSint64List'); +goog.require('proto.jspb.test.extendRepeatedStringList'); +goog.require('proto.jspb.test.extendRepeatedUint32List'); +goog.require('proto.jspb.test.extendRepeatedUint64List'); + + +var suite = {}; + +var BYTES = new Uint8Array([1, 2, 8, 9]); + +var BYTES_B64 = goog.crypt.base64.encodeByteArray(BYTES); + + +/** + * Helper: fill all fields on a TestAllTypes message. + * @param {proto.jspb.test.TestAllTypes} msg + */ +function fillAllFields(msg) { + msg.setOptionalInt32(-42); + // can be exactly represented by JS number (64-bit double, i.e., 52-bit + // mantissa). + msg.setOptionalInt64(-0x7fffffff00000000); + msg.setOptionalUint32(0x80000000); + msg.setOptionalUint64(0xf000000000000000); + msg.setOptionalSint32(-100); + msg.setOptionalSint64(-0x8000000000000000); + msg.setOptionalFixed32(1234); + msg.setOptionalFixed64(0x1234567800000000); + msg.setOptionalSfixed32(-1234); + msg.setOptionalSfixed64(-0x1234567800000000); + msg.setOptionalFloat(1.5); + msg.setOptionalDouble(-1.5); + msg.setOptionalBool(true); + msg.setOptionalString('hello world'); + msg.setOptionalBytes(BYTES); + msg.setOptionalGroup(new proto.jspb.test.TestAllTypes.OptionalGroup()); + msg.getOptionalGroup().setA(100); + var submsg = new proto.jspb.test.ForeignMessage(); + submsg.setC(16); + msg.setOptionalForeignMessage(submsg); + msg.setOptionalForeignEnum(proto.jspb.test.ForeignEnum.FOREIGN_FOO); + msg.setOneofString('oneof'); + + + msg.setRepeatedInt32List([-42]); + msg.setRepeatedInt64List([-0x7fffffff00000000]); + msg.setRepeatedUint32List([0x80000000]); + msg.setRepeatedUint64List([0xf000000000000000]); + msg.setRepeatedSint32List([-100]); + msg.setRepeatedSint64List([-0x8000000000000000]); + msg.setRepeatedFixed32List([1234]); + msg.setRepeatedFixed64List([0x1234567800000000]); + msg.setRepeatedSfixed32List([-1234]); + msg.setRepeatedSfixed64List([-0x1234567800000000]); + msg.setRepeatedFloatList([1.5]); + msg.setRepeatedDoubleList([-1.5]); + msg.setRepeatedBoolList([true]); + msg.setRepeatedStringList(['hello world']); + msg.setRepeatedBytesList([BYTES, BYTES]); + msg.setRepeatedGroupList([new proto.jspb.test.TestAllTypes.RepeatedGroup()]); + msg.getRepeatedGroupList()[0].setA(100); + submsg = new proto.jspb.test.ForeignMessage(); + submsg.setC(1000); + msg.setRepeatedForeignMessageList([submsg]); + msg.setRepeatedForeignEnumList([proto.jspb.test.ForeignEnum.FOREIGN_FOO]); + + msg.setPackedRepeatedInt32List([-42]); + msg.setPackedRepeatedInt64List([-0x7fffffff00000000]); + msg.setPackedRepeatedUint32List([0x80000000]); + msg.setPackedRepeatedUint64List([0xf000000000000000]); + msg.setPackedRepeatedSint32List([-100]); + msg.setPackedRepeatedSint64List([-0x8000000000000000]); + msg.setPackedRepeatedFixed32List([1234]); + msg.setPackedRepeatedFixed64List([0x1234567800000000]); + msg.setPackedRepeatedSfixed32List([-1234]); + msg.setPackedRepeatedSfixed64List([-0x1234567800000000]); + msg.setPackedRepeatedFloatList([1.5]); + msg.setPackedRepeatedDoubleList([-1.5]); + msg.setPackedRepeatedBoolList([true]); + +} + + +/** + * Helper: compare a bytes field to an expected value + * @param {Uint8Array|string} arr + * @param {Uint8Array} expected + * @return {boolean} + */ +function bytesCompare(arr, expected) { + if (typeof arr === 'string') { + arr = goog.crypt.base64.decodeStringToUint8Array(arr); + } + if (arr.length != expected.length) { + return false; + } + for (var i = 0; i < arr.length; i++) { + if (arr[i] != expected[i]) { + return false; + } + } + return true; +} + + +/** + * Helper: verify contents of given TestAllTypes message as set by + * fillAllFields(). + * @param {proto.jspb.test.TestAllTypes} original + * @param {proto.jspb.test.TestAllTypes} copy + */ +function checkAllFields(original, copy) { + assertTrue(jspb.Message.equals(original, copy)); + + assertEquals(copy.getOptionalInt32(), -42); + assertEquals(copy.getOptionalInt64(), -0x7fffffff00000000); + assertEquals(copy.getOptionalUint32(), 0x80000000); + assertEquals(copy.getOptionalUint64(), 0xf000000000000000); + assertEquals(copy.getOptionalSint32(), -100); + assertEquals(copy.getOptionalSint64(), -0x8000000000000000); + assertEquals(copy.getOptionalFixed32(), 1234); + assertEquals(copy.getOptionalFixed64(), 0x1234567800000000); + assertEquals(copy.getOptionalSfixed32(), -1234); + assertEquals(copy.getOptionalSfixed64(), -0x1234567800000000); + assertEquals(copy.getOptionalFloat(), 1.5); + assertEquals(copy.getOptionalDouble(), -1.5); + assertEquals(copy.getOptionalBool(), true); + assertEquals(copy.getOptionalString(), 'hello world'); + assertEquals(true, bytesCompare(copy.getOptionalBytes(), BYTES)); + assertEquals(true, bytesCompare(copy.getOptionalBytes_asU8(), BYTES)); + assertEquals( + copy.getOptionalBytes_asB64(), goog.crypt.base64.encodeByteArray(BYTES)); + + assertEquals(copy.getOptionalGroup().getA(), 100); + assertEquals(copy.getOptionalForeignMessage().getC(), 16); + assertEquals(copy.getOptionalForeignEnum(), + proto.jspb.test.ForeignEnum.FOREIGN_FOO); + + + assertEquals(copy.getOneofString(), 'oneof'); + assertEquals(copy.getOneofFieldCase(), + proto.jspb.test.TestAllTypes.OneofFieldCase.ONEOF_STRING); + + assertElementsEquals(copy.getRepeatedInt32List(), [-42]); + assertElementsEquals(copy.getRepeatedInt64List(), [-0x7fffffff00000000]); + assertElementsEquals(copy.getRepeatedUint32List(), [0x80000000]); + assertElementsEquals(copy.getRepeatedUint64List(), [0xf000000000000000]); + assertElementsEquals(copy.getRepeatedSint32List(), [-100]); + assertElementsEquals(copy.getRepeatedSint64List(), [-0x8000000000000000]); + assertElementsEquals(copy.getRepeatedFixed32List(), [1234]); + assertElementsEquals(copy.getRepeatedFixed64List(), [0x1234567800000000]); + assertElementsEquals(copy.getRepeatedSfixed32List(), [-1234]); + assertElementsEquals(copy.getRepeatedSfixed64List(), [-0x1234567800000000]); + assertElementsEquals(copy.getRepeatedFloatList(), [1.5]); + assertElementsEquals(copy.getRepeatedDoubleList(), [-1.5]); + assertElementsEquals(copy.getRepeatedBoolList(), [true]); + assertElementsEquals(copy.getRepeatedStringList(), ['hello world']); + assertEquals(copy.getRepeatedBytesList().length, 2); + assertEquals(true, bytesCompare(copy.getRepeatedBytesList_asU8()[0], BYTES)); + assertEquals(true, bytesCompare(copy.getRepeatedBytesList()[0], BYTES)); + assertEquals(true, bytesCompare(copy.getRepeatedBytesList_asU8()[1], BYTES)); + assertEquals(copy.getRepeatedBytesList_asB64()[0], BYTES_B64); + assertEquals(copy.getRepeatedBytesList_asB64()[1], BYTES_B64); + assertEquals(copy.getRepeatedGroupList().length, 1); + assertEquals(copy.getRepeatedGroupList()[0].getA(), 100); + assertEquals(copy.getRepeatedForeignMessageList().length, 1); + assertEquals(copy.getRepeatedForeignMessageList()[0].getC(), 1000); + assertElementsEquals(copy.getRepeatedForeignEnumList(), + [proto.jspb.test.ForeignEnum.FOREIGN_FOO]); + + assertElementsEquals(copy.getPackedRepeatedInt32List(), [-42]); + assertElementsEquals(copy.getPackedRepeatedInt64List(), + [-0x7fffffff00000000]); + assertElementsEquals(copy.getPackedRepeatedUint32List(), [0x80000000]); + assertElementsEquals(copy.getPackedRepeatedUint64List(), + [0xf000000000000000]); + assertElementsEquals(copy.getPackedRepeatedSint32List(), [-100]); + assertElementsEquals(copy.getPackedRepeatedSint64List(), + [-0x8000000000000000]); + assertElementsEquals(copy.getPackedRepeatedFixed32List(), [1234]); + assertElementsEquals(copy.getPackedRepeatedFixed64List(), + [0x1234567800000000]); + assertElementsEquals(copy.getPackedRepeatedSfixed32List(), [-1234]); + assertElementsEquals(copy.getPackedRepeatedSfixed64List(), + [-0x1234567800000000]); + assertElementsEquals(copy.getPackedRepeatedFloatList(), [1.5]); + assertElementsEquals(copy.getPackedRepeatedDoubleList(), [-1.5]); + +} + + +/** + * Helper: verify that all expected extensions are present. + * @param {!proto.jspb.test.TestExtendable} msg + */ +function checkExtensions(msg) { + assertEquals(-42, + msg.getExtension(proto.jspb.test.extendOptionalInt32)); + assertEquals(-0x7fffffff00000000, + msg.getExtension(proto.jspb.test.extendOptionalInt64)); + assertEquals(0x80000000, + msg.getExtension(proto.jspb.test.extendOptionalUint32)); + assertEquals(0xf000000000000000, + msg.getExtension(proto.jspb.test.extendOptionalUint64)); + assertEquals(-100, + msg.getExtension(proto.jspb.test.extendOptionalSint32)); + assertEquals(-0x8000000000000000, + msg.getExtension(proto.jspb.test.extendOptionalSint64)); + assertEquals(1234, + msg.getExtension(proto.jspb.test.extendOptionalFixed32)); + assertEquals(0x1234567800000000, + msg.getExtension(proto.jspb.test.extendOptionalFixed64)); + assertEquals(-1234, + msg.getExtension(proto.jspb.test.extendOptionalSfixed32)); + assertEquals(-0x1234567800000000, + msg.getExtension(proto.jspb.test.extendOptionalSfixed64)); + assertEquals(1.5, + msg.getExtension(proto.jspb.test.extendOptionalFloat)); + assertEquals(-1.5, + msg.getExtension(proto.jspb.test.extendOptionalDouble)); + assertEquals(true, + msg.getExtension(proto.jspb.test.extendOptionalBool)); + assertEquals('hello world', + msg.getExtension(proto.jspb.test.extendOptionalString)); + assertEquals( + true, bytesCompare( + msg.getExtension(proto.jspb.test.extendOptionalBytes), BYTES)); + assertEquals(16, + msg.getExtension( + proto.jspb.test.ExtendsWithMessage.optionalExtension).getFoo()); + + + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedInt32List), + [-42]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedInt64List), + [-0x7fffffff00000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedUint32List), + [0x80000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedUint64List), + [0xf000000000000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedSint32List), + [-100]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedSint64List), + [-0x8000000000000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedFixed32List), + [1234]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedFixed64List), + [0x1234567800000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedSfixed32List), + [-1234]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedSfixed64List), + [-0x1234567800000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedFloatList), + [1.5]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedDoubleList), + [-1.5]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedBoolList), + [true]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedStringList), + ['hello world']); + assertEquals( + true, + bytesCompare( + msg.getExtension(proto.jspb.test.extendRepeatedBytesList)[0], BYTES)); + assertEquals(1000, + msg.getExtension( + proto.jspb.test.ExtendsWithMessage.repeatedExtensionList)[0] + .getFoo()); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendRepeatedForeignEnumList), + [proto.jspb.test.ForeignEnum.FOREIGN_FOO]); + + + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedInt32List), + [-42]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedInt64List), + [-0x7fffffff00000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedUint32List), + [0x80000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedUint64List), + [0xf000000000000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedSint32List), + [-100]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedSint64List), + [-0x8000000000000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedFixed32List), + [1234]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedFixed64List), + [0x1234567800000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedSfixed32List), + [-1234]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedSfixed64List), + [-0x1234567800000000]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedFloatList), + [1.5]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedDoubleList), + [-1.5]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedBoolList), + [true]); + assertElementsEquals( + msg.getExtension(proto.jspb.test.extendPackedRepeatedForeignEnumList), + [proto.jspb.test.ForeignEnum.FOREIGN_FOO]); + +} + + +describe('protoBinaryTest', function() { + /** + * Tests a basic serialization-deserializaton round-trip with all supported + * field types (on the TestAllTypes message type). + */ + it('testRoundTrip', function() { + var msg = new proto.jspb.test.TestAllTypes(); + fillAllFields(msg); + var encoded = msg.serializeBinary(); + var decoded = proto.jspb.test.TestAllTypes.deserializeBinary(encoded); + checkAllFields(msg, decoded); + }); + + /** + * Test that base64 string and Uint8Array are interchangeable in bytes fields. + */ + it('testBytesFieldsGettersInterop', function() { + var msg = new proto.jspb.test.TestAllTypes(); + // Set from a base64 string and check all the getters work. + msg.setOptionalBytes(BYTES_B64); + assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES)); + assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES)); + assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); + + // Test binary serialize round trip doesn't break it. + msg = proto.jspb.test.TestAllTypes.deserializeBinary(msg.serializeBinary()); + assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES)); + assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES)); + assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); + + msg = new proto.jspb.test.TestAllTypes(); + // Set from a Uint8Array and check all the getters work. + msg.setOptionalBytes(BYTES); + assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES)); + assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES)); + assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); + + }); + + /** + * Test that bytes setters will receive result of any of the getters. + */ + it('testBytesFieldsSettersInterop', function() { + var msg = new proto.jspb.test.TestAllTypes(); + msg.setOptionalBytes(BYTES); + assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); + + msg.setOptionalBytes(msg.getOptionalBytes()); + assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); + msg.setOptionalBytes(msg.getOptionalBytes_asB64()); + assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); + msg.setOptionalBytes(msg.getOptionalBytes_asU8()); + assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); + }); + + /** + * Test that bytes setters will receive result of any of the getters. + */ + it('testRepeatedBytesGetters', function() { + var msg = new proto.jspb.test.TestAllTypes(); + + function assertGetters() { + assertTrue(typeof msg.getRepeatedBytesList_asB64()[0] === 'string'); + assertTrue(typeof msg.getRepeatedBytesList_asB64()[1] === 'string'); + assertTrue(msg.getRepeatedBytesList_asU8()[0] instanceof Uint8Array); + assertTrue(msg.getRepeatedBytesList_asU8()[1] instanceof Uint8Array); + + assertTrue(bytesCompare(msg.getRepeatedBytesList()[0], BYTES)); + assertTrue(bytesCompare(msg.getRepeatedBytesList()[1], BYTES)); + assertTrue(bytesCompare(msg.getRepeatedBytesList_asB64()[0], BYTES)); + assertTrue(bytesCompare(msg.getRepeatedBytesList_asB64()[1], BYTES)); + assertTrue(bytesCompare(msg.getRepeatedBytesList_asU8()[0], BYTES)); + assertTrue(bytesCompare(msg.getRepeatedBytesList_asU8()[1], BYTES)); + } + + msg.setRepeatedBytesList([BYTES, BYTES]); + assertGetters(); + + msg.setRepeatedBytesList([BYTES_B64, BYTES_B64]); + assertGetters(); + + msg.setRepeatedBytesList([]); + assertEquals(0, msg.getRepeatedBytesList().length); + assertEquals(0, msg.getRepeatedBytesList_asB64().length); + assertEquals(0, msg.getRepeatedBytesList_asU8().length); + }); + + /** + * Helper: fill all extension values. + * @param {proto.jspb.test.TestExtendable} msg + */ + function fillExtensions(msg) { + msg.setExtension( + proto.jspb.test.extendOptionalInt32, -42); + msg.setExtension( + proto.jspb.test.extendOptionalInt64, -0x7fffffff00000000); + msg.setExtension( + proto.jspb.test.extendOptionalUint32, 0x80000000); + msg.setExtension( + proto.jspb.test.extendOptionalUint64, 0xf000000000000000); + msg.setExtension( + proto.jspb.test.extendOptionalSint32, -100); + msg.setExtension( + proto.jspb.test.extendOptionalSint64, -0x8000000000000000); + msg.setExtension( + proto.jspb.test.extendOptionalFixed32, 1234); + msg.setExtension( + proto.jspb.test.extendOptionalFixed64, 0x1234567800000000); + msg.setExtension( + proto.jspb.test.extendOptionalSfixed32, -1234); + msg.setExtension( + proto.jspb.test.extendOptionalSfixed64, -0x1234567800000000); + msg.setExtension( + proto.jspb.test.extendOptionalFloat, 1.5); + msg.setExtension( + proto.jspb.test.extendOptionalDouble, -1.5); + msg.setExtension( + proto.jspb.test.extendOptionalBool, true); + msg.setExtension( + proto.jspb.test.extendOptionalString, 'hello world'); + msg.setExtension(proto.jspb.test.extendOptionalBytes, BYTES); + var submsg = new proto.jspb.test.ExtendsWithMessage(); + submsg.setFoo(16); + msg.setExtension( + proto.jspb.test.ExtendsWithMessage.optionalExtension, submsg); + msg.setExtension( + proto.jspb.test.extendOptionalForeignEnum, + proto.jspb.test.ForeignEnum.FOREIGN_FOO); + + + msg.setExtension( + proto.jspb.test.extendRepeatedInt32List, [-42]); + msg.setExtension( + proto.jspb.test.extendRepeatedInt64List, [-0x7fffffff00000000]); + msg.setExtension( + proto.jspb.test.extendRepeatedUint32List, [0x80000000]); + msg.setExtension( + proto.jspb.test.extendRepeatedUint64List, [0xf000000000000000]); + msg.setExtension( + proto.jspb.test.extendRepeatedSint32List, [-100]); + msg.setExtension( + proto.jspb.test.extendRepeatedSint64List, [-0x8000000000000000]); + msg.setExtension( + proto.jspb.test.extendRepeatedFixed32List, [1234]); + msg.setExtension( + proto.jspb.test.extendRepeatedFixed64List, [0x1234567800000000]); + msg.setExtension( + proto.jspb.test.extendRepeatedSfixed32List, [-1234]); + msg.setExtension( + proto.jspb.test.extendRepeatedSfixed64List, [-0x1234567800000000]); + msg.setExtension( + proto.jspb.test.extendRepeatedFloatList, [1.5]); + msg.setExtension( + proto.jspb.test.extendRepeatedDoubleList, [-1.5]); + msg.setExtension( + proto.jspb.test.extendRepeatedBoolList, [true]); + msg.setExtension( + proto.jspb.test.extendRepeatedStringList, ['hello world']); + msg.setExtension(proto.jspb.test.extendRepeatedBytesList, [BYTES]); + submsg = new proto.jspb.test.ExtendsWithMessage(); + submsg.setFoo(1000); + msg.setExtension( + proto.jspb.test.ExtendsWithMessage.repeatedExtensionList, [submsg]); + msg.setExtension(proto.jspb.test.extendRepeatedForeignEnumList, + [proto.jspb.test.ForeignEnum.FOREIGN_FOO]); + + + msg.setExtension( + proto.jspb.test.extendPackedRepeatedInt32List, [-42]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedInt64List, [-0x7fffffff00000000]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedUint32List, [0x80000000]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedUint64List, [0xf000000000000000]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedSint32List, [-100]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedSint64List, [-0x8000000000000000]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedFixed32List, [1234]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedFixed64List, [0x1234567800000000]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedSfixed32List, [-1234]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedSfixed64List, + [-0x1234567800000000]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedFloatList, [1.5]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedDoubleList, [-1.5]); + msg.setExtension( + proto.jspb.test.extendPackedRepeatedBoolList, [true]); + msg.setExtension(proto.jspb.test.extendPackedRepeatedForeignEnumList, + [proto.jspb.test.ForeignEnum.FOREIGN_FOO]); + + } + + + /** + * Tests extension serialization and deserialization. + */ + it('testExtensions', function() { + var msg = new proto.jspb.test.TestExtendable(); + fillExtensions(msg); + var encoded = msg.serializeBinary(); + var decoded = proto.jspb.test.TestExtendable.deserializeBinary(encoded); + checkExtensions(decoded); + }); +}); diff --git a/tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.1.0/message_test.js b/tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.1.0/message_test.js new file mode 100644 index 0000000..9830a02 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.1.0/message_test.js @@ -0,0 +1,1060 @@ +// 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. + +// Test suite is written using Jasmine -- see http://jasmine.github.io/ + +goog.setTestOnly(); + +goog.require('goog.json'); +goog.require('goog.testing.asserts'); +goog.require('goog.userAgent'); + +// CommonJS-LoadFromFile: google-protobuf jspb +goog.require('jspb.Message'); + +// CommonJS-LoadFromFile: test5_pb proto.jspb.exttest.beta +goog.require('proto.jspb.exttest.beta.floatingStrField'); + +// CommonJS-LoadFromFile: test3_pb proto.jspb.exttest +goog.require('proto.jspb.exttest.floatingMsgField'); + +// CommonJS-LoadFromFile: test4_pb proto.jspb.exttest +goog.require('proto.jspb.exttest.floatingMsgFieldTwo'); + +// CommonJS-LoadFromFile: test_pb proto.jspb.test +goog.require('proto.jspb.test.CloneExtension'); +goog.require('proto.jspb.test.Complex'); +goog.require('proto.jspb.test.DefaultValues'); +goog.require('proto.jspb.test.Empty'); +goog.require('proto.jspb.test.EnumContainer'); +goog.require('proto.jspb.test.floatingMsgField'); +goog.require('proto.jspb.test.FloatingPointFields'); +goog.require('proto.jspb.test.floatingStrField'); +goog.require('proto.jspb.test.HasExtensions'); +goog.require('proto.jspb.test.IndirectExtension'); +goog.require('proto.jspb.test.IsExtension'); +goog.require('proto.jspb.test.OptionalFields'); +goog.require('proto.jspb.test.OuterEnum'); +goog.require('proto.jspb.test.OuterMessage.Complex'); +goog.require('proto.jspb.test.Simple1'); +goog.require('proto.jspb.test.Simple2'); +goog.require('proto.jspb.test.SpecialCases'); +goog.require('proto.jspb.test.TestClone'); +goog.require('proto.jspb.test.TestGroup'); +goog.require('proto.jspb.test.TestGroup1'); +goog.require('proto.jspb.test.TestMessageWithOneof'); +goog.require('proto.jspb.test.TestReservedNames'); +goog.require('proto.jspb.test.TestReservedNamesExtension'); + +// CommonJS-LoadFromFile: test2_pb proto.jspb.test +goog.require('proto.jspb.test.ExtensionMessage'); +goog.require('proto.jspb.test.TestExtensionsMessage'); +goog.require('proto.jspb.test.simple1'); + + + +describe('Message test suite', function() { + it('testEmptyProto', function() { + var empty1 = new proto.jspb.test.Empty([]); + var empty2 = new proto.jspb.test.Empty([]); + assertObjectEquals({}, empty1.toObject()); + assertObjectEquals('Message should not be corrupted:', empty2, empty1); + }); + + it('testTopLevelEnum', function() { + var response = new proto.jspb.test.EnumContainer([]); + response.setOuterEnum(proto.jspb.test.OuterEnum.FOO); + assertEquals(proto.jspb.test.OuterEnum.FOO, response.getOuterEnum()); + }); + + it('testByteStrings', function() { + var data = new proto.jspb.test.DefaultValues([]); + data.setBytesField('some_bytes'); + assertEquals('some_bytes', data.getBytesField()); + }); + + it('testComplexConversion', function() { + var data1 = ['a', , , [, 11], [[, 22], [, 33]], , ['s1', 's2'], , true]; + var data2 = ['a', , , [, 11], [[, 22], [, 33]], , ['s1', 's2'], , true]; + var foo = new proto.jspb.test.Complex(data1); + var bar = new proto.jspb.test.Complex(data2); + var result = foo.toObject(); + assertObjectEquals( + { + aString: 'a', + anOutOfOrderBool: true, + aNestedMessage: {anInt: 11}, + aRepeatedMessageList: [{anInt: 22}, {anInt: 33}], + aRepeatedStringList: ['s1', 's2'] + }, + result); + + // Now test with the jspb instances included. + result = foo.toObject(true /* opt_includeInstance */); + assertObjectEquals( + { + aString: 'a', + anOutOfOrderBool: true, + aNestedMessage: + {anInt: 11, $jspbMessageInstance: foo.getANestedMessage()}, + aRepeatedMessageList: [ + {anInt: 22, $jspbMessageInstance: foo.getARepeatedMessageList()[0]}, + {anInt: 33, $jspbMessageInstance: foo.getARepeatedMessageList()[1]} + ], + aRepeatedStringList: ['s1', 's2'], + $jspbMessageInstance: foo + }, + result); + }); + + it('testMissingFields', function() { + var foo = new proto.jspb.test.Complex([ + undefined, undefined, undefined, [], undefined, undefined, undefined, + undefined + ]); + var bar = new proto.jspb.test.Complex([ + undefined, undefined, undefined, [], undefined, undefined, undefined, + undefined + ]); + var result = foo.toObject(); + assertObjectEquals( + { + aString: undefined, + anOutOfOrderBool: undefined, + aNestedMessage: {anInt: undefined}, + // Note: JsPb converts undefined repeated fields to empty arrays. + aRepeatedMessageList: [], + aRepeatedStringList: [] + }, + result); + }); + + it('testNestedComplexMessage', function() { + // Instantiate the message and set a unique field, just to ensure that we + // are not getting jspb.test.Complex instead. + var msg = new proto.jspb.test.OuterMessage.Complex(); + msg.setInnerComplexField(5); + }); + + it('testSpecialCases', function() { + // Note: Some property names are reserved in JavaScript. + // These names are converted to the Js property named pb_. + var special = new proto.jspb.test.SpecialCases( + ['normal', 'default', 'function', 'var']); + var result = special.toObject(); + assertObjectEquals( + { + normal: 'normal', + pb_default: 'default', + pb_function: 'function', + pb_var: 'var' + }, + result); + }); + + it('testDefaultValues', function() { + var defaultString = 'default<>\'"abc'; + var response = new proto.jspb.test.DefaultValues(); + + // Test toObject + var expectedObject = { + stringField: defaultString, + boolField: true, + intField: 11, + enumField: 13, + emptyField: '', + bytesField: 'bW9v' + }; + assertObjectEquals(expectedObject, response.toObject()); + + + // Test getters + response = new proto.jspb.test.DefaultValues(); + assertEquals(defaultString, response.getStringField()); + assertEquals(true, response.getBoolField()); + assertEquals(11, response.getIntField()); + assertEquals(13, response.getEnumField()); + assertEquals('', response.getEmptyField()); + assertEquals('bW9v', response.getBytesField()); + + function makeDefault(values) { + return new proto.jspb.test.DefaultValues(values); + } + + // Test with undefined values, + // Use push to workaround IE treating undefined array elements as holes. + response = makeDefault([undefined, undefined, undefined, undefined]); + assertEquals(defaultString, response.getStringField()); + assertEquals(true, response.getBoolField()); + assertEquals(11, response.getIntField()); + assertEquals(13, response.getEnumField()); + assertFalse(response.hasStringField()); + assertFalse(response.hasBoolField()); + assertFalse(response.hasIntField()); + assertFalse(response.hasEnumField()); + + // Test with null values, as would be returned by a JSON serializer. + response = makeDefault([null, null, null, null]); + assertEquals(defaultString, response.getStringField()); + assertEquals(true, response.getBoolField()); + assertEquals(11, response.getIntField()); + assertEquals(13, response.getEnumField()); + assertFalse(response.hasStringField()); + assertFalse(response.hasBoolField()); + assertFalse(response.hasIntField()); + assertFalse(response.hasEnumField()); + + // Test with false-like values. + response = makeDefault(['', false, 0, 0]); + assertEquals('', response.getStringField()); + assertEquals(false, response.getBoolField()); + assertEquals(true, response.getIntField() == 0); + assertEquals(true, response.getEnumField() == 0); + assertTrue(response.hasStringField()); + assertTrue(response.hasBoolField()); + assertTrue(response.hasIntField()); + assertTrue(response.hasEnumField()); + + // Test that clearing the values reverts them to the default state. + response = makeDefault(['blah', false, 111, 77]); + response.clearStringField(); + response.clearBoolField(); + response.clearIntField(); + response.clearEnumField(); + assertEquals(defaultString, response.getStringField()); + assertEquals(true, response.getBoolField()); + assertEquals(11, response.getIntField()); + assertEquals(13, response.getEnumField()); + assertFalse(response.hasStringField()); + assertFalse(response.hasBoolField()); + assertFalse(response.hasIntField()); + assertFalse(response.hasEnumField()); + + // Test that setFoo(null) clears the values. + response = makeDefault(['blah', false, 111, 77]); + response.setStringField(null); + response.setBoolField(null); + response.setIntField(undefined); + response.setEnumField(undefined); + assertEquals(defaultString, response.getStringField()); + assertEquals(true, response.getBoolField()); + assertEquals(11, response.getIntField()); + assertEquals(13, response.getEnumField()); + assertFalse(response.hasStringField()); + assertFalse(response.hasBoolField()); + assertFalse(response.hasIntField()); + assertFalse(response.hasEnumField()); + }); + + it('testClearFields', function() { + var data = ['str', true, [11], [[22], [33]], ['s1', 's2']]; + var foo = new proto.jspb.test.OptionalFields(data); + foo.clearAString(); + foo.clearABool(); + foo.clearANestedMessage(); + foo.clearARepeatedMessageList(); + foo.clearARepeatedStringList(); + assertEquals('', foo.getAString()); + assertEquals(false, foo.getABool()); + assertUndefined(foo.getANestedMessage()); + assertFalse(foo.hasAString()); + assertFalse(foo.hasABool()); + assertObjectEquals([], foo.getARepeatedMessageList()); + assertObjectEquals([], foo.getARepeatedStringList()); + // NOTE: We want the missing fields in 'expected' to be undefined, + // but we actually get a sparse array instead. We could use something + // like [1,undefined,2] to avoid this, except that this is still + // sparse on IE. No comment... + var expected = [, , , [], []]; + expected[0] = expected[1] = expected[2] = undefined; + assertObjectEquals(expected, foo.toArray()); + }); + + it('testDifferenceRawObject', /** @suppress {visibility} */ function() { + var p1 = new proto.jspb.test.HasExtensions(['hi', 'diff', {}]); + var p2 = + new proto.jspb.test.HasExtensions(['hi', 'what', {1000: 'unique'}]); + var diff = /** @type {proto.jspb.test.HasExtensions} */ + (jspb.Message.difference(p1, p2)); + assertEquals('', diff.getStr1()); + assertEquals('what', diff.getStr2()); + assertEquals('', diff.getStr3()); + assertEquals('unique', diff.extensionObject_[1000]); + }); + + it('testEqualsSimple', function() { + var s1 = new proto.jspb.test.Simple1(['hi']); + assertTrue(jspb.Message.equals(s1, new proto.jspb.test.Simple1(['hi']))); + assertFalse(jspb.Message.equals(s1, new proto.jspb.test.Simple1(['bye']))); + var s1b = new proto.jspb.test.Simple1(['hi', ['hello']]); + assertTrue(jspb.Message.equals( + s1b, new proto.jspb.test.Simple1(['hi', ['hello']]))); + assertTrue(jspb.Message.equals(s1b, new proto.jspb.test.Simple1([ + 'hi', ['hello', undefined, undefined, undefined] + ]))); + assertFalse(jspb.Message.equals( + s1b, new proto.jspb.test.Simple1(['no', ['hello']]))); + // Test with messages of different types + var s2 = new proto.jspb.test.Simple2(['hi']); + assertFalse(jspb.Message.equals(s1, s2)); + }); + + it('testEquals_softComparison', function() { + var s1 = new proto.jspb.test.Simple1(['hi', [], null]); + assertTrue( + jspb.Message.equals(s1, new proto.jspb.test.Simple1(['hi', []]))); + + var s1b = new proto.jspb.test.Simple1(['hi', [], true]); + assertTrue( + jspb.Message.equals(s1b, new proto.jspb.test.Simple1(['hi', [], 1]))); + }); + + it('testEqualsComplex', function() { + var data1 = ['a', , , [, 11], [[, 22], [, 33]], , ['s1', 's2'], , 1]; + var data2 = ['a', , , [, 11], [[, 22], [, 34]], , ['s1', 's2'], , 1]; + var data3 = ['a', , , [, 11], [[, 22]], , ['s1', 's2'], , 1]; + var data4 = ['hi']; + var c1a = new proto.jspb.test.Complex(data1); + var c1b = new proto.jspb.test.Complex(data1); + var c2 = new proto.jspb.test.Complex(data2); + var c3 = new proto.jspb.test.Complex(data3); + var s1 = new proto.jspb.test.Simple1(data4); + + assertTrue(jspb.Message.equals(c1a, c1b)); + assertFalse(jspb.Message.equals(c1a, c2)); + assertFalse(jspb.Message.equals(c2, c3)); + assertFalse(jspb.Message.equals(c1a, s1)); + }); + + it('testEqualsExtensionsConstructed', function() { + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions([]), + new proto.jspb.test.HasExtensions([{}]))); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]))); + assertFalse(jspb.Message.equals( + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'b'}]}]))); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}]))); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions([, , , {100: [{200: 'a'}]}]))); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions([, , , {100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions([{100: [{200: 'a'}]}]))); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions(['hi', , , {100: [{200: 'a'}]}]))); + assertTrue(jspb.Message.equals( + new proto.jspb.test.HasExtensions(['hi', , , {100: [{200: 'a'}]}]), + new proto.jspb.test.HasExtensions(['hi', {100: [{200: 'a'}]}]))); + }); + + it('testEqualsExtensionsUnconstructed', function() { + assertTrue(jspb.Message.compareFields([], [{}])); + assertTrue(jspb.Message.compareFields([, , , {}], [])); + assertTrue(jspb.Message.compareFields([, , , {}], [, , {}])); + assertTrue(jspb.Message.compareFields( + ['hi', {100: [{200: 'a'}]}], ['hi', {100: [{200: 'a'}]}])); + assertFalse(jspb.Message.compareFields( + ['hi', {100: [{200: 'a'}]}], ['hi', {100: [{200: 'b'}]}])); + assertTrue(jspb.Message.compareFields( + [{100: [{200: 'a'}]}], [{100: [{200: 'a'}]}])); + assertTrue(jspb.Message.compareFields( + [{100: [{200: 'a'}]}], [, , , {100: [{200: 'a'}]}])); + assertTrue(jspb.Message.compareFields( + [, , , {100: [{200: 'a'}]}], [{100: [{200: 'a'}]}])); + assertTrue(jspb.Message.compareFields( + ['hi', {100: [{200: 'a'}]}], ['hi', , , {100: [{200: 'a'}]}])); + assertTrue(jspb.Message.compareFields( + ['hi', , , {100: [{200: 'a'}]}], ['hi', {100: [{200: 'a'}]}])); + }); + + it('testToMap', function() { + var p1 = new proto.jspb.test.Simple1(['k', ['v']]); + var p2 = new proto.jspb.test.Simple1(['k1', ['v1', 'v2']]); + var soymap = jspb.Message.toMap( + [p1, p2], proto.jspb.test.Simple1.prototype.getAString, + proto.jspb.test.Simple1.prototype.toObject); + assertEquals('k', soymap['k'].aString); + assertArrayEquals(['v'], soymap['k'].aRepeatedStringList); + var protomap = jspb.Message.toMap( + [p1, p2], proto.jspb.test.Simple1.prototype.getAString); + assertEquals('k', protomap['k'].getAString()); + assertArrayEquals(['v'], protomap['k'].getARepeatedStringList()); + }); + + it('testClone', function() { + var supportsUint8Array = + !goog.userAgent.IE || goog.userAgent.isVersionOrHigher('10'); + var original = new proto.jspb.test.TestClone(); + original.setStr('v1'); + var simple1 = new proto.jspb.test.Simple1(['x1', ['y1', 'z1']]); + var simple2 = new proto.jspb.test.Simple1(['x2', ['y2', 'z2']]); + var simple3 = new proto.jspb.test.Simple1(['x3', ['y3', 'z3']]); + original.setSimple1(simple1); + original.setSimple2List([simple2, simple3]); + var bytes1 = supportsUint8Array ? new Uint8Array([1, 2, 3]) : '123'; + original.setBytesField(bytes1); + var extension = new proto.jspb.test.CloneExtension(); + extension.setExt('e1'); + original.setExtension(proto.jspb.test.IsExtension.extField, extension); + var clone = original.clone(); + assertArrayEquals( + [ + 'v1', , ['x1', ['y1', 'z1']], , + [['x2', ['y2', 'z2']], ['x3', ['y3', 'z3']]], bytes1, , + {100: [, 'e1']} + ], + clone.toArray()); + clone.setStr('v2'); + var simple4 = new proto.jspb.test.Simple1(['a1', ['b1', 'c1']]); + var simple5 = new proto.jspb.test.Simple1(['a2', ['b2', 'c2']]); + var simple6 = new proto.jspb.test.Simple1(['a3', ['b3', 'c3']]); + clone.setSimple1(simple4); + clone.setSimple2List([simple5, simple6]); + if (supportsUint8Array) { + clone.getBytesField()[0] = 4; + assertObjectEquals(bytes1, original.getBytesField()); + } + var bytes2 = supportsUint8Array ? new Uint8Array([4, 5, 6]) : '456'; + clone.setBytesField(bytes2); + var newExtension = new proto.jspb.test.CloneExtension(); + newExtension.setExt('e2'); + clone.setExtension(proto.jspb.test.CloneExtension.extField, newExtension); + assertArrayEquals( + [ + 'v2', , ['a1', ['b1', 'c1']], , + [['a2', ['b2', 'c2']], ['a3', ['b3', 'c3']]], bytes2, , + {100: [, 'e2']} + ], + clone.toArray()); + assertArrayEquals( + [ + 'v1', , ['x1', ['y1', 'z1']], , + [['x2', ['y2', 'z2']], ['x3', ['y3', 'z3']]], bytes1, , + {100: [, 'e1']} + ], + original.toArray()); + }); + + it('testCopyInto', function() { + var supportsUint8Array = + !goog.userAgent.IE || goog.userAgent.isVersionOrHigher('10'); + var original = new proto.jspb.test.TestClone(); + original.setStr('v1'); + var dest = new proto.jspb.test.TestClone(); + dest.setStr('override'); + var simple1 = new proto.jspb.test.Simple1(['x1', ['y1', 'z1']]); + var simple2 = new proto.jspb.test.Simple1(['x2', ['y2', 'z2']]); + var simple3 = new proto.jspb.test.Simple1(['x3', ['y3', 'z3']]); + var destSimple1 = new proto.jspb.test.Simple1(['ox1', ['oy1', 'oz1']]); + var destSimple2 = new proto.jspb.test.Simple1(['ox2', ['oy2', 'oz2']]); + var destSimple3 = new proto.jspb.test.Simple1(['ox3', ['oy3', 'oz3']]); + original.setSimple1(simple1); + original.setSimple2List([simple2, simple3]); + dest.setSimple1(destSimple1); + dest.setSimple2List([destSimple2, destSimple3]); + var bytes1 = supportsUint8Array ? new Uint8Array([1, 2, 3]) : '123'; + var bytes2 = supportsUint8Array ? new Uint8Array([4, 5, 6]) : '456'; + original.setBytesField(bytes1); + dest.setBytesField(bytes2); + var extension = new proto.jspb.test.CloneExtension(); + extension.setExt('e1'); + original.setExtension(proto.jspb.test.CloneExtension.extField, extension); + + jspb.Message.copyInto(original, dest); + assertArrayEquals(original.toArray(), dest.toArray()); + assertEquals('x1', dest.getSimple1().getAString()); + assertEquals( + 'e1', + dest.getExtension(proto.jspb.test.CloneExtension.extField).getExt()); + dest.getSimple1().setAString('new value'); + assertNotEquals( + dest.getSimple1().getAString(), original.getSimple1().getAString()); + if (supportsUint8Array) { + dest.getBytesField()[0] = 7; + assertObjectEquals(bytes1, original.getBytesField()); + assertObjectEquals(new Uint8Array([7, 2, 3]), dest.getBytesField()); + } else { + dest.setBytesField('789'); + assertObjectEquals(bytes1, original.getBytesField()); + assertObjectEquals('789', dest.getBytesField()); + } + dest.getExtension(proto.jspb.test.CloneExtension.extField) + .setExt('new value'); + assertNotEquals( + dest.getExtension(proto.jspb.test.CloneExtension.extField).getExt(), + original.getExtension(proto.jspb.test.CloneExtension.extField) + .getExt()); + }); + + it('testCopyInto_notSameType', function() { + var a = new proto.jspb.test.TestClone(); + var b = new proto.jspb.test.Simple1(['str', ['s1', 's2']]); + + var e = assertThrows(function() { + jspb.Message.copyInto(a, b); + }); + assertContains('should have the same type', e.message); + }); + + it('testExtensions', function() { + var extension1 = new proto.jspb.test.IsExtension(['ext1field']); + var extension2 = new proto.jspb.test.Simple1(['str', ['s1', 's2']]); + var extendable = new proto.jspb.test.HasExtensions(['v1', 'v2', 'v3']); + extendable.setExtension(proto.jspb.test.IsExtension.extField, extension1); + extendable.setExtension( + proto.jspb.test.IndirectExtension.simple, extension2); + extendable.setExtension(proto.jspb.test.IndirectExtension.str, 'xyzzy'); + extendable.setExtension( + proto.jspb.test.IndirectExtension.repeatedStrList, ['a', 'b']); + var s1 = new proto.jspb.test.Simple1(['foo', ['s1', 's2']]); + var s2 = new proto.jspb.test.Simple1(['bar', ['t1', 't2']]); + extendable.setExtension( + proto.jspb.test.IndirectExtension.repeatedSimpleList, [s1, s2]); + assertObjectEquals( + extension1, + extendable.getExtension(proto.jspb.test.IsExtension.extField)); + assertObjectEquals( + extension2, + extendable.getExtension(proto.jspb.test.IndirectExtension.simple)); + assertObjectEquals( + 'xyzzy', + extendable.getExtension(proto.jspb.test.IndirectExtension.str)); + assertObjectEquals( + ['a', 'b'], + extendable.getExtension( + proto.jspb.test.IndirectExtension.repeatedStrList)); + assertObjectEquals( + [s1, s2], + extendable.getExtension( + proto.jspb.test.IndirectExtension.repeatedSimpleList)); + // Not supported yet, but it should work... + extendable.setExtension(proto.jspb.test.IndirectExtension.simple, null); + assertNull( + extendable.getExtension(proto.jspb.test.IndirectExtension.simple)); + extendable.setExtension(proto.jspb.test.IndirectExtension.str, null); + assertNull(extendable.getExtension(proto.jspb.test.IndirectExtension.str)); + + + // Extension fields with jspb.ignore = true are ignored. + assertUndefined(proto.jspb.test.IndirectExtension['ignored']); + assertUndefined(proto.jspb.test.HasExtensions['ignoredFloating']); + }); + + it('testFloatingExtensions', function() { + // From an autogenerated container. + var extendable = new proto.jspb.test.HasExtensions(['v1', 'v2', 'v3']); + var extension = new proto.jspb.test.Simple1(['foo', ['s1', 's2']]); + extendable.setExtension(proto.jspb.test.simple1, extension); + assertObjectEquals( + extension, extendable.getExtension(proto.jspb.test.simple1)); + + // From _lib mode. + extension = new proto.jspb.test.ExtensionMessage(['s1']); + extendable = new proto.jspb.test.TestExtensionsMessage([16]); + extendable.setExtension(proto.jspb.test.floatingMsgField, extension); + extendable.setExtension(proto.jspb.test.floatingStrField, 's2'); + assertObjectEquals( + extension, extendable.getExtension(proto.jspb.test.floatingMsgField)); + assertObjectEquals( + 's2', extendable.getExtension(proto.jspb.test.floatingStrField)); + assertNotUndefined(proto.jspb.exttest.floatingMsgField); + assertNotUndefined(proto.jspb.exttest.floatingMsgFieldTwo); + assertNotUndefined(proto.jspb.exttest.beta.floatingStrField); + }); + + it('testToObject_extendedObject', function() { + var extension1 = new proto.jspb.test.IsExtension(['ext1field']); + var extension2 = new proto.jspb.test.Simple1(['str', ['s1', 's2'], true]); + var extendable = new proto.jspb.test.HasExtensions(['v1', 'v2', 'v3']); + extendable.setExtension(proto.jspb.test.IsExtension.extField, extension1); + extendable.setExtension( + proto.jspb.test.IndirectExtension.simple, extension2); + extendable.setExtension(proto.jspb.test.IndirectExtension.str, 'xyzzy'); + extendable.setExtension( + proto.jspb.test.IndirectExtension.repeatedStrList, ['a', 'b']); + var s1 = new proto.jspb.test.Simple1(['foo', ['s1', 's2'], true]); + var s2 = new proto.jspb.test.Simple1(['bar', ['t1', 't2'], false]); + extendable.setExtension( + proto.jspb.test.IndirectExtension.repeatedSimpleList, [s1, s2]); + assertObjectEquals( + { + str1: 'v1', + str2: 'v2', + str3: 'v3', + extField: {ext1: 'ext1field'}, + simple: { + aString: 'str', + aRepeatedStringList: ['s1', 's2'], + aBoolean: true + }, + str: 'xyzzy', + repeatedStrList: ['a', 'b'], + repeatedSimpleList: [ + {aString: 'foo', aRepeatedStringList: ['s1', 's2'], aBoolean: true}, + {aString: 'bar', aRepeatedStringList: ['t1', 't2'], aBoolean: false} + ] + }, + extendable.toObject()); + + // Now, with instances included. + assertObjectEquals( + { + str1: 'v1', + str2: 'v2', + str3: 'v3', + extField: { + ext1: 'ext1field', + $jspbMessageInstance: + extendable.getExtension(proto.jspb.test.IsExtension.extField) + }, + simple: { + aString: 'str', + aRepeatedStringList: ['s1', 's2'], + aBoolean: true, + $jspbMessageInstance: extendable.getExtension( + proto.jspb.test.IndirectExtension.simple) + }, + str: 'xyzzy', + repeatedStrList: ['a', 'b'], + repeatedSimpleList: [ + { + aString: 'foo', + aRepeatedStringList: ['s1', 's2'], + aBoolean: true, + $jspbMessageInstance: s1 + }, + { + aString: 'bar', + aRepeatedStringList: ['t1', 't2'], + aBoolean: false, + $jspbMessageInstance: s2 + } + ], + $jspbMessageInstance: extendable + }, + extendable.toObject(true /* opt_includeInstance */)); + }); + + it('testInitialization_emptyArray', function() { + var msg = new proto.jspb.test.HasExtensions([]); + assertArrayEquals([], msg.toArray()); + }); + + it('testInitialization_justExtensionObject', function() { + var msg = new proto.jspb.test.Empty([{1: 'hi'}]); + // The extensionObject is not moved from its original location. + assertArrayEquals([{1: 'hi'}], msg.toArray()); + }); + + it('testInitialization_incompleteList', function() { + var msg = new proto.jspb.test.Empty([1, {4: 'hi'}]); + // The extensionObject is not moved from its original location. + assertArrayEquals([1, {4: 'hi'}], msg.toArray()); + }); + + it('testInitialization_forwardCompatible', function() { + var msg = new proto.jspb.test.Empty([1, 2, 3, {1: 'hi'}]); + assertArrayEquals([1, 2, 3, {1: 'hi'}], msg.toArray()); + }); + + it('testExtendedMessageEnsureObject', + /** @suppress {visibility} */ function() { + var data = + new proto.jspb.test.HasExtensions(['str1', {'a_key': 'an_object'}]); + assertEquals('an_object', data.extensionObject_['a_key']); + }); + + it('testToObject_hasExtensionField', function() { + var data = new proto.jspb.test.HasExtensions(['str1', {100: ['ext1']}]); + var obj = data.toObject(); + assertEquals('str1', obj.str1); + assertEquals('ext1', obj.extField.ext1); + }); + + it('testGetExtension', function() { + var data = new proto.jspb.test.HasExtensions(['str1', {100: ['ext1']}]); + assertEquals('str1', data.getStr1()); + var extension = data.getExtension(proto.jspb.test.IsExtension.extField); + assertNotNull(extension); + assertEquals('ext1', extension.getExt1()); + }); + + it('testSetExtension', function() { + var data = new proto.jspb.test.HasExtensions(); + var extensionMessage = new proto.jspb.test.IsExtension(['is_extension']); + data.setExtension(proto.jspb.test.IsExtension.extField, extensionMessage); + var obj = data.toObject(); + assertNotNull(data.getExtension(proto.jspb.test.IsExtension.extField)); + assertEquals('is_extension', obj.extField.ext1); + }); + + /** + * Note that group is long deprecated, we only support it because JsPb has + * a goal of being able to generate JS classes for all proto descriptors. + */ + it('testGroups', function() { + var group = new proto.jspb.test.TestGroup(); + var someGroup = new proto.jspb.test.TestGroup.RepeatedGroup(); + someGroup.setId('g1'); + someGroup.setSomeBoolList([true, false]); + group.setRepeatedGroupList([someGroup]); + var groups = group.getRepeatedGroupList(); + assertEquals('g1', groups[0].getId()); + assertObjectEquals([true, false], groups[0].getSomeBoolList()); + assertObjectEquals( + {id: 'g1', someBoolList: [true, false]}, groups[0].toObject()); + assertObjectEquals( + { + repeatedGroupList: [{id: 'g1', someBoolList: [true, false]}], + requiredGroup: {id: undefined}, + optionalGroup: undefined, + requiredSimple: {aRepeatedStringList: [], aString: undefined}, + optionalSimple: undefined, + id: undefined + }, + group.toObject()); + var group1 = new proto.jspb.test.TestGroup1(); + group1.setGroup(someGroup); + assertEquals(someGroup, group1.getGroup()); + }); + + it('testNonExtensionFieldsAfterExtensionRange', function() { + var data = [{'1': 'a_string'}]; + var message = new proto.jspb.test.Complex(data); + assertArrayEquals([], message.getARepeatedStringList()); + }); + + it('testReservedGetterNames', function() { + var message = new proto.jspb.test.TestReservedNames(); + message.setExtension$(11); + message.setExtension(proto.jspb.test.TestReservedNamesExtension.foo, 12); + assertEquals(11, message.getExtension$()); + assertEquals( + 12, + message.getExtension(proto.jspb.test.TestReservedNamesExtension.foo)); + assertObjectEquals({extension: 11, foo: 12}, message.toObject()); + }); + + it('testInitializeMessageWithUnsetOneof', function() { + var message = new proto.jspb.test.TestMessageWithOneof([]); + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase + .PARTIAL_ONEOF_NOT_SET, + message.getPartialOneofCase()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.RecursiveOneofCase + .RECURSIVE_ONEOF_NOT_SET, + message.getRecursiveOneofCase()); + }); + + it('testInitializeMessageWithSingleValueSetInOneof', function() { + var message = new proto.jspb.test.TestMessageWithOneof([, , 'x']); + + assertEquals('x', message.getPone()); + assertEquals('', message.getPthree()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PONE, + message.getPartialOneofCase()); + }); + + it('testKeepsLastWireValueSetInUnion_multipleValues', function() { + var message = new proto.jspb.test.TestMessageWithOneof([, , 'x', , 'y']); + + assertEquals('', message.getPone()); + assertEquals('y', message.getPthree()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PTHREE, + message.getPartialOneofCase()); + }); + + it('testSettingOneofFieldClearsOthers', function() { + var message = new proto.jspb.test.TestMessageWithOneof; + assertEquals('', message.getPone()); + assertEquals('', message.getPthree()); + assertFalse(message.hasPone()); + assertFalse(message.hasPthree()); + + message.setPone('hi'); + assertEquals('hi', message.getPone()); + assertEquals('', message.getPthree()); + assertTrue(message.hasPone()); + assertFalse(message.hasPthree()); + + message.setPthree('bye'); + assertEquals('', message.getPone()); + assertEquals('bye', message.getPthree()); + assertFalse(message.hasPone()); + assertTrue(message.hasPthree()); + }); + + it('testSettingOneofFieldDoesNotClearFieldsFromOtherUnions', function() { + var other = new proto.jspb.test.TestMessageWithOneof; + var message = new proto.jspb.test.TestMessageWithOneof; + assertEquals('', message.getPone()); + assertEquals('', message.getPthree()); + assertUndefined(message.getRone()); + assertFalse(message.hasPone()); + assertFalse(message.hasPthree()); + + message.setPone('hi'); + message.setRone(other); + assertEquals('hi', message.getPone()); + assertEquals('', message.getPthree()); + assertEquals(other, message.getRone()); + assertTrue(message.hasPone()); + assertFalse(message.hasPthree()); + + message.setPthree('bye'); + assertEquals('', message.getPone()); + assertEquals('bye', message.getPthree()); + assertEquals(other, message.getRone()); + assertFalse(message.hasPone()); + assertTrue(message.hasPthree()); + }); + + it('testUnsetsOneofCaseWhenFieldIsCleared', function() { + var message = new proto.jspb.test.TestMessageWithOneof; + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase + .PARTIAL_ONEOF_NOT_SET, + message.getPartialOneofCase()); + + message.setPone('hi'); + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PONE, + message.getPartialOneofCase()); + + message.clearPone(); + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase + .PARTIAL_ONEOF_NOT_SET, + message.getPartialOneofCase()); + }); + + it('testMessageWithDefaultOneofValues', function() { + var message = new proto.jspb.test.TestMessageWithOneof; + assertEquals(1234, message.getAone()); + assertEquals(0, message.getAtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofACase + .DEFAULT_ONEOF_A_NOT_SET, + message.getDefaultOneofACase()); + + message.setAone(567); + assertEquals(567, message.getAone()); + assertEquals(0, message.getAtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.AONE, + message.getDefaultOneofACase()); + + message.setAtwo(890); + assertEquals(1234, message.getAone()); + assertEquals(890, message.getAtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.ATWO, + message.getDefaultOneofACase()); + + message.clearAtwo(); + assertEquals(1234, message.getAone()); + assertEquals(0, message.getAtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofACase + .DEFAULT_ONEOF_A_NOT_SET, + message.getDefaultOneofACase()); + }); + + it('testMessageWithDefaultOneofValues_defaultNotOnFirstField', function() { + var message = new proto.jspb.test.TestMessageWithOneof; + assertEquals(0, message.getBone()); + assertEquals(1234, message.getBtwo()); + assertFalse(message.hasBone()); + assertFalse(message.hasBtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase + .DEFAULT_ONEOF_B_NOT_SET, + message.getDefaultOneofBCase()); + + message.setBone(2); + assertEquals(2, message.getBone()); + assertEquals(1234, message.getBtwo()); + assertTrue(message.hasBone()); + assertFalse(message.hasBtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BONE, + message.getDefaultOneofBCase()); + + message.setBtwo(3); + assertEquals(0, message.getBone()); + assertFalse(message.hasBone()); + assertTrue(message.hasBtwo()); + assertEquals(3, message.getBtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BTWO, + message.getDefaultOneofBCase()); + + message.clearBtwo(); + assertEquals(0, message.getBone()); + assertFalse(message.hasBone()); + assertFalse(message.hasBtwo()); + assertEquals(1234, message.getBtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase + .DEFAULT_ONEOF_B_NOT_SET, + message.getDefaultOneofBCase()); + }); + + it('testInitializeMessageWithOneofDefaults', function() { + var message = + new proto.jspb.test.TestMessageWithOneof(new Array(9).concat(567)); + assertEquals(567, message.getAone()); + assertEquals(0, message.getAtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.AONE, + message.getDefaultOneofACase()); + + message = + new proto.jspb.test.TestMessageWithOneof(new Array(10).concat(890)); + assertEquals(1234, message.getAone()); + assertEquals(890, message.getAtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.ATWO, + message.getDefaultOneofACase()); + + message = + new proto.jspb.test.TestMessageWithOneof(new Array(9).concat(567, 890)); + assertEquals(1234, message.getAone()); + assertEquals(890, message.getAtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofACase.ATWO, + message.getDefaultOneofACase()); + }); + + it('testInitializeMessageWithOneofDefaults_defaultNotSetOnFirstField', + function() { + var message; + + message = + new proto.jspb.test.TestMessageWithOneof(new Array(11).concat(567)); + assertEquals(567, message.getBone()); + assertEquals(1234, message.getBtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BONE, + message.getDefaultOneofBCase()); + + message = + new proto.jspb.test.TestMessageWithOneof(new Array(12).concat(890)); + assertEquals(0, message.getBone()); + assertEquals(890, message.getBtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BTWO, + message.getDefaultOneofBCase()); + + message = new proto.jspb.test.TestMessageWithOneof( + new Array(11).concat(567, 890)); + assertEquals(0, message.getBone()); + assertEquals(890, message.getBtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.DefaultOneofBCase.BTWO, + message.getDefaultOneofBCase()); + }); + + it('testOneofContainingAnotherMessage', function() { + var message = new proto.jspb.test.TestMessageWithOneof; + assertEquals( + proto.jspb.test.TestMessageWithOneof.RecursiveOneofCase + .RECURSIVE_ONEOF_NOT_SET, + message.getRecursiveOneofCase()); + + var other = new proto.jspb.test.TestMessageWithOneof; + message.setRone(other); + assertEquals(other, message.getRone()); + assertEquals('', message.getRtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.RecursiveOneofCase.RONE, + message.getRecursiveOneofCase()); + + message.setRtwo('hi'); + assertUndefined(message.getRone()); + assertEquals('hi', message.getRtwo()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.RecursiveOneofCase.RTWO, + message.getRecursiveOneofCase()); + }); + + it('testQueryingOneofCaseEnsuresOnlyOneFieldIsSetInUnderlyingArray', + function() { + var message = new proto.jspb.test.TestMessageWithOneof; + message.setPone('x'); + assertEquals('x', message.getPone()); + assertEquals('', message.getPthree()); + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PONE, + message.getPartialOneofCase()); + + var array = message.toArray(); + assertEquals('x', array[2]); + assertUndefined(array[4]); + array[4] = 'y'; + + assertEquals( + proto.jspb.test.TestMessageWithOneof.PartialOneofCase.PTHREE, + message.getPartialOneofCase()); + assertUndefined(array[2]); + assertEquals('y', array[4]); + }); + + it('testFloatingPointFieldsSupportNan', function() { + var assertNan = function(x) { + assertTrue( + 'Expected ' + x + ' (' + goog.typeOf(x) + ') to be NaN.', + typeof x === 'number' && isNaN(x)); + }; + + var message = new proto.jspb.test.FloatingPointFields([ + 'NaN', 'NaN', ['NaN', 'NaN'], 'NaN', 'NaN', 'NaN', ['NaN', 'NaN'], 'NaN' + ]); + assertNan(message.getOptionalFloatField()); + assertNan(message.getRequiredFloatField()); + assertNan(message.getRepeatedFloatFieldList()[0]); + assertNan(message.getRepeatedFloatFieldList()[1]); + assertNan(message.getDefaultFloatField()); + assertNan(message.getOptionalDoubleField()); + assertNan(message.getRequiredDoubleField()); + assertNan(message.getRepeatedDoubleFieldList()[0]); + assertNan(message.getRepeatedDoubleFieldList()[1]); + assertNan(message.getDefaultDoubleField()); + }); +}); diff --git a/tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.1.0/test3.proto b/tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.1.0/test3.proto new file mode 100644 index 0000000..940a552 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/js/compatibility_tests/v3.1.0/test3.proto @@ -0,0 +1,53 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto2"; + +option java_package = "com.google.apps.jspb.proto"; +option java_multiple_files = true; + +package jspb.exttest; + +message TestExtensionsMessage { + optional int32 intfield = 1; + extensions 100 to max; +} + +message ExtensionMessage { + extend TestExtensionsMessage { + optional ExtensionMessage ext_field = 100; + } + optional string ext1 = 1; +} + +extend TestExtensionsMessage { + optional ExtensionMessage floating_msg_field = 101; + optional string floating_str_field = 102; +} diff --git a/tools/go-generator/cmd/generator/_protobuf/js/data.proto b/tools/go-generator/cmd/generator/_protobuf/js/data.proto new file mode 100644 index 0000000..ca815ca --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/js/data.proto @@ -0,0 +1,50 @@ +// 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: mwr@google.com (Mark Rawling) + +syntax = "proto2"; + +package jspb.test; + +option java_package = "com.google.apps.jspb.proto"; +option java_multiple_files = true; + +// legacy data, must be nested +message data { + message NestedData { + required string str = 1; + } +} + +// new data, does not require nesting +message UnnestedData { + required string str = 1; +} diff --git a/tools/go-generator/cmd/generator/_protobuf/js/experimental/benchmarks/code_size/apps_jspb/popular_types_proto3.js b/tools/go-generator/cmd/generator/_protobuf/js/experimental/benchmarks/code_size/apps_jspb/popular_types_proto3.js new file mode 100644 index 0000000..9b80428 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/js/experimental/benchmarks/code_size/apps_jspb/popular_types_proto3.js @@ -0,0 +1,53 @@ +/** + * @fileoverview The code size benchmark of apps JSPB for proto3 popular types. + */ +goog.module('protobuf.benchmark.code_size.apps_jspb.PopularTypesProto3'); + +// const ForeignEnum = goog.require('proto.proto3_unittest.ForeignEnum'); +const ForeignMessage = goog.require('proto.proto3_unittest.ForeignMessage'); +const TestAllTypes = goog.require('proto.proto3_unittest.TestAllTypes'); +const {ensureCommonBaseLine} = goog.require('protobuf.benchmark.codeSize.codeSizeBase'); + +ensureCommonBaseLine(); + +/** + * @return {string} + */ +function accessPopularTypes() { + const msgAllTypes = TestAllTypes.deserialize(''); + msgAllTypes.addRepeatedForeignMessage(ForeignMessage.deserialize(''), 1); + [ForeignMessage.deserialize('')].forEach( + (e) => msgAllTypes.addRepeatedForeignMessage(e)); + + msgAllTypes.setOptionalString(''); + msgAllTypes.setOptionalInt32(1); + msgAllTypes.setOptionalForeignMessage(ForeignMessage.deserialize('')); + msgAllTypes.setOptionalBool(true); + // msgAllTypes.setOptionalForeignEnum(ForeignEnum.FOREIGN_BAR); + msgAllTypes.setOptionalInt64(1); + msgAllTypes.setOptionalDouble(1.0); + msgAllTypes.setRepeatedForeignMessageList([ForeignMessage.deserialize('')]); + let arrayVal = msgAllTypes.getRepeatedForeignMessageList(); + arrayVal[0] = ForeignMessage.deserialize(''); + msgAllTypes.setRepeatedForeignMessageList(arrayVal); + msgAllTypes.setOptionalUint64(1); + + let s = ''; + s += msgAllTypes.getOptionalString(); + s += msgAllTypes.getOptionalInt32(); + s += msgAllTypes.getOptionalForeignMessage(); + s += msgAllTypes.getOptionalBool(); + // s += msgAllTypes.getOptionalForeignEnum(); + s += msgAllTypes.getOptionalInt64(); + s += msgAllTypes.getOptionalDouble(); + s += msgAllTypes.getRepeatedForeignMessageList(); + s += msgAllTypes.getRepeatedForeignMessageList()[0]; + s += msgAllTypes.getRepeatedForeignMessageList().length; + s += msgAllTypes.getOptionalUint64(); + + s += msgAllTypes.serialize(); + + return s; +} + +goog.global['__hiddenTest'] += accessPopularTypes(); diff --git a/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/bytestring.js b/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/bytestring.js new file mode 100644 index 0000000..d6af5f1 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/bytestring.js @@ -0,0 +1,183 @@ +/** + * @fileoverview Provides ByteString as a basic data type for protos. + */ +goog.module('protobuf.ByteString'); + +const base64 = goog.require('goog.crypt.base64'); +const {arrayBufferSlice, cloneArrayBufferView, hashUint8Array, uint8ArrayEqual} = goog.require('protobuf.binary.typedArrays'); + +/** + * Immutable sequence of bytes. + * + * Bytes can be obtained as an ArrayBuffer or a base64 encoded string. + * @final + */ +class ByteString { + /** + * @param {?Uint8Array} bytes + * @param {?string} base64 + * @private + */ + constructor(bytes, base64) { + /** @private {?Uint8Array}*/ + this.bytes_ = bytes; + /** @private {?string} */ + this.base64_ = base64; + /** @private {number} */ + this.hashCode_ = 0; + } + + /** + * Constructs a ByteString instance from a base64 string. + * @param {string} value + * @return {!ByteString} + */ + static fromBase64String(value) { + if (value == null) { + throw new Error('value must not be null'); + } + return new ByteString(/* bytes */ null, value); + } + + /** + * Constructs a ByteString from an array buffer. + * @param {!ArrayBuffer} bytes + * @param {number=} start + * @param {number=} end + * @return {!ByteString} + */ + static fromArrayBuffer(bytes, start = 0, end = undefined) { + return new ByteString( + new Uint8Array(arrayBufferSlice(bytes, start, end)), /* base64 */ null); + } + + /** + * Constructs a ByteString from any ArrayBufferView (e.g. DataView, + * TypedArray, Uint8Array, etc.). + * @param {!ArrayBufferView} bytes + * @return {!ByteString} + */ + static fromArrayBufferView(bytes) { + return new ByteString(cloneArrayBufferView(bytes), /* base64 */ null); + } + + /** + * Constructs a ByteString from an Uint8Array. DON'T MODIFY the underlying + * ArrayBuffer, since the ByteString directly uses it without making a copy. + * + * This method exists so that internal APIs can construct a ByteString without + * paying the penalty of copying an ArrayBuffer when that ArrayBuffer is not + * supposed to change. It is exposed to a limited number of internal classes + * through bytestring_internal.js. + * + * @param {!Uint8Array} bytes + * @return {!ByteString} + * @package + */ + static fromUint8ArrayUnsafe(bytes) { + return new ByteString(bytes, /* base64 */ null); + } + + /** + * Returns this ByteString as an ArrayBuffer. + * @return {!ArrayBuffer} + */ + toArrayBuffer() { + const bytes = this.ensureBytes_(); + return arrayBufferSlice( + bytes.buffer, bytes.byteOffset, bytes.byteOffset + bytes.byteLength); + } + + /** + * Returns this ByteString as an Uint8Array. DON'T MODIFY the returned array, + * since the ByteString holds the reference to the same array. + * + * This method exists so that internal APIs can get contents of a ByteString + * without paying the penalty of copying an ArrayBuffer. It is exposed to a + * limited number of internal classes through bytestring_internal.js. + * @return {!Uint8Array} + * @package + */ + toUint8ArrayUnsafe() { + return this.ensureBytes_(); + } + + /** + * Returns this ByteString as a base64 encoded string. + * @return {string} + */ + toBase64String() { + return this.ensureBase64String_(); + } + + /** + * Returns true for Bytestrings that contain identical values. + * @param {*} other + * @return {boolean} + */ + equals(other) { + if (this === other) { + return true; + } + + if (!(other instanceof ByteString)) { + return false; + } + + const otherByteString = /** @type {!ByteString} */ (other); + return uint8ArrayEqual(this.ensureBytes_(), otherByteString.ensureBytes_()); + } + + /** + * Returns a number (int32) that is suitable for using in hashed structures. + * @return {number} + */ + hashCode() { + if (this.hashCode_ == 0) { + this.hashCode_ = hashUint8Array(this.ensureBytes_()); + } + return this.hashCode_; + } + + /** + * Returns true if the bytestring is empty. + * @return {boolean} + */ + isEmpty() { + if (this.bytes_ != null && this.bytes_.byteLength == 0) { + return true; + } + if (this.base64_ != null && this.base64_.length == 0) { + return true; + } + return false; + } + + /** + * @return {!Uint8Array} + * @private + */ + ensureBytes_() { + if (this.bytes_) { + return this.bytes_; + } + return this.bytes_ = base64.decodeStringToUint8Array( + /** @type {string} */ (this.base64_)); + } + + /** + * @return {string} + * @private + */ + ensureBase64String_() { + if (this.base64_ == null) { + this.base64_ = base64.encodeByteArray(this.bytes_); + } + return this.base64_; + } +} + +/** @const {!ByteString} */ +ByteString.EMPTY = new ByteString(new Uint8Array(0), null); + +exports = ByteString; diff --git a/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/binary_storage_test.js b/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/binary_storage_test.js new file mode 100644 index 0000000..2686f04 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/binary_storage_test.js @@ -0,0 +1,165 @@ +/** + * @fileoverview Tests for storage.js. + */ +goog.module('protobuf.runtime.BinaryStorageTest'); + +goog.setTestOnly(); + +const BinaryStorage = goog.require('protobuf.runtime.BinaryStorage'); +const {Field} = goog.require('protobuf.binary.field'); + +/** + * @type {number} + */ +const DEFAULT_PIVOT = 24; + +const /** !Field */ field1 = + Field.fromDecodedValue(/* decodedValue= */ 1, /* encoder= */ () => {}); +const /** !Field */ field2 = + Field.fromDecodedValue(/* decodedValue= */ 2, /* encoder= */ () => {}); +const /** !Field */ field3 = + Field.fromDecodedValue(/* decodedValue= */ 3, /* encoder= */ () => {}); +const /** !Field */ field4 = + Field.fromDecodedValue(/* decodedValue= */ 4, /* encoder= */ () => {}); + +/** + * Returns the number of fields stored. + * + * @param {!BinaryStorage} storage + * @return {number} + */ +function getStorageSize(storage) { + let size = 0; + storage.forEach(() => void size++); + return size; +} + +describe('BinaryStorage', () => { + it('sets and gets a field not greater than the pivot', () => { + const storage = new BinaryStorage(DEFAULT_PIVOT); + + storage.set(1, field1); + storage.set(DEFAULT_PIVOT, field2); + + expect(storage.getPivot()).toBe(DEFAULT_PIVOT); + expect(storage.get(1)).toBe(field1); + expect(storage.get(DEFAULT_PIVOT)).toBe(field2); + }); + + it('sets and gets a field greater than the pivot', () => { + const storage = new BinaryStorage(DEFAULT_PIVOT); + + storage.set(DEFAULT_PIVOT + 1, field1); + storage.set(100000, field2); + + expect(storage.get(DEFAULT_PIVOT + 1)).toBe(field1); + expect(storage.get(100000)).toBe(field2); + }); + + it('sets and gets a field when pivot is zero', () => { + const storage = new BinaryStorage(0); + + storage.set(0, field1); + storage.set(100000, field2); + + expect(storage.getPivot()).toBe(0); + expect(storage.get(0)).toBe(field1); + expect(storage.get(100000)).toBe(field2); + }); + + it('sets and gets a field when pivot is undefined', () => { + const storage = new BinaryStorage(); + + storage.set(0, field1); + storage.set(DEFAULT_PIVOT, field2); + storage.set(DEFAULT_PIVOT + 1, field3); + + expect(storage.getPivot()).toBe(DEFAULT_PIVOT); + expect(storage.get(0)).toBe(field1); + expect(storage.get(DEFAULT_PIVOT)).toBe(field2); + expect(storage.get(DEFAULT_PIVOT + 1)).toBe(field3); + }); + + it('returns undefined for nonexistent fields', () => { + const storage = new BinaryStorage(DEFAULT_PIVOT); + + expect(storage.get(1)).toBeUndefined(); + expect(storage.get(DEFAULT_PIVOT)).toBeUndefined(); + expect(storage.get(DEFAULT_PIVOT + 1)).toBeUndefined(); + expect(storage.get(100000)).toBeUndefined(); + }); + + it('returns undefined for nonexistent fields after map initialization', + () => { + const storage = new BinaryStorage(DEFAULT_PIVOT); + storage.set(100001, field1); + + expect(storage.get(1)).toBeUndefined(); + expect(storage.get(DEFAULT_PIVOT)).toBeUndefined(); + expect(storage.get(DEFAULT_PIVOT + 1)).toBeUndefined(); + expect(storage.get(100000)).toBeUndefined(); + }); + + it('deletes a field in delete() when values are only in array', () => { + const storage = new BinaryStorage(DEFAULT_PIVOT); + storage.set(1, field1); + + storage.delete(1); + + expect(storage.get(1)).toBeUndefined(); + }); + + it('deletes a field in delete() when values are both in array and map', + () => { + const storage = new BinaryStorage(DEFAULT_PIVOT); + storage.set(DEFAULT_PIVOT, field2); + storage.set(DEFAULT_PIVOT + 1, field3); + + storage.delete(DEFAULT_PIVOT); + storage.delete(DEFAULT_PIVOT + 1); + + expect(storage.get(DEFAULT_PIVOT)).toBeUndefined(); + expect(storage.get(DEFAULT_PIVOT + 1)).toBeUndefined(); + }); + + it('deletes a field in delete() when values are only in map', () => { + const storage = new BinaryStorage(DEFAULT_PIVOT); + storage.set(100000, field4); + + storage.delete(100000); + + expect(storage.get(100000)).toBeUndefined(); + }); + + it('loops over all the elements in forEach()', () => { + const storage = new BinaryStorage(DEFAULT_PIVOT); + storage.set(1, field1); + storage.set(DEFAULT_PIVOT, field2); + storage.set(DEFAULT_PIVOT + 1, field3); + storage.set(100000, field4); + + const fields = new Map(); + storage.forEach( + (field, fieldNumber) => void fields.set(fieldNumber, field)); + + expect(fields.size).toEqual(4); + expect(fields.get(1)).toBe(field1); + expect(storage.get(DEFAULT_PIVOT)).toBe(field2); + expect(storage.get(DEFAULT_PIVOT + 1)).toBe(field3); + expect(fields.get(100000)).toBe(field4); + }); + + it('creates a shallow copy of the storage in shallowCopy()', () => { + const storage = new BinaryStorage(DEFAULT_PIVOT); + storage.set(1, field1); + storage.set(100000, field2); + + const copy = storage.shallowCopy(); + + expect(getStorageSize(copy)).toEqual(2); + expect(copy.get(1)).not.toBe(field1); + expect(copy.get(1).getDecodedValue()).toEqual(1); + expect(copy.get(100000)).not.toBe(field1); + expect(copy.get(100000).getDecodedValue()).toEqual(2); + }); +}); diff --git a/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/indexer.js b/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/indexer.js new file mode 100644 index 0000000..205a34e --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/indexer.js @@ -0,0 +1,55 @@ +/** + * @fileoverview Utilities to index a binary proto by fieldnumbers without + * relying on strutural proto information. + */ +goog.module('protobuf.binary.indexer'); + +const BinaryStorage = goog.require('protobuf.runtime.BinaryStorage'); +const BufferDecoder = goog.require('protobuf.binary.BufferDecoder'); +const WireType = goog.require('protobuf.binary.WireType'); +const {Field} = goog.require('protobuf.binary.field'); +const {checkCriticalState} = goog.require('protobuf.internal.checks'); +const {skipField, tagToFieldNumber, tagToWireType} = goog.require('protobuf.binary.tag'); + +/** + * Appends a new entry in the index array for the given field number. + * @param {!BinaryStorage} storage + * @param {number} fieldNumber + * @param {!WireType} wireType + * @param {number} startIndex + */ +function addIndexEntry(storage, fieldNumber, wireType, startIndex) { + const field = storage.get(fieldNumber); + if (field !== undefined) { + field.addIndexEntry(wireType, startIndex); + } else { + storage.set(fieldNumber, Field.fromFirstIndexEntry(wireType, startIndex)); + } +} + +/** + * Creates an index of field locations in a given binary protobuf. + * @param {!BufferDecoder} bufferDecoder + * @param {number|undefined} pivot + * @return {!BinaryStorage} + * @package + */ +function buildIndex(bufferDecoder, pivot) { + bufferDecoder.setCursor(bufferDecoder.startIndex()); + + const storage = new BinaryStorage(pivot); + while (bufferDecoder.hasNext()) { + const tag = bufferDecoder.getUnsignedVarint32(); + const wireType = tagToWireType(tag); + const fieldNumber = tagToFieldNumber(tag); + checkCriticalState(fieldNumber > 0, `Invalid field number ${fieldNumber}`); + addIndexEntry(storage, fieldNumber, wireType, bufferDecoder.cursor()); + skipField(bufferDecoder, wireType, fieldNumber); + } + return storage; +} + +exports = { + buildIndex, + tagToWireType, +}; diff --git a/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/packed_double_test_pairs.js b/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/packed_double_test_pairs.js new file mode 100644 index 0000000..de2cb55 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/packed_double_test_pairs.js @@ -0,0 +1,52 @@ +goog.module('protobuf.binary.packedDoubleTestPairs'); + +const BufferDecoder = goog.require('protobuf.binary.BufferDecoder'); +const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper'); + +/** + * An array of Pairs of packed double values and their bit representation. + * This is used to test encoding and decoding from/to the protobuf wire format. + * @return {!Array<{name: string, doubleValues: !Array, + * bufferDecoder: !BufferDecoder, skip_writer: ?boolean}>} + */ +function getPackedDoublePairs() { + return [ + { + name: 'empty value', + doubleValues: [], + bufferDecoder: createBufferDecoder(0x00), + skip_writer: true, + }, + { + name: 'single value', + doubleValues: [1], + bufferDecoder: createBufferDecoder( + 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x3F), + }, + { + name: 'multiple values', + doubleValues: [1, 0], + bufferDecoder: createBufferDecoder( + 0x10, // length + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xF0, + 0x3F, // 1 + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, // 0 + ), + }, + ]; +} + +exports = {getPackedDoublePairs}; diff --git a/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/packed_float_test_pairs.js b/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/packed_float_test_pairs.js new file mode 100644 index 0000000..6d12046 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/packed_float_test_pairs.js @@ -0,0 +1,34 @@ +goog.module('protobuf.binary.packedFloatTestPairs'); + +const BufferDecoder = goog.require('protobuf.binary.BufferDecoder'); +const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper'); + +/** + * An array of Pairs of packed float values and their bit representation. + * This is used to test encoding and decoding from/to the protobuf wire format. + * @return {!Array<{name: string, floatValues: !Array, + * bufferDecoder: !BufferDecoder, skip_writer: ?boolean}>} + */ +function getPackedFloatPairs() { + return [ + { + name: 'empty value', + floatValues: [], + bufferDecoder: createBufferDecoder(0x00), + skip_writer: true, + }, + { + name: 'single value', + floatValues: [1], + bufferDecoder: createBufferDecoder(0x04, 0x00, 0x00, 0x80, 0x3F), + }, + { + name: 'multiple values', + floatValues: [1, 0], + bufferDecoder: createBufferDecoder( + 0x08, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00), + }, + ]; +} + +exports = {getPackedFloatPairs}; diff --git a/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/packed_int32_test_pairs.js b/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/packed_int32_test_pairs.js new file mode 100644 index 0000000..fbe5f40 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/packed_int32_test_pairs.js @@ -0,0 +1,33 @@ +goog.module('protobuf.binary.packedInt32TestPairs'); + +const BufferDecoder = goog.require('protobuf.binary.BufferDecoder'); +const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper'); + +/** + * An array of Pairs of packed int32 values and their bit representation. + * This is used to test encoding and decoding from/to the protobuf wire format. + * @return {!Array<{name: string, int32Values: !Array, + * bufferDecoder: !BufferDecoder, skip_writer: ?boolean}>} + */ +function getPackedInt32Pairs() { + return [ + { + name: 'empty value', + int32Values: [], + bufferDecoder: createBufferDecoder(0x00), + skip_writer: true, + }, + { + name: 'single value', + int32Values: [1], + bufferDecoder: createBufferDecoder(0x01, 0x01), + }, + { + name: 'multiple values', + int32Values: [1, 0], + bufferDecoder: createBufferDecoder(0x02, 0x01, 0x00), + }, + ]; +} + +exports = {getPackedInt32Pairs}; diff --git a/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/packed_int64_test_pairs.js b/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/packed_int64_test_pairs.js new file mode 100644 index 0000000..a6cf54e --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/packed_int64_test_pairs.js @@ -0,0 +1,34 @@ +goog.module('protobuf.binary.packedInt64TestPairs'); + +const BufferDecoder = goog.require('protobuf.binary.BufferDecoder'); +const Int64 = goog.require('protobuf.Int64'); +const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper'); + +/** + * An array of Pairs of packed int64 values and their bit representation. + * This is used to test encoding and decoding from/to the protobuf wire format. + * @return {!Array<{name: string, int64Values: !Array, + * bufferDecoder: !BufferDecoder, skip_writer: ?boolean}>} + */ +function getPackedInt64Pairs() { + return [ + { + name: 'empty value', + int64Values: [], + bufferDecoder: createBufferDecoder(0x00), + skip_writer: true, + }, + { + name: 'single value', + int64Values: [Int64.fromInt(1)], + bufferDecoder: createBufferDecoder(0x01, 0x01), + }, + { + name: 'multiple values', + int64Values: [Int64.fromInt(1), Int64.fromInt(0)], + bufferDecoder: createBufferDecoder(0x02, 0x01, 0x00), + }, + ]; +} + +exports = {getPackedInt64Pairs}; diff --git a/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/packed_sfixed64_test_pairs.js b/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/packed_sfixed64_test_pairs.js new file mode 100644 index 0000000..5b86703 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/packed_sfixed64_test_pairs.js @@ -0,0 +1,53 @@ +goog.module('protobuf.binary.packedSfixed64TestPairs'); + +const BufferDecoder = goog.require('protobuf.binary.BufferDecoder'); +const Int64 = goog.require('protobuf.Int64'); +const {createBufferDecoder} = goog.require('protobuf.binary.bufferDecoderHelper'); + +/** + * An array of Pairs of packed sfixed64 values and their bit representation. + * This is used to test encoding and decoding from/to the protobuf wire format. + * @return {!Array<{name: string, sfixed64Values: !Array, + * bufferDecoder: !BufferDecoder, skip_writer: ?boolean}>} + */ +function getPackedSfixed64Pairs() { + return [ + { + name: 'empty value', + sfixed64Values: [], + bufferDecoder: createBufferDecoder(0x00), + skip_writer: true, + }, + { + name: 'single value', + sfixed64Values: [Int64.fromInt(1)], + bufferDecoder: createBufferDecoder( + 0x08, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00), + }, + { + name: 'multiple values', + sfixed64Values: [Int64.fromInt(1), Int64.fromInt(0)], + bufferDecoder: createBufferDecoder( + 0x10, // length + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, // 1 + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, // 2 + ), + }, + ]; +} + +exports = {getPackedSfixed64Pairs}; diff --git a/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/tag.js b/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/tag.js new file mode 100644 index 0000000..b288df3 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/js/experimental/runtime/kernel/tag.js @@ -0,0 +1,144 @@ +goog.module('protobuf.binary.tag'); + +const BufferDecoder = goog.require('protobuf.binary.BufferDecoder'); +const WireType = goog.require('protobuf.binary.WireType'); +const {checkCriticalElementIndex, checkCriticalState} = goog.require('protobuf.internal.checks'); + +/** + * Returns wire type stored in a tag. + * Protos store the wire type as the first 3 bit of a tag. + * @param {number} tag + * @return {!WireType} + */ +function tagToWireType(tag) { + return /** @type {!WireType} */ (tag & 0x07); +} + +/** + * Returns the field number stored in a tag. + * Protos store the field number in the upper 29 bits of a 32 bit number. + * @param {number} tag + * @return {number} + */ +function tagToFieldNumber(tag) { + return tag >>> 3; +} + +/** + * Combines wireType and fieldNumber into a tag. + * @param {!WireType} wireType + * @param {number} fieldNumber + * @return {number} + */ +function createTag(wireType, fieldNumber) { + return (fieldNumber << 3 | wireType) >>> 0; +} + +/** + * Returns the length, in bytes, of the field in the tag stream, less the tag + * itself. + * Note: This moves the cursor in the bufferDecoder. + * @param {!BufferDecoder} bufferDecoder + * @param {number} start + * @param {!WireType} wireType + * @param {number} fieldNumber + * @return {number} + * @private + */ +function getTagLength(bufferDecoder, start, wireType, fieldNumber) { + bufferDecoder.setCursor(start); + skipField(bufferDecoder, wireType, fieldNumber); + return bufferDecoder.cursor() - start; +} + +/** + * @param {number} value + * @return {number} + */ +function get32BitVarintLength(value) { + if (value < 0) { + return 5; + } + let size = 1; + while (value >= 128) { + size++; + value >>>= 7; + } + return size; +} + +/** + * Skips over a field. + * Note: If the field is a start group the entire group will be skipped, placing + * the cursor onto the next field. + * @param {!BufferDecoder} bufferDecoder + * @param {!WireType} wireType + * @param {number} fieldNumber + */ +function skipField(bufferDecoder, wireType, fieldNumber) { + switch (wireType) { + case WireType.VARINT: + checkCriticalElementIndex( + bufferDecoder.cursor(), bufferDecoder.endIndex()); + bufferDecoder.skipVarint(); + return; + case WireType.FIXED64: + bufferDecoder.skip(8); + return; + case WireType.DELIMITED: + checkCriticalElementIndex( + bufferDecoder.cursor(), bufferDecoder.endIndex()); + const length = bufferDecoder.getUnsignedVarint32(); + bufferDecoder.skip(length); + return; + case WireType.START_GROUP: + const foundGroup = skipGroup_(bufferDecoder, fieldNumber); + checkCriticalState(foundGroup, 'No end group found.'); + return; + case WireType.FIXED32: + bufferDecoder.skip(4); + return; + default: + throw new Error(`Unexpected wire type: ${wireType}`); + } +} + +/** + * Skips over fields until it finds the end of a given group consuming the stop + * group tag. + * @param {!BufferDecoder} bufferDecoder + * @param {number} groupFieldNumber + * @return {boolean} Whether the end group tag was found. + * @private + */ +function skipGroup_(bufferDecoder, groupFieldNumber) { + // On a start group we need to keep skipping fields until we find a + // corresponding stop group + // Note: Since we are calling skipField from here nested groups will be + // handled by recursion of this method and thus we will not see a nested + // STOP GROUP here unless there is something wrong with the input data. + while (bufferDecoder.hasNext()) { + const tag = bufferDecoder.getUnsignedVarint32(); + const wireType = tagToWireType(tag); + const fieldNumber = tagToFieldNumber(tag); + + if (wireType === WireType.END_GROUP) { + checkCriticalState( + groupFieldNumber === fieldNumber, + `Expected stop group for fieldnumber ${groupFieldNumber} not found.`); + return true; + } else { + skipField(bufferDecoder, wireType, fieldNumber); + } + } + return false; +} + +exports = { + createTag, + get32BitVarintLength, + getTagLength, + skipField, + tagToWireType, + tagToFieldNumber, +}; diff --git a/tools/go-generator/cmd/generator/_protobuf/js/package.json b/tools/go-generator/cmd/generator/_protobuf/js/package.json new file mode 100644 index 0000000..f7e8a3f --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/js/package.json @@ -0,0 +1,27 @@ +{ + "name": "google-protobuf", + "version": "3.19.4", + "description": "Protocol Buffers for JavaScript", + "main": "google-protobuf.js", + "files": [ + "google" + ], + "dependencies": {}, + "devDependencies": { + "glob": "~7.1.4", + "google-closure-compiler": "~20190819.0.0", + "google-closure-deps": "^20210406.0.0", + "google-closure-library": "~20190819.0.0", + "gulp": "~4.0.2", + "jasmine": "~3.4.0" + }, + "scripts": { + "test": "node ./node_modules/gulp/bin/gulp.js test" + }, + "repository": { + "type": "git", + "url": "https://github.com/protocolbuffers/protobuf/tree/master/js" + }, + "author": "Google Protocol Buffers Team", + "license": "BSD-3-Clause" +} diff --git a/tools/go-generator/cmd/generator/_protobuf/js/test13.proto b/tools/go-generator/cmd/generator/_protobuf/js/test13.proto new file mode 100644 index 0000000..b9895d8 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/js/test13.proto @@ -0,0 +1,70 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto2"; + +package jspb.filenametest.package1; + +message TestMessage { + extensions 1 to 100; +} + +extend TestMessage { + optional int32 a = 1; +} + +enum TestEnum { + VALUE_0 = 0; + VALUE_1 = 1; +} + +message TestLooooooooooooooooooooooooooooooooooooooooooooooooooooooongName1 { + optional TestLooooooooooooooooooooooooooooooooooooooooooooooooooooooongName2 + a = 1; + optional int32 b = 2; +} + +message TestLooooooooooooooooooooooooooooooooooooooooooooooooooooooongName2 { + optional TestLooooooooooooooooooooooooooooooooooooooooooooooooooooooongName3 + a = 1; + optional int32 b = 2; +} + +message TestLooooooooooooooooooooooooooooooooooooooooooooooooooooooongName3 { + optional TestLooooooooooooooooooooooooooooooooooooooooooooooooooooooongName4 + a = 1; + optional int32 b = 2; +} + +message TestLooooooooooooooooooooooooooooooooooooooooooooooooooooooongName4 { + optional TestLooooooooooooooooooooooooooooooooooooooooooooooooooooooongName1 + a = 1; + optional int32 b = 2; +} diff --git a/tools/go-generator/cmd/generator/_protobuf/js/test2.proto b/tools/go-generator/cmd/generator/_protobuf/js/test2.proto new file mode 100644 index 0000000..e9457e7 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/js/test2.proto @@ -0,0 +1,60 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto2"; + +package jspb.test; + +import "test.proto"; + +option java_package = "com.google.apps.jspb.proto"; +option java_multiple_files = true; + +message TestExtensionsMessage { + optional int32 intfield = 1; + extensions 100 to max; +} + +message ExtensionMessage { + extend TestExtensionsMessage { + optional ExtensionMessage ext_field = 100; + } + optional string ext1 = 1; +} + +// Floating extensions are only supported when generating a _lib.js library. +extend TestExtensionsMessage { + optional ExtensionMessage floating_msg_field = 101; + optional string floating_str_field = 102; +} + +message ForeignNestedFieldMessage { + optional Deeply.Nested.Message deeply_nested_message = 1; +} diff --git a/tools/go-generator/cmd/generator/_protobuf/js/test9.proto b/tools/go-generator/cmd/generator/_protobuf/js/test9.proto new file mode 100644 index 0000000..9f68085 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/js/test9.proto @@ -0,0 +1,39 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto2"; + +package jspb.exttest.strict.nine; + +message Simple9 { + required string a_string = 1; + repeated string a_repeated_string = 2; + optional bool a_boolean = 3; +} diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/README.md b/tools/go-generator/cmd/generator/_protobuf/kokoro/README.md new file mode 100644 index 0000000..590d7bd --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/README.md @@ -0,0 +1,12 @@ + +Kokoro Infrastructure +---------------------- + +The files in this directory serve as plumbing for running Protobuf +tests under Kokoro, our internal CI. + +We have shared this part of our CI configuration in hopes that it is +helpful to contributors who want to better understand the details of +our test and release processes. If there are changes, please file an +issue; unfortunately, we may not be able to accept PRs (but feel free +to send one if it helps to explain the issue). diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/aarch64/dockcross_helpers/run_dockcross_manylinux2014_aarch64.sh b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/aarch64/dockcross_helpers/run_dockcross_manylinux2014_aarch64.sh new file mode 100755 index 0000000..ba34fa7 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/aarch64/dockcross_helpers/run_dockcross_manylinux2014_aarch64.sh @@ -0,0 +1,36 @@ +#!/bin/bash + +set -e + +# go to the repo root +cd $(dirname $0)/../../../.. + +if [[ -t 0 ]]; then + DOCKER_TTY_ARGS="-it" +else + # The input device on kokoro is not a TTY, so -it does not work. + DOCKER_TTY_ARGS= +fi + +# Pin the dockcross image since newer versions of the image break the build +PINNED_DOCKCROSS_IMAGE_VERSION=dockcross/manylinux2014-aarch64:20210803-41e5c69 + +# running dockcross image without any arguments generates a wrapper +# scripts that can be used to run commands under the dockcross image +# easily. +# See https://github.com/dockcross/dockcross#usage for details +docker run $DOCKER_TTY_ARGS --rm $PINNED_DOCKCROSS_IMAGE_VERSION >dockcross-manylinux2014-aarch64.sh +chmod +x dockcross-manylinux2014-aarch64.sh + +# the wrapper script has CRLF line endings and bash doesn't like that +# so we change CRLF line endings into LF. +sed -i 's/\r//g' dockcross-manylinux2014-aarch64.sh + +# The dockcross wrapper script runs arbitrary commands under the selected dockcross +# image with the following properties which make its use very convenient: +# * the current working directory is mounted under /work so the container can easily +# access the current workspace +# * the processes in the container run under the same UID and GID as the host process so unlike +# vanilla "docker run" invocations, the workspace doesn't get polluted with files +# owned by root. +./dockcross-manylinux2014-aarch64.sh --image $PINNED_DOCKCROSS_IMAGE_VERSION -- "$@" diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/aarch64/test_php_aarch64.sh b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/aarch64/test_php_aarch64.sh new file mode 100755 index 0000000..b11ef43 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/aarch64/test_php_aarch64.sh @@ -0,0 +1,31 @@ +#!/bin/bash + +set -ex + +# go to the repo root +cd $(dirname $0)/../../.. + +# there is no php testing docker image readily available, so we build +# our own. It's a aarch64 image, but that's fine since qemu will +# automatically be used to run the commands in the dockerfile. +docker build -t testimage_protobuf_php_arm64v8 kokoro/linux/aarch64/testimage_protobuf_php_arm64v8 + +if [[ -t 0 ]]; then + DOCKER_TTY_ARGS="-it" +else + # The input device on kokoro is not a TTY, so -it does not work. + DOCKER_TTY_ARGS= +fi + +# crosscompile protoc as we will later need it for the php build. +# we build it under the dockcross/manylinux2014-aarch64 image so that the resulting protoc binary is compatible +# with a wide range of linux distros (including any docker images we will use later to build and test php) +kokoro/linux/aarch64/dockcross_helpers/run_dockcross_manylinux2014_aarch64.sh kokoro/linux/aarch64/protoc_crosscompile_aarch64.sh + +# use an actual aarch64 docker image (with a real aarch64 php) to run build & test protobuf php under an emulator +# * mount the protobuf root as /work to be able to access the crosscompiled files +# * to avoid running the process inside docker as root (which can pollute the workspace with files owned by root), we force +# running under current user's UID and GID. To be able to do that, we need to provide a home directory for the user +# otherwise the UID would be homeless under the docker container and pip install wouldn't work. For simplicity, +# we just run map the user's home to a throwaway temporary directory +docker run $DOCKER_TTY_ARGS --rm --user "$(id -u):$(id -g)" -e "HOME=/home/fake-user" -v "$(mktemp -d):/home/fake-user" -v "$(pwd)":/work -w /work testimage_protobuf_php_arm64v8 kokoro/linux/aarch64/php_build_and_run_tests_with_qemu_aarch64.sh diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/bazel/continuous.cfg b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/bazel/continuous.cfg new file mode 100644 index 0000000..13cfef1 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/bazel/continuous.cfg @@ -0,0 +1,5 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/bazel/build.sh" +timeout_mins: 15 diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/cpp_aarch64/continuous.cfg b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/cpp_aarch64/continuous.cfg new file mode 100644 index 0000000..0f1be4a --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/cpp_aarch64/continuous.cfg @@ -0,0 +1,5 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/cpp_aarch64/build.sh" +timeout_mins: 120 diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/cpp_distcheck/continuous.cfg b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/cpp_distcheck/continuous.cfg new file mode 100644 index 0000000..4289f6a --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/cpp_distcheck/continuous.cfg @@ -0,0 +1,5 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/cpp_distcheck/build.sh" +timeout_mins: 1440 diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/csharp/continuous.cfg b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/csharp/continuous.cfg new file mode 100644 index 0000000..3d17767 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/csharp/continuous.cfg @@ -0,0 +1,5 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/csharp/build.sh" +timeout_mins: 1440 diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/dist_install/continuous.cfg b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/dist_install/continuous.cfg new file mode 100644 index 0000000..b1e0b20 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/dist_install/continuous.cfg @@ -0,0 +1,5 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/dist_install/build.sh" +timeout_mins: 1440 diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/dockerfile/test/csharp/Dockerfile b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/dockerfile/test/csharp/Dockerfile new file mode 100644 index 0000000..c07fcbc --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/dockerfile/test/csharp/Dockerfile @@ -0,0 +1,41 @@ +FROM debian:buster + +# Install dependencies. We start with the basic ones require to build protoc +# and the C++ build +RUN apt-get update && apt-get install -y \ + autoconf \ + autotools-dev \ + build-essential \ + bzip2 \ + ccache \ + curl \ + gcc \ + git \ + libc6 \ + libc6-dbg \ + libc6-dev \ + libgtest-dev \ + libtool \ + make \ + parallel \ + time \ + wget \ + && apt-get clean + +# Update ca-certificates to fix known buster + .NET 5 issue +# https://github.com/NuGet/Announcements/issues/49 +RUN apt-get update && apt-get install -y ca-certificates && apt-get clean + +# dotnet SDK prerequisites +RUN apt-get update && apt-get install -y libunwind8 libicu63 && apt-get clean + +# Install dotnet SDK via install script +RUN wget -q https://dot.net/v1/dotnet-install.sh && \ + chmod u+x dotnet-install.sh && \ + ./dotnet-install.sh --version 3.1.415 && \ + ./dotnet-install.sh --version 6.0.100 && \ + ln -s /root/.dotnet/dotnet /usr/local/bin + +RUN wget -q www.nuget.org/NuGet.exe -O /usr/local/bin/nuget.exe + +ENV DOTNET_SKIP_FIRST_TIME_EXPERIENCE true diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/dockerfile/test/javascript/Dockerfile b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/dockerfile/test/javascript/Dockerfile new file mode 100644 index 0000000..184828f --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/dockerfile/test/javascript/Dockerfile @@ -0,0 +1,37 @@ +FROM ubuntu:latest + +RUN apt-get update && apt-get install -y gnupg + +# Install dependencies. We start with the basic ones require to build protoc +# and the C++ build +RUN apt-get clean && apt-get update && apt-get install -y --force-yes \ + autoconf \ + autotools-dev \ + build-essential \ + bzip2 \ + ccache \ + curl \ + gcc \ + git \ + libc6 \ + libc6-dbg \ + libc6-dev \ + libgtest-dev \ + libtool \ + make \ + parallel \ + time \ + wget \ + && apt-get clean + + +################## +# Javascript dependencies. +# We need to set these environment variables so that the Docker build does not +# have to ask for this information while it is installing the tzdata package. +RUN DEBIAN_FRONTEND="noninteractive" TZ="America/Los_Angeles" \ + apt-get install -y \ + # -- For javascript and closure compiler -- \ + npm \ + default-jre \ + python diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/java_aarch64/presubmit.cfg b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/java_aarch64/presubmit.cfg new file mode 100644 index 0000000..5db46d4 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/java_aarch64/presubmit.cfg @@ -0,0 +1,11 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/java_aarch64/build.sh" +timeout_mins: 120 + +action { + define_artifacts { + regex: "**/sponge_log.xml" + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/java_jdk7/presubmit.cfg b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/java_jdk7/presubmit.cfg new file mode 100644 index 0000000..07a9df5 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/java_jdk7/presubmit.cfg @@ -0,0 +1,11 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/java_jdk7/build.sh" +timeout_mins: 120 + +action { + define_artifacts { + regex: "**/sponge_log.xml" + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/javascript/continuous.cfg b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/javascript/continuous.cfg new file mode 100644 index 0000000..b42f522 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/javascript/continuous.cfg @@ -0,0 +1,11 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/javascript/build.sh" +timeout_mins: 120 + +action { + define_artifacts { + regex: "**/sponge_log.xml" + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/jruby92/presubmit.cfg b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/jruby92/presubmit.cfg new file mode 100644 index 0000000..3339584 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/jruby92/presubmit.cfg @@ -0,0 +1,11 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/jruby92/build.sh" +timeout_mins: 120 + +action { + define_artifacts { + regex: "**/sponge_log.xml" + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/make_test_output.py b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/make_test_output.py new file mode 100644 index 0000000..9853685 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/make_test_output.py @@ -0,0 +1,94 @@ +"""Gathers output from test runs and create an XML file in JUnit format. + +The output files from the individual tests have been written in a directory +structure like: + + $DIR/joblog (output from "parallel --joblog joblog") + $DIR/logs/1/cpp/stdout + $DIR/logs/1/cpp/stderr + $DIR/logs/1/csharp/stdout + $DIR/logs/1/csharp/stderr + $DIR/logs/1/java_jdk7/stdout + $DIR/logs/1/java_jdk7/stderr + etc. + +This script bundles them into a single output XML file so Jenkins can show +detailed test results. It runs as the last step before the Jenkins build +finishes. +""" + +import os +import sys +from yattag import Doc +from collections import defaultdict + + +def readtests(basedir): + tests = defaultdict(dict) + + # Sample input (note: separators are tabs). + # + # Seq Host Starttime Runtime Send Receive Exitval Signal Command + # 1 : 1456263838.313 0.005 0 0 0 0 echo A + with open(basedir + "/joblog") as jobs: + firstline = next(jobs) + for line in jobs: + values = line.split("\t") + + name = values[8].split()[-1] + test = tests[name] + test["name"] = name + test["time"] = values[3] + + exitval = values[6] + if int(exitval): + # We don't have a more specific message. User should look at stderr. + test["failure"] = "TEST FAILURE" + else: + test["failure"] = False + + for testname in os.listdir(basedir + "/logs/1"): + test = tests[testname] + + with open(basedir + "/logs/1/" + testname + "/stdout") as f: + test["stdout"] = f.read() + + with open(basedir + "/logs/1/" + testname + "/stderr") as f: + test["stderr"] = f.read() + + # The cpp test is special since it doesn't run under parallel so doesn't show + # up in the job log. + tests["cpp"]["name"] = "cpp" + + with open(basedir + '/logs/1/cpp/build_time', 'r') as f: + tests["cpp"]["time"] = f.read().strip() + tests["cpp"]["failure"] = False + + ret = tests.values() + ret.sort(key=lambda x: x["name"]) + + return ret + + +def genxml(tests): + doc, tag, text = Doc().tagtext() + + with tag("testsuites"): + with tag("testsuite", name="Protobuf Tests"): + for test in tests: + with tag("testcase", name=test["name"], classname=test["name"], + time=test["time"]): + with tag("system-out"): + text(test["stdout"]) + with tag("system-err"): + text(test["stderr"]) + if test["failure"]: + with tag("failure"): + text(test["failure"]) + + return doc.getvalue() + + +sys.stderr.write("make_test_output.py: writing XML from directory: " + + sys.argv[1] + "\n") +print(genxml(readtests(sys.argv[1]))) diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/php80/presubmit.cfg b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/php80/presubmit.cfg new file mode 100644 index 0000000..6d67a8c --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/php80/presubmit.cfg @@ -0,0 +1,5 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/php80/build.sh" +timeout_mins: 20 diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python27_cpp/presubmit.cfg b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python27_cpp/presubmit.cfg new file mode 100644 index 0000000..ace22d0 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python27_cpp/presubmit.cfg @@ -0,0 +1,11 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/python27_cpp/build.sh" +timeout_mins: 120 + +action { + define_artifacts { + regex: "**/sponge_log.xml" + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python310_cpp/build.sh b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python310_cpp/build.sh new file mode 100755 index 0000000..2903a2d --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python310_cpp/build.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# +# This is the top-level script we give to Kokoro as the entry point for +# running the "pull request" project: +# +# This script selects a specific Dockerfile (for building a Docker image) and +# a script to run inside that image. Then we delegate to the general +# build_and_run_docker.sh script. + +# Change to repo root +cd $(dirname $0)/../../.. + +export DOCKERHUB_ORGANIZATION=protobuftesting +export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python310 +export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh +export OUTPUT_DIR=testoutput +export TEST_SET="python310_cpp" +./kokoro/linux/build_and_run_docker.sh diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python35/build.sh b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python35/build.sh new file mode 100755 index 0000000..66ea03f --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python35/build.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# +# This is the top-level script we give to Kokoro as the entry point for +# running the "pull request" project: +# +# This script selects a specific Dockerfile (for building a Docker image) and +# a script to run inside that image. Then we delegate to the general +# build_and_run_docker.sh script. + +# Change to repo root +cd $(dirname $0)/../../.. + +export DOCKERHUB_ORGANIZATION=protobuftesting +export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python35 +export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh +export OUTPUT_DIR=testoutput +export TEST_SET="python35" +./kokoro/linux/build_and_run_docker.sh diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python35/presubmit.cfg b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python35/presubmit.cfg new file mode 100644 index 0000000..2b3e12c --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python35/presubmit.cfg @@ -0,0 +1,11 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/python35/build.sh" +timeout_mins: 120 + +action { + define_artifacts { + regex: "**/sponge_log.xml" + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python36_cpp/presubmit.cfg b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python36_cpp/presubmit.cfg new file mode 100644 index 0000000..df9e714 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python36_cpp/presubmit.cfg @@ -0,0 +1,11 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/python36_cpp/build.sh" +timeout_mins: 120 + +action { + define_artifacts { + regex: "**/sponge_log.xml" + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python37/build.sh b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python37/build.sh new file mode 100755 index 0000000..2117a27 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python37/build.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# +# This is the top-level script we give to Kokoro as the entry point for +# running the "pull request" project: +# +# This script selects a specific Dockerfile (for building a Docker image) and +# a script to run inside that image. Then we delegate to the general +# build_and_run_docker.sh script. + +# Change to repo root +cd $(dirname $0)/../../.. + +export DOCKERHUB_ORGANIZATION=protobuftesting +export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python37 +export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh +export OUTPUT_DIR=testoutput +export TEST_SET="python37" +./kokoro/linux/build_and_run_docker.sh diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python37_cpp/presubmit.cfg b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python37_cpp/presubmit.cfg new file mode 100644 index 0000000..49c441f --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python37_cpp/presubmit.cfg @@ -0,0 +1,11 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/python37_cpp/build.sh" +timeout_mins: 120 + +action { + define_artifacts { + regex: "**/sponge_log.xml" + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python38/presubmit.cfg b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python38/presubmit.cfg new file mode 100644 index 0000000..76425d2 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python38/presubmit.cfg @@ -0,0 +1,11 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/python38/build.sh" +timeout_mins: 120 + +action { + define_artifacts { + regex: "**/sponge_log.xml" + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python38_cpp/build.sh b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python38_cpp/build.sh new file mode 100755 index 0000000..b43859b --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python38_cpp/build.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# +# This is the top-level script we give to Kokoro as the entry point for +# running the "pull request" project: +# +# This script selects a specific Dockerfile (for building a Docker image) and +# a script to run inside that image. Then we delegate to the general +# build_and_run_docker.sh script. + +# Change to repo root +cd $(dirname $0)/../../.. + +export DOCKERHUB_ORGANIZATION=protobuftesting +export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python38 +export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh +export OUTPUT_DIR=testoutput +export TEST_SET="python38_cpp" +./kokoro/linux/build_and_run_docker.sh diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python39/build.sh b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python39/build.sh new file mode 100755 index 0000000..497dc66 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python39/build.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# +# This is the top-level script we give to Kokoro as the entry point for +# running the "pull request" project: +# +# This script selects a specific Dockerfile (for building a Docker image) and +# a script to run inside that image. Then we delegate to the general +# build_and_run_docker.sh script. + +# Change to repo root +cd $(dirname $0)/../../.. + +export DOCKERHUB_ORGANIZATION=protobuftesting +export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python39 +export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh +export OUTPUT_DIR=testoutput +export TEST_SET="python39" +./kokoro/linux/build_and_run_docker.sh diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python39_cpp/build.sh b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python39_cpp/build.sh new file mode 100755 index 0000000..f45d2ec --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python39_cpp/build.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# +# This is the top-level script we give to Kokoro as the entry point for +# running the "pull request" project: +# +# This script selects a specific Dockerfile (for building a Docker image) and +# a script to run inside that image. Then we delegate to the general +# build_and_run_docker.sh script. + +# Change to repo root +cd $(dirname $0)/../../.. + +export DOCKERHUB_ORGANIZATION=protobuftesting +export DOCKERFILE_DIR=kokoro/linux/dockerfile/test/python39 +export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh +export OUTPUT_DIR=testoutput +export TEST_SET="python39_cpp" +./kokoro/linux/build_and_run_docker.sh diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python_compatibility/build.sh b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python_compatibility/build.sh new file mode 100755 index 0000000..1ba3539 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/python_compatibility/build.sh @@ -0,0 +1,17 @@ +#!/bin/bash +# +# This is the top-level script we give to Kokoro as the entry point for +# running the "pull request" project: +# +# This script selects a specific Dockerfile (for building a Docker image) and +# a script to run inside that image. Then we delegate to the general +# build_and_run_docker.sh script. + +# Change to repo root +cd $(dirname $0)/../../.. + +export DOCKERFILE_DIR=kokoro/linux/64-bit +export DOCKER_RUN_SCRIPT=kokoro/linux/pull_request_in_docker.sh +export OUTPUT_DIR=testoutput +export TEST_SET="python_compatibility" +./kokoro/linux/build_and_run_docker.sh diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/ruby27/continuous.cfg b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/ruby27/continuous.cfg new file mode 100644 index 0000000..9cce8c9 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/linux/ruby27/continuous.cfg @@ -0,0 +1,11 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/linux/ruby27/build.sh" +timeout_mins: 120 + +action { + define_artifacts { + regex: "**/sponge_log.xml" + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/macos/cpp/build.sh b/tools/go-generator/cmd/generator/_protobuf/kokoro/macos/cpp/build.sh new file mode 100755 index 0000000..bae2ebb --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/macos/cpp/build.sh @@ -0,0 +1,11 @@ +#!/bin/bash +# +# Build file to set up and run tests + +# Change to repo root +cd $(dirname $0)/../../.. + +# Prepare worker environment to run tests +source kokoro/macos/prepare_build_macos_rc + +./tests.sh cpp diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/macos/objectivec_cocoapods_integration/build.sh b/tools/go-generator/cmd/generator/_protobuf/kokoro/macos/objectivec_cocoapods_integration/build.sh new file mode 100755 index 0000000..f96d289 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/macos/objectivec_cocoapods_integration/build.sh @@ -0,0 +1,11 @@ +#!/bin/bash +# +# Build file to set up and run tests + +# Change to repo root +cd $(dirname $0)/../../.. + +# Prepare worker environment to run tests +source kokoro/macos/prepare_build_macos_rc + +./tests.sh objectivec_cocoapods_integration diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/macos/objectivec_osx/continuous.cfg b/tools/go-generator/cmd/generator/_protobuf/kokoro/macos/objectivec_osx/continuous.cfg new file mode 100644 index 0000000..41bd46a --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/macos/objectivec_osx/continuous.cfg @@ -0,0 +1,5 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/macos/objectivec_osx/build.sh" +timeout_mins: 1440 diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/macos/php7.0_mac/presubmit.cfg b/tools/go-generator/cmd/generator/_protobuf/kokoro/macos/php7.0_mac/presubmit.cfg new file mode 100644 index 0000000..c2c1811 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/macos/php7.0_mac/presubmit.cfg @@ -0,0 +1,5 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/macos/php7.0_mac/build.sh" +timeout_mins: 1440 diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/release/csharp/windows/continuous.cfg b/tools/go-generator/cmd/generator/_protobuf/kokoro/release/csharp/windows/continuous.cfg new file mode 100644 index 0000000..f508c65 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/release/csharp/windows/continuous.cfg @@ -0,0 +1,11 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/release/csharp/windows/build_nuget.bat" +timeout_mins: 60 + +action { + define_artifacts { + regex: "**/*.nupkg" + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/release/protoc/macos/build.sh b/tools/go-generator/cmd/generator/_protobuf/kokoro/release/protoc/macos/build.sh new file mode 100755 index 0000000..47c9bfa --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/release/protoc/macos/build.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +set -ex +CXXFLAGS_COMMON="-std=c++14 -DNDEBUG -mmacosx-version-min=10.9" + +cd github/protobuf +./autogen.sh + +mkdir build64 && cd build64 +export CXXFLAGS="$CXXFLAGS_COMMON -m64" +../configure --disable-shared +make -j4 +file src/protoc +otool -L src/protoc | grep dylib +cd .. diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/release/protoc/macos/release.cfg b/tools/go-generator/cmd/generator/_protobuf/kokoro/release/protoc/macos/release.cfg new file mode 100644 index 0000000..da903d0 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/release/protoc/macos/release.cfg @@ -0,0 +1,8 @@ +# Configuration for Mac OSX protoc release builds +build_file: "protobuf/kokoro/release/protoc/macos/build.sh" + +action { + define_artifacts { + regex: "**/protoc" + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/release/python/linux/build_artifacts.sh b/tools/go-generator/cmd/generator/_protobuf/kokoro/release/python/linux/build_artifacts.sh new file mode 100755 index 0000000..9a3fc58 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/release/python/linux/build_artifacts.sh @@ -0,0 +1,90 @@ +#!/bin/bash + +set -ex + +# change to repo root +pushd $(dirname $0)/../../../.. + +# Create stage dir +ORIGINAL_DIR=`pwd` +pushd .. +cp -R $ORIGINAL_DIR stage +export STAGE_DIR="`pwd`/stage" +popd + +export REPO_DIR=protobuf +export BUILD_VERSION=`grep -i "version" python/google/protobuf/__init__.py | grep -o "'.*'" | tr -d "'"` + +export BUILD_COMMIT=`git rev-parse HEAD` +export PLAT=x86_64 +export UNICODE_WIDTH=32 +export MACOSX_DEPLOYMENT_TARGET=10.9 + +rm -rf artifacts/ +rm -rf multibuild/ +mkdir artifacts +export ARTIFACT_DIR=$(pwd)/artifacts + +git clone https://github.com/matthew-brett/multibuild.git +# Pin multibuild scripts at a known commit to avoid potentially unwanted future changes from +# silently creeping in (see https://github.com/protocolbuffers/protobuf/issues/9180). +# IMPORTANT: always pin multibuild at the same commit for: +# - linux/build_artifacts.sh +# - linux/build_artifacts.sh +# - windows/build_artifacts.bat +(cd multibuild; git checkout b89bb903e94308be79abefa4f436bf123ebb1313) +cp kokoro/release/python/linux/config.sh config.sh + +build_artifact_version() { + MB_PYTHON_VERSION=$1 + cp -R $STAGE_DIR $REPO_DIR + + source multibuild/common_utils.sh + source multibuild/travis_steps.sh + before_install + + clean_code $REPO_DIR $BUILD_COMMIT + + build_wheel $REPO_DIR/python $PLAT + + mv wheelhouse/* $ARTIFACT_DIR + + # Clean up env + rm -rf venv + sudo rm -rf $REPO_DIR +} + +build_x86_64_manylinux1_artifact_version() { + # Explicitly request building manylinux1 wheels, which is no longer the default. + # https://github.com/protocolbuffers/protobuf/issues/9180 + MB_ML_VER=1 + build_artifact_version $@ +} + +build_x86_64_manylinux2010_artifact_version() { + # Explicitly request building manylinux2010 wheels + MB_ML_VER=2010 + build_artifact_version $@ +} + +build_crosscompiled_aarch64_manylinux2014_artifact_version() { + # crosscompilation is only supported with the dockcross manylinux2014 image + DOCKER_IMAGE=dockcross/manylinux2014-aarch64:20210706-65bf2dd + MB_ML_VER=2014 + PLAT=aarch64 + + # TODO(jtatermusch): currently when crosscompiling, "auditwheel repair" will be disabled + # since auditwheel doesn't work for crosscomiled wheels. + build_artifact_version $@ +} + +build_x86_64_manylinux1_artifact_version 3.6 +build_x86_64_manylinux1_artifact_version 3.7 +build_x86_64_manylinux1_artifact_version 3.8 +build_x86_64_manylinux1_artifact_version 3.9 +build_x86_64_manylinux2010_artifact_version 3.10 + +build_crosscompiled_aarch64_manylinux2014_artifact_version 3.7 +build_crosscompiled_aarch64_manylinux2014_artifact_version 3.8 +build_crosscompiled_aarch64_manylinux2014_artifact_version 3.9 +build_crosscompiled_aarch64_manylinux2014_artifact_version 3.10 diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/release/python/linux/config.sh b/tools/go-generator/cmd/generator/_protobuf/kokoro/release/python/linux/config.sh new file mode 100644 index 0000000..8920495 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/release/python/linux/config.sh @@ -0,0 +1,93 @@ +# Define custom utilities +# Test for OSX with [ -n "$IS_OSX" ] + +function pre_build { + # Any stuff that you need to do before you start building the wheels + # Runs in the root directory of this repository. + pushd protobuf + + if [ "$PLAT" == "aarch64" ] + then + local configure_host_flag="--host=aarch64" + fi + + # Build protoc and libprotobuf + ./autogen.sh + CXXFLAGS="-fPIC -g -O2" ./configure $configure_host_flag + make -j8 + + if [ "$PLAT" == "aarch64" ] + then + # we are crosscompiling for aarch64 while running on x64 + # the simplest way for build_py command to be able to generate + # the protos is by running the protoc process under + # an emulator. That way we don't have to build a x64 version + # of protoc. The qemu-arm emulator is already included + # in the dockcross docker image. + # Running protoc under an emulator is fast as protoc doesn't + # really do much. + + # create a simple shell wrapper that runs crosscompiled protoc under qemu + echo '#!/bin/bash' >protoc_qemu_wrapper.sh + echo 'exec qemu-aarch64 "../src/protoc" "$@"' >>protoc_qemu_wrapper.sh + chmod ugo+x protoc_qemu_wrapper.sh + + # PROTOC variable is by build_py step that runs under ./python directory + export PROTOC=../protoc_qemu_wrapper.sh + fi + + # Generate python dependencies. + pushd python + python setup.py build_py + popd + + popd +} + +function bdist_wheel_cmd { + # Builds wheel with bdist_wheel, puts into wheelhouse + # + # It may sometimes be useful to use bdist_wheel for the wheel building + # process. For example, versioneer has problems with versions which are + # fixed with bdist_wheel: + # https://github.com/warner/python-versioneer/issues/121 + local abs_wheelhouse=$1 + + # Modify build version + pwd + ls + + if [ "$PLAT" == "aarch64" ] + then + # when crosscompiling for aarch64, --plat-name needs to be set explicitly + # to end up with correctly named wheel file + # the value should be manylinuxABC_ARCH and dockcross docker image + # conveniently provides the value in the AUDITWHEEL_PLAT env + local plat_name_flag="--plat-name=$AUDITWHEEL_PLAT" + + # override the value of EXT_SUFFIX to make sure the crosscompiled .so files in the wheel have the correct filename suffix + export PROTOCOL_BUFFERS_OVERRIDE_EXT_SUFFIX="$(python -c 'import sysconfig; print(sysconfig.get_config_var("EXT_SUFFIX").replace("-x86_64-linux-gnu.so", "-aarch64-linux-gnu.so"))')" + fi + + python setup.py bdist_wheel --cpp_implementation --compile_static_extension $plat_name_flag + cp dist/*.whl $abs_wheelhouse +} + +function build_wheel { + build_wheel_cmd "bdist_wheel_cmd" $@ +} + +function run_tests { + # Runs tests on installed distribution from an empty directory + python --version + python -c "from google.protobuf.pyext import _message;" +} + +if [ "$PLAT" == "aarch64" ] +then + # when crosscompiling for aarch64, override the default multibuild's repair_wheelhouse logic + # since "auditwheel repair" doesn't work for crosscompiled wheels + function repair_wheelhouse { + echo "Skipping repair_wheelhouse since auditwheel requires build architecture to match wheel architecture." + } +fi diff --git a/tools/go-generator/cmd/generator/_protobuf/kokoro/release/python/windows/presubmit.cfg b/tools/go-generator/cmd/generator/_protobuf/kokoro/release/python/windows/presubmit.cfg new file mode 100644 index 0000000..5261606 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/kokoro/release/python/windows/presubmit.cfg @@ -0,0 +1,8 @@ +# Configuration for Windows protoc release builds +build_file: "protobuf/kokoro/release/python/windows/build_artifacts.bat" + +action { + define_artifacts { + regex: "github/protobuf/artifacts/**" + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/m4/ax_prog_cxx_for_build.m4 b/tools/go-generator/cmd/generator/_protobuf/m4/ax_prog_cxx_for_build.m4 new file mode 100644 index 0000000..8cc0f73 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/m4/ax_prog_cxx_for_build.m4 @@ -0,0 +1,110 @@ +# =========================================================================== +# http://www.gnu.org/software/autoconf-archive/ax_prog_cxx_for_build.html +# =========================================================================== +# +# SYNOPSIS +# +# AX_PROG_CXX_FOR_BUILD +# +# DESCRIPTION +# +# This macro searches for a C++ compiler that generates native +# executables, that is a C++ compiler that surely is not a cross-compiler. +# This can be useful if you have to generate source code at compile-time +# like for example GCC does. +# +# The macro sets the CXX_FOR_BUILD and CXXCPP_FOR_BUILD macros to anything +# needed to compile or link (CXX_FOR_BUILD) and preprocess +# (CXXCPP_FOR_BUILD). The value of these variables can be overridden by +# the user by specifying a compiler with an environment variable (like you +# do for standard CXX). +# +# LICENSE +# +# Copyright (c) 2008 Paolo Bonzini +# Copyright (c) 2012 Avionic Design GmbH +# +# Based on the AX_PROG_CC_FOR_BUILD macro by Paolo Bonzini. +# +# Copying and distribution of this file, with or without modification, are +# permitted in any medium without royalty provided the copyright notice +# and this notice are preserved. This file is offered as-is, without any +# warranty. + +#serial 2 + +AU_ALIAS([AC_PROG_CXX_FOR_BUILD], [AX_PROG_CXX_FOR_BUILD]) +AC_DEFUN([AX_PROG_CXX_FOR_BUILD], [dnl +AC_REQUIRE([AX_PROG_CC_FOR_BUILD])dnl +AC_REQUIRE([AC_PROG_CXX])dnl +AC_REQUIRE([AC_PROG_CXXCPP])dnl +AC_REQUIRE([AC_CANONICAL_HOST])dnl + +dnl Use the standard macros, but make them use other variable names +dnl +pushdef([ac_cv_prog_CXXCPP], ac_cv_build_prog_CXXCPP)dnl +pushdef([ac_cv_prog_gxx], ac_cv_build_prog_gxx)dnl +pushdef([ac_cv_prog_cxx_works], ac_cv_build_prog_cxx_works)dnl +pushdef([ac_cv_prog_cxx_cross], ac_cv_build_prog_cxx_cross)dnl +pushdef([ac_cv_prog_cxx_g], ac_cv_build_prog_cxx_g)dnl +pushdef([CXX], CXX_FOR_BUILD)dnl +pushdef([CXXCPP], CXXCPP_FOR_BUILD)dnl +pushdef([CXXFLAGS], CXXFLAGS_FOR_BUILD)dnl +pushdef([CPPFLAGS], CPPFLAGS_FOR_BUILD)dnl +pushdef([CXXCPPFLAGS], CXXCPPFLAGS_FOR_BUILD)dnl +pushdef([host], build)dnl +pushdef([host_alias], build_alias)dnl +pushdef([host_cpu], build_cpu)dnl +pushdef([host_vendor], build_vendor)dnl +pushdef([host_os], build_os)dnl +pushdef([ac_cv_host], ac_cv_build)dnl +pushdef([ac_cv_host_alias], ac_cv_build_alias)dnl +pushdef([ac_cv_host_cpu], ac_cv_build_cpu)dnl +pushdef([ac_cv_host_vendor], ac_cv_build_vendor)dnl +pushdef([ac_cv_host_os], ac_cv_build_os)dnl +pushdef([ac_cxxcpp], ac_build_cxxcpp)dnl +pushdef([ac_compile], ac_build_compile)dnl +pushdef([ac_link], ac_build_link)dnl + +save_cross_compiling=$cross_compiling +save_ac_tool_prefix=$ac_tool_prefix +cross_compiling=no +ac_tool_prefix= + +AC_PROG_CXX +AC_PROG_CXXCPP + +ac_tool_prefix=$save_ac_tool_prefix +cross_compiling=$save_cross_compiling + +dnl Restore the old definitions +dnl +popdef([ac_link])dnl +popdef([ac_compile])dnl +popdef([ac_cxxcpp])dnl +popdef([ac_cv_host_os])dnl +popdef([ac_cv_host_vendor])dnl +popdef([ac_cv_host_cpu])dnl +popdef([ac_cv_host_alias])dnl +popdef([ac_cv_host])dnl +popdef([host_os])dnl +popdef([host_vendor])dnl +popdef([host_cpu])dnl +popdef([host_alias])dnl +popdef([host])dnl +popdef([CXXCPPFLAGS])dnl +popdef([CPPFLAGS])dnl +popdef([CXXFLAGS])dnl +popdef([CXXCPP])dnl +popdef([CXX])dnl +popdef([ac_cv_prog_cxx_g])dnl +popdef([ac_cv_prog_cxx_cross])dnl +popdef([ac_cv_prog_cxx_works])dnl +popdef([ac_cv_prog_gxx])dnl +popdef([ac_cv_prog_CXXCPP])dnl + +dnl Finally, set Makefile variables +dnl +AC_SUBST([CXXFLAGS_FOR_BUILD])dnl +AC_SUBST([CXXCPPFLAGS_FOR_BUILD])dnl +]) diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBEmpty.pbobjc.m b/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBEmpty.pbobjc.m new file mode 100644 index 0000000..df3e398 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBEmpty.pbobjc.m @@ -0,0 +1,85 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/empty.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "GPBProtocolBuffers_RuntimeSupport.h" +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "GPBEmpty.pbobjc.h" +#endif +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +#pragma mark - GPBEmptyRoot + +@implementation GPBEmptyRoot + +// No extensions in the file and no imports, so no need to generate +// +extensionRegistry. + +@end + +#pragma mark - GPBEmptyRoot_FileDescriptor + +static GPBFileDescriptor *GPBEmptyRoot_FileDescriptor(void) { + // This is called by +initialize so there is no need to worry + // about thread safety of the singleton. + static GPBFileDescriptor *descriptor = NULL; + if (!descriptor) { + GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); + descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf" + objcPrefix:@"GPB" + syntax:GPBFileSyntaxProto3]; + } + return descriptor; +} + +#pragma mark - GPBEmpty + +@implementation GPBEmpty + + +typedef struct GPBEmpty__storage_ { + uint32_t _has_storage_[1]; +} GPBEmpty__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBEmpty class] + rootClass:[GPBEmptyRoot class] + file:GPBEmptyRoot_FileDescriptor() + fields:NULL + fieldCount:0 + storageSize:sizeof(GPBEmpty__storage_) + flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)]; + #if defined(DEBUG) && DEBUG + NSAssert(descriptor == nil, @"Startup recursed!"); + #endif // DEBUG + descriptor = localDescriptor; + } + return descriptor; +} + +@end + + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBProtocolBuffers.m b/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBProtocolBuffers.m new file mode 100644 index 0000000..0545ae9 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBProtocolBuffers.m @@ -0,0 +1,66 @@ +// 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. + +// If you want to build protocol buffers in your own project without adding the +// project dependency, you can just add this file. + + +// This warning seems to treat code differently when it is #imported than when +// it is inline in the file. GPBDictionary.m compiles cleanly in other targets, +// but when #imported here it triggers a bunch of warnings that don't make +// much sense, and don't trigger when compiled directly. So we shut off the +// warnings here. +#pragma clang diagnostic ignored "-Wnullability-completeness" + +#import "GPBArray.m" +#import "GPBCodedInputStream.m" +#import "GPBCodedOutputStream.m" +#import "GPBDescriptor.m" +#import "GPBDictionary.m" +#import "GPBExtensionInternals.m" +#import "GPBExtensionRegistry.m" +#import "GPBMessage.m" +#import "GPBRootObject.m" +#import "GPBUnknownField.m" +#import "GPBUnknownFieldSet.m" +#import "GPBUtilities.m" +#import "GPBWellKnownTypes.m" +#import "GPBWireFormat.m" + +#import "GPBAny.pbobjc.m" +#import "GPBApi.pbobjc.m" +#import "GPBDuration.pbobjc.m" +#import "GPBEmpty.pbobjc.m" +#import "GPBFieldMask.pbobjc.m" +#import "GPBSourceContext.pbobjc.m" +#import "GPBStruct.pbobjc.m" +#import "GPBTimestamp.pbobjc.m" +#import "GPBType.pbobjc.m" +#import "GPBWrappers.pbobjc.m" diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBProtocolBuffers_RuntimeSupport.h b/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBProtocolBuffers_RuntimeSupport.h new file mode 100644 index 0000000..04dde62 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBProtocolBuffers_RuntimeSupport.h @@ -0,0 +1,40 @@ +// 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. + +// This header is meant to only be used by the generated source, it should not +// be included in code using protocol buffers. + +#import "GPBBootstrap.h" + +#import "GPBDescriptor_PackagePrivate.h" +#import "GPBExtensionInternals.h" +#import "GPBMessage_PackagePrivate.h" +#import "GPBRootObject_PackagePrivate.h" +#import "GPBUtilities_PackagePrivate.h" diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBSourceContext.pbobjc.h b/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBSourceContext.pbobjc.h new file mode 100644 index 0000000..7a10336 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBSourceContext.pbobjc.h @@ -0,0 +1,77 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/source_context.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import + #import + #import +#else + #import "GPBDescriptor.h" + #import "GPBMessage.h" + #import "GPBRootObject.h" +#endif + +#if GOOGLE_PROTOBUF_OBJC_VERSION < 30004 +#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. +#endif +#if 30004 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION +#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. +#endif + +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +CF_EXTERN_C_BEGIN + +NS_ASSUME_NONNULL_BEGIN + +#pragma mark - GPBSourceContextRoot + +/** + * Exposes the extension registry for this file. + * + * The base class provides: + * @code + * + (GPBExtensionRegistry *)extensionRegistry; + * @endcode + * which is a @c GPBExtensionRegistry that includes all the extensions defined by + * this file and all files that it depends on. + **/ +GPB_FINAL @interface GPBSourceContextRoot : GPBRootObject +@end + +#pragma mark - GPBSourceContext + +typedef GPB_ENUM(GPBSourceContext_FieldNumber) { + GPBSourceContext_FieldNumber_FileName = 1, +}; + +/** + * `SourceContext` represents information about the source of a + * protobuf element, like the file in which it is defined. + **/ +GPB_FINAL @interface GPBSourceContext : GPBMessage + +/** + * The path-qualified name of the .proto file that contained the associated + * protobuf element. For example: `"google/protobuf/source_context.proto"`. + **/ +@property(nonatomic, readwrite, copy, null_resettable) NSString *fileName; + +@end + +NS_ASSUME_NONNULL_END + +CF_EXTERN_C_END + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBType.pbobjc.m b/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBType.pbobjc.m new file mode 100644 index 0000000..70dae31 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBType.pbobjc.m @@ -0,0 +1,727 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/type.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import +#else + #import "GPBProtocolBuffers_RuntimeSupport.h" +#endif + +#import + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import + #import + #import +#else + #import "GPBType.pbobjc.h" + #import "GPBAny.pbobjc.h" + #import "GPBSourceContext.pbobjc.h" +#endif +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#pragma clang diagnostic ignored "-Wdollar-in-identifier-extension" + +#pragma mark - Objective C Class declarations +// Forward declarations of Objective C classes that we can use as +// static values in struct initializers. +// We don't use [Foo class] because it is not a static value. +GPBObjCClassDeclaration(GPBAny); +GPBObjCClassDeclaration(GPBEnumValue); +GPBObjCClassDeclaration(GPBField); +GPBObjCClassDeclaration(GPBOption); +GPBObjCClassDeclaration(GPBSourceContext); + +#pragma mark - GPBTypeRoot + +@implementation GPBTypeRoot + +// No extensions in the file and none of the imports (direct or indirect) +// defined extensions, so no need to generate +extensionRegistry. + +@end + +#pragma mark - GPBTypeRoot_FileDescriptor + +static GPBFileDescriptor *GPBTypeRoot_FileDescriptor(void) { + // This is called by +initialize so there is no need to worry + // about thread safety of the singleton. + static GPBFileDescriptor *descriptor = NULL; + if (!descriptor) { + GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); + descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf" + objcPrefix:@"GPB" + syntax:GPBFileSyntaxProto3]; + } + return descriptor; +} + +#pragma mark - Enum GPBSyntax + +GPBEnumDescriptor *GPBSyntax_EnumDescriptor(void) { + static _Atomic(GPBEnumDescriptor*) descriptor = nil; + if (!descriptor) { + static const char *valueNames = + "SyntaxProto2\000SyntaxProto3\000"; + static const int32_t values[] = { + GPBSyntax_SyntaxProto2, + GPBSyntax_SyntaxProto3, + }; + GPBEnumDescriptor *worker = + [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GPBSyntax) + valueNames:valueNames + values:values + count:(uint32_t)(sizeof(values) / sizeof(int32_t)) + enumVerifier:GPBSyntax_IsValidValue]; + GPBEnumDescriptor *expected = nil; + if (!atomic_compare_exchange_strong(&descriptor, &expected, worker)) { + [worker release]; + } + } + return descriptor; +} + +BOOL GPBSyntax_IsValidValue(int32_t value__) { + switch (value__) { + case GPBSyntax_SyntaxProto2: + case GPBSyntax_SyntaxProto3: + return YES; + default: + return NO; + } +} + +#pragma mark - GPBType + +@implementation GPBType + +@dynamic name; +@dynamic fieldsArray, fieldsArray_Count; +@dynamic oneofsArray, oneofsArray_Count; +@dynamic optionsArray, optionsArray_Count; +@dynamic hasSourceContext, sourceContext; +@dynamic syntax; + +typedef struct GPBType__storage_ { + uint32_t _has_storage_[1]; + GPBSyntax syntax; + NSString *name; + NSMutableArray *fieldsArray; + NSMutableArray *oneofsArray; + NSMutableArray *optionsArray; + GPBSourceContext *sourceContext; +} GPBType__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "name", + .dataTypeSpecific.clazz = Nil, + .number = GPBType_FieldNumber_Name, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBType__storage_, name), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero), + .dataType = GPBDataTypeString, + }, + { + .name = "fieldsArray", + .dataTypeSpecific.clazz = GPBObjCClass(GPBField), + .number = GPBType_FieldNumber_FieldsArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GPBType__storage_, fieldsArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + { + .name = "oneofsArray", + .dataTypeSpecific.clazz = Nil, + .number = GPBType_FieldNumber_OneofsArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GPBType__storage_, oneofsArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeString, + }, + { + .name = "optionsArray", + .dataTypeSpecific.clazz = GPBObjCClass(GPBOption), + .number = GPBType_FieldNumber_OptionsArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GPBType__storage_, optionsArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + { + .name = "sourceContext", + .dataTypeSpecific.clazz = GPBObjCClass(GPBSourceContext), + .number = GPBType_FieldNumber_SourceContext, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GPBType__storage_, sourceContext), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + { + .name = "syntax", + .dataTypeSpecific.enumDescFunc = GPBSyntax_EnumDescriptor, + .number = GPBType_FieldNumber_Syntax, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GPBType__storage_, syntax), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor | GPBFieldClearHasIvarOnZero), + .dataType = GPBDataTypeEnum, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBType class] + rootClass:[GPBTypeRoot class] + file:GPBTypeRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBType__storage_) + flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)]; + #if defined(DEBUG) && DEBUG + NSAssert(descriptor == nil, @"Startup recursed!"); + #endif // DEBUG + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +int32_t GPBType_Syntax_RawValue(GPBType *message) { + GPBDescriptor *descriptor = [GPBType descriptor]; + GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBType_FieldNumber_Syntax]; + return GPBGetMessageRawEnumField(message, field); +} + +void SetGPBType_Syntax_RawValue(GPBType *message, int32_t value) { + GPBDescriptor *descriptor = [GPBType descriptor]; + GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBType_FieldNumber_Syntax]; + GPBSetMessageRawEnumField(message, field, value); +} + +#pragma mark - GPBField + +@implementation GPBField + +@dynamic kind; +@dynamic cardinality; +@dynamic number; +@dynamic name; +@dynamic typeURL; +@dynamic oneofIndex; +@dynamic packed; +@dynamic optionsArray, optionsArray_Count; +@dynamic jsonName; +@dynamic defaultValue; + +typedef struct GPBField__storage_ { + uint32_t _has_storage_[1]; + GPBField_Kind kind; + GPBField_Cardinality cardinality; + int32_t number; + int32_t oneofIndex; + NSString *name; + NSString *typeURL; + NSMutableArray *optionsArray; + NSString *jsonName; + NSString *defaultValue; +} GPBField__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "kind", + .dataTypeSpecific.enumDescFunc = GPBField_Kind_EnumDescriptor, + .number = GPBField_FieldNumber_Kind, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBField__storage_, kind), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor | GPBFieldClearHasIvarOnZero), + .dataType = GPBDataTypeEnum, + }, + { + .name = "cardinality", + .dataTypeSpecific.enumDescFunc = GPBField_Cardinality_EnumDescriptor, + .number = GPBField_FieldNumber_Cardinality, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GPBField__storage_, cardinality), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor | GPBFieldClearHasIvarOnZero), + .dataType = GPBDataTypeEnum, + }, + { + .name = "number", + .dataTypeSpecific.clazz = Nil, + .number = GPBField_FieldNumber_Number, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GPBField__storage_, number), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero), + .dataType = GPBDataTypeInt32, + }, + { + .name = "name", + .dataTypeSpecific.clazz = Nil, + .number = GPBField_FieldNumber_Name, + .hasIndex = 3, + .offset = (uint32_t)offsetof(GPBField__storage_, name), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero), + .dataType = GPBDataTypeString, + }, + { + .name = "typeURL", + .dataTypeSpecific.clazz = Nil, + .number = GPBField_FieldNumber_TypeURL, + .hasIndex = 4, + .offset = (uint32_t)offsetof(GPBField__storage_, typeURL), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom | GPBFieldClearHasIvarOnZero), + .dataType = GPBDataTypeString, + }, + { + .name = "oneofIndex", + .dataTypeSpecific.clazz = Nil, + .number = GPBField_FieldNumber_OneofIndex, + .hasIndex = 5, + .offset = (uint32_t)offsetof(GPBField__storage_, oneofIndex), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero), + .dataType = GPBDataTypeInt32, + }, + { + .name = "packed", + .dataTypeSpecific.clazz = Nil, + .number = GPBField_FieldNumber_Packed, + .hasIndex = 6, + .offset = 7, // Stored in _has_storage_ to save space. + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero), + .dataType = GPBDataTypeBool, + }, + { + .name = "optionsArray", + .dataTypeSpecific.clazz = GPBObjCClass(GPBOption), + .number = GPBField_FieldNumber_OptionsArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GPBField__storage_, optionsArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + { + .name = "jsonName", + .dataTypeSpecific.clazz = Nil, + .number = GPBField_FieldNumber_JsonName, + .hasIndex = 8, + .offset = (uint32_t)offsetof(GPBField__storage_, jsonName), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero), + .dataType = GPBDataTypeString, + }, + { + .name = "defaultValue", + .dataTypeSpecific.clazz = Nil, + .number = GPBField_FieldNumber_DefaultValue, + .hasIndex = 9, + .offset = (uint32_t)offsetof(GPBField__storage_, defaultValue), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero), + .dataType = GPBDataTypeString, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBField class] + rootClass:[GPBTypeRoot class] + file:GPBTypeRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBField__storage_) + flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)]; +#if !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS + static const char *extraTextFormatInfo = + "\001\006\004\241!!\000"; + [localDescriptor setupExtraTextInfo:extraTextFormatInfo]; +#endif // !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS + #if defined(DEBUG) && DEBUG + NSAssert(descriptor == nil, @"Startup recursed!"); + #endif // DEBUG + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +int32_t GPBField_Kind_RawValue(GPBField *message) { + GPBDescriptor *descriptor = [GPBField descriptor]; + GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBField_FieldNumber_Kind]; + return GPBGetMessageRawEnumField(message, field); +} + +void SetGPBField_Kind_RawValue(GPBField *message, int32_t value) { + GPBDescriptor *descriptor = [GPBField descriptor]; + GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBField_FieldNumber_Kind]; + GPBSetMessageRawEnumField(message, field, value); +} + +int32_t GPBField_Cardinality_RawValue(GPBField *message) { + GPBDescriptor *descriptor = [GPBField descriptor]; + GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBField_FieldNumber_Cardinality]; + return GPBGetMessageRawEnumField(message, field); +} + +void SetGPBField_Cardinality_RawValue(GPBField *message, int32_t value) { + GPBDescriptor *descriptor = [GPBField descriptor]; + GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBField_FieldNumber_Cardinality]; + GPBSetMessageRawEnumField(message, field, value); +} + +#pragma mark - Enum GPBField_Kind + +GPBEnumDescriptor *GPBField_Kind_EnumDescriptor(void) { + static _Atomic(GPBEnumDescriptor*) descriptor = nil; + if (!descriptor) { + static const char *valueNames = + "TypeUnknown\000TypeDouble\000TypeFloat\000TypeInt" + "64\000TypeUint64\000TypeInt32\000TypeFixed64\000Type" + "Fixed32\000TypeBool\000TypeString\000TypeGroup\000Ty" + "peMessage\000TypeBytes\000TypeUint32\000TypeEnum\000" + "TypeSfixed32\000TypeSfixed64\000TypeSint32\000Typ" + "eSint64\000"; + static const int32_t values[] = { + GPBField_Kind_TypeUnknown, + GPBField_Kind_TypeDouble, + GPBField_Kind_TypeFloat, + GPBField_Kind_TypeInt64, + GPBField_Kind_TypeUint64, + GPBField_Kind_TypeInt32, + GPBField_Kind_TypeFixed64, + GPBField_Kind_TypeFixed32, + GPBField_Kind_TypeBool, + GPBField_Kind_TypeString, + GPBField_Kind_TypeGroup, + GPBField_Kind_TypeMessage, + GPBField_Kind_TypeBytes, + GPBField_Kind_TypeUint32, + GPBField_Kind_TypeEnum, + GPBField_Kind_TypeSfixed32, + GPBField_Kind_TypeSfixed64, + GPBField_Kind_TypeSint32, + GPBField_Kind_TypeSint64, + }; + GPBEnumDescriptor *worker = + [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GPBField_Kind) + valueNames:valueNames + values:values + count:(uint32_t)(sizeof(values) / sizeof(int32_t)) + enumVerifier:GPBField_Kind_IsValidValue]; + GPBEnumDescriptor *expected = nil; + if (!atomic_compare_exchange_strong(&descriptor, &expected, worker)) { + [worker release]; + } + } + return descriptor; +} + +BOOL GPBField_Kind_IsValidValue(int32_t value__) { + switch (value__) { + case GPBField_Kind_TypeUnknown: + case GPBField_Kind_TypeDouble: + case GPBField_Kind_TypeFloat: + case GPBField_Kind_TypeInt64: + case GPBField_Kind_TypeUint64: + case GPBField_Kind_TypeInt32: + case GPBField_Kind_TypeFixed64: + case GPBField_Kind_TypeFixed32: + case GPBField_Kind_TypeBool: + case GPBField_Kind_TypeString: + case GPBField_Kind_TypeGroup: + case GPBField_Kind_TypeMessage: + case GPBField_Kind_TypeBytes: + case GPBField_Kind_TypeUint32: + case GPBField_Kind_TypeEnum: + case GPBField_Kind_TypeSfixed32: + case GPBField_Kind_TypeSfixed64: + case GPBField_Kind_TypeSint32: + case GPBField_Kind_TypeSint64: + return YES; + default: + return NO; + } +} + +#pragma mark - Enum GPBField_Cardinality + +GPBEnumDescriptor *GPBField_Cardinality_EnumDescriptor(void) { + static _Atomic(GPBEnumDescriptor*) descriptor = nil; + if (!descriptor) { + static const char *valueNames = + "CardinalityUnknown\000CardinalityOptional\000C" + "ardinalityRequired\000CardinalityRepeated\000"; + static const int32_t values[] = { + GPBField_Cardinality_CardinalityUnknown, + GPBField_Cardinality_CardinalityOptional, + GPBField_Cardinality_CardinalityRequired, + GPBField_Cardinality_CardinalityRepeated, + }; + GPBEnumDescriptor *worker = + [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GPBField_Cardinality) + valueNames:valueNames + values:values + count:(uint32_t)(sizeof(values) / sizeof(int32_t)) + enumVerifier:GPBField_Cardinality_IsValidValue]; + GPBEnumDescriptor *expected = nil; + if (!atomic_compare_exchange_strong(&descriptor, &expected, worker)) { + [worker release]; + } + } + return descriptor; +} + +BOOL GPBField_Cardinality_IsValidValue(int32_t value__) { + switch (value__) { + case GPBField_Cardinality_CardinalityUnknown: + case GPBField_Cardinality_CardinalityOptional: + case GPBField_Cardinality_CardinalityRequired: + case GPBField_Cardinality_CardinalityRepeated: + return YES; + default: + return NO; + } +} + +#pragma mark - GPBEnum + +@implementation GPBEnum + +@dynamic name; +@dynamic enumvalueArray, enumvalueArray_Count; +@dynamic optionsArray, optionsArray_Count; +@dynamic hasSourceContext, sourceContext; +@dynamic syntax; + +typedef struct GPBEnum__storage_ { + uint32_t _has_storage_[1]; + GPBSyntax syntax; + NSString *name; + NSMutableArray *enumvalueArray; + NSMutableArray *optionsArray; + GPBSourceContext *sourceContext; +} GPBEnum__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "name", + .dataTypeSpecific.clazz = Nil, + .number = GPBEnum_FieldNumber_Name, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBEnum__storage_, name), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero), + .dataType = GPBDataTypeString, + }, + { + .name = "enumvalueArray", + .dataTypeSpecific.clazz = GPBObjCClass(GPBEnumValue), + .number = GPBEnum_FieldNumber_EnumvalueArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GPBEnum__storage_, enumvalueArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + { + .name = "optionsArray", + .dataTypeSpecific.clazz = GPBObjCClass(GPBOption), + .number = GPBEnum_FieldNumber_OptionsArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GPBEnum__storage_, optionsArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + { + .name = "sourceContext", + .dataTypeSpecific.clazz = GPBObjCClass(GPBSourceContext), + .number = GPBEnum_FieldNumber_SourceContext, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GPBEnum__storage_, sourceContext), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + { + .name = "syntax", + .dataTypeSpecific.enumDescFunc = GPBSyntax_EnumDescriptor, + .number = GPBEnum_FieldNumber_Syntax, + .hasIndex = 2, + .offset = (uint32_t)offsetof(GPBEnum__storage_, syntax), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor | GPBFieldClearHasIvarOnZero), + .dataType = GPBDataTypeEnum, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBEnum class] + rootClass:[GPBTypeRoot class] + file:GPBTypeRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBEnum__storage_) + flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)]; + #if defined(DEBUG) && DEBUG + NSAssert(descriptor == nil, @"Startup recursed!"); + #endif // DEBUG + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +int32_t GPBEnum_Syntax_RawValue(GPBEnum *message) { + GPBDescriptor *descriptor = [GPBEnum descriptor]; + GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBEnum_FieldNumber_Syntax]; + return GPBGetMessageRawEnumField(message, field); +} + +void SetGPBEnum_Syntax_RawValue(GPBEnum *message, int32_t value) { + GPBDescriptor *descriptor = [GPBEnum descriptor]; + GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBEnum_FieldNumber_Syntax]; + GPBSetMessageRawEnumField(message, field, value); +} + +#pragma mark - GPBEnumValue + +@implementation GPBEnumValue + +@dynamic name; +@dynamic number; +@dynamic optionsArray, optionsArray_Count; + +typedef struct GPBEnumValue__storage_ { + uint32_t _has_storage_[1]; + int32_t number; + NSString *name; + NSMutableArray *optionsArray; +} GPBEnumValue__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "name", + .dataTypeSpecific.clazz = Nil, + .number = GPBEnumValue_FieldNumber_Name, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBEnumValue__storage_, name), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero), + .dataType = GPBDataTypeString, + }, + { + .name = "number", + .dataTypeSpecific.clazz = Nil, + .number = GPBEnumValue_FieldNumber_Number, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GPBEnumValue__storage_, number), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero), + .dataType = GPBDataTypeInt32, + }, + { + .name = "optionsArray", + .dataTypeSpecific.clazz = GPBObjCClass(GPBOption), + .number = GPBEnumValue_FieldNumber_OptionsArray, + .hasIndex = GPBNoHasBit, + .offset = (uint32_t)offsetof(GPBEnumValue__storage_, optionsArray), + .flags = GPBFieldRepeated, + .dataType = GPBDataTypeMessage, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBEnumValue class] + rootClass:[GPBTypeRoot class] + file:GPBTypeRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBEnumValue__storage_) + flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)]; + #if defined(DEBUG) && DEBUG + NSAssert(descriptor == nil, @"Startup recursed!"); + #endif // DEBUG + descriptor = localDescriptor; + } + return descriptor; +} + +@end + +#pragma mark - GPBOption + +@implementation GPBOption + +@dynamic name; +@dynamic hasValue, value; + +typedef struct GPBOption__storage_ { + uint32_t _has_storage_[1]; + NSString *name; + GPBAny *value; +} GPBOption__storage_; + +// This method is threadsafe because it is initially called +// in +initialize for each subclass. ++ (GPBDescriptor *)descriptor { + static GPBDescriptor *descriptor = nil; + if (!descriptor) { + static GPBMessageFieldDescription fields[] = { + { + .name = "name", + .dataTypeSpecific.clazz = Nil, + .number = GPBOption_FieldNumber_Name, + .hasIndex = 0, + .offset = (uint32_t)offsetof(GPBOption__storage_, name), + .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldClearHasIvarOnZero), + .dataType = GPBDataTypeString, + }, + { + .name = "value", + .dataTypeSpecific.clazz = GPBObjCClass(GPBAny), + .number = GPBOption_FieldNumber_Value, + .hasIndex = 1, + .offset = (uint32_t)offsetof(GPBOption__storage_, value), + .flags = GPBFieldOptional, + .dataType = GPBDataTypeMessage, + }, + }; + GPBDescriptor *localDescriptor = + [GPBDescriptor allocDescriptorForClass:[GPBOption class] + rootClass:[GPBTypeRoot class] + file:GPBTypeRoot_FileDescriptor() + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(GPBOption__storage_) + flags:(GPBDescriptorInitializationFlags)(GPBDescriptorInitializationFlag_UsesClassRefs | GPBDescriptorInitializationFlag_Proto3OptionalKnown)]; + #if defined(DEBUG) && DEBUG + NSAssert(descriptor == nil, @"Startup recursed!"); + #endif // DEBUG + descriptor = localDescriptor; + } + return descriptor; +} + +@end + + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBUnknownField.h b/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBUnknownField.h new file mode 100644 index 0000000..5b96023 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBUnknownField.h @@ -0,0 +1,99 @@ +// 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. + +#import + +@class GPBCodedOutputStream; +@class GPBUInt32Array; +@class GPBUInt64Array; +@class GPBUnknownFieldSet; + +NS_ASSUME_NONNULL_BEGIN +/** + * Store an unknown field. These are used in conjunction with + * GPBUnknownFieldSet. + **/ +@interface GPBUnknownField : NSObject + +/** Initialize a field with the given number. */ +- (instancetype)initWithNumber:(int32_t)number; + +/** The field number the data is stored under. */ +@property(nonatomic, readonly, assign) int32_t number; + +/** An array of varint values for this field. */ +@property(nonatomic, readonly, strong) GPBUInt64Array *varintList; + +/** An array of fixed32 values for this field. */ +@property(nonatomic, readonly, strong) GPBUInt32Array *fixed32List; + +/** An array of fixed64 values for this field. */ +@property(nonatomic, readonly, strong) GPBUInt64Array *fixed64List; + +/** An array of data values for this field. */ +@property(nonatomic, readonly, strong) NSArray *lengthDelimitedList; + +/** An array of groups of values for this field. */ +@property(nonatomic, readonly, strong) NSArray *groupList; + +/** + * Add a value to the varintList. + * + * @param value The value to add. + **/ +- (void)addVarint:(uint64_t)value; +/** + * Add a value to the fixed32List. + * + * @param value The value to add. + **/ +- (void)addFixed32:(uint32_t)value; +/** + * Add a value to the fixed64List. + * + * @param value The value to add. + **/ +- (void)addFixed64:(uint64_t)value; +/** + * Add a value to the lengthDelimitedList. + * + * @param value The value to add. + **/ +- (void)addLengthDelimited:(NSData *)value; +/** + * Add a value to the groupList. + * + * @param value The value to add. + **/ +- (void)addGroup:(GPBUnknownFieldSet *)value; + +@end + +NS_ASSUME_NONNULL_END diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBUnknownFieldSet.m b/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBUnknownFieldSet.m new file mode 100644 index 0000000..a7335f0 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBUnknownFieldSet.m @@ -0,0 +1,395 @@ +// 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. + +#import "GPBUnknownFieldSet_PackagePrivate.h" + +#import "GPBCodedInputStream_PackagePrivate.h" +#import "GPBCodedOutputStream.h" +#import "GPBUnknownField_PackagePrivate.h" +#import "GPBUtilities.h" +#import "GPBWireFormat.h" + +#pragma mark Helpers + +static void checkNumber(int32_t number) { + if (number == 0) { + [NSException raise:NSInvalidArgumentException + format:@"Zero is not a valid field number."]; + } +} + +@implementation GPBUnknownFieldSet { + @package + CFMutableDictionaryRef fields_; +} + +static void CopyWorker(const void *key, const void *value, void *context) { +#pragma unused(key) + GPBUnknownField *field = value; + GPBUnknownFieldSet *result = context; + + GPBUnknownField *copied = [field copy]; + [result addField:copied]; + [copied release]; +} + +// Direct access is use for speed, to avoid even internally declaring things +// read/write, etc. The warning is enabled in the project to ensure code calling +// protos can turn on -Wdirect-ivar-access without issues. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdirect-ivar-access" + +- (id)copyWithZone:(NSZone *)zone { + GPBUnknownFieldSet *result = [[GPBUnknownFieldSet allocWithZone:zone] init]; + if (fields_) { + CFDictionaryApplyFunction(fields_, CopyWorker, result); + } + return result; +} + +- (void)dealloc { + if (fields_) { + CFRelease(fields_); + } + [super dealloc]; +} + +- (BOOL)isEqual:(id)object { + BOOL equal = NO; + if ([object isKindOfClass:[GPBUnknownFieldSet class]]) { + GPBUnknownFieldSet *set = (GPBUnknownFieldSet *)object; + if ((fields_ == NULL) && (set->fields_ == NULL)) { + equal = YES; + } else if ((fields_ != NULL) && (set->fields_ != NULL)) { + equal = CFEqual(fields_, set->fields_); + } + } + return equal; +} + +- (NSUInteger)hash { + // Return the hash of the fields dictionary (or just some value). + if (fields_) { + return CFHash(fields_); + } + return (NSUInteger)[GPBUnknownFieldSet class]; +} + +#pragma mark - Public Methods + +- (BOOL)hasField:(int32_t)number { + ssize_t key = number; + return fields_ ? (CFDictionaryGetValue(fields_, (void *)key) != nil) : NO; +} + +- (GPBUnknownField *)getField:(int32_t)number { + ssize_t key = number; + GPBUnknownField *result = + fields_ ? CFDictionaryGetValue(fields_, (void *)key) : nil; + return result; +} + +- (NSUInteger)countOfFields { + return fields_ ? CFDictionaryGetCount(fields_) : 0; +} + +- (NSArray *)sortedFields { + if (!fields_) return [NSArray array]; + size_t count = CFDictionaryGetCount(fields_); + ssize_t keys[count]; + GPBUnknownField *values[count]; + CFDictionaryGetKeysAndValues(fields_, (const void **)keys, + (const void **)values); + struct GPBFieldPair { + ssize_t key; + GPBUnknownField *value; + } pairs[count]; + for (size_t i = 0; i < count; ++i) { + pairs[i].key = keys[i]; + pairs[i].value = values[i]; + }; + qsort_b(pairs, count, sizeof(struct GPBFieldPair), + ^(const void *first, const void *second) { + const struct GPBFieldPair *a = first; + const struct GPBFieldPair *b = second; + return (a->key > b->key) ? 1 : ((a->key == b->key) ? 0 : -1); + }); + for (size_t i = 0; i < count; ++i) { + values[i] = pairs[i].value; + }; + return [NSArray arrayWithObjects:values count:count]; +} + +#pragma mark - Internal Methods + +- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)output { + if (!fields_) return; + size_t count = CFDictionaryGetCount(fields_); + ssize_t keys[count]; + GPBUnknownField *values[count]; + CFDictionaryGetKeysAndValues(fields_, (const void **)keys, + (const void **)values); + if (count > 1) { + struct GPBFieldPair { + ssize_t key; + GPBUnknownField *value; + } pairs[count]; + + for (size_t i = 0; i < count; ++i) { + pairs[i].key = keys[i]; + pairs[i].value = values[i]; + }; + qsort_b(pairs, count, sizeof(struct GPBFieldPair), + ^(const void *first, const void *second) { + const struct GPBFieldPair *a = first; + const struct GPBFieldPair *b = second; + return (a->key > b->key) ? 1 : ((a->key == b->key) ? 0 : -1); + }); + for (size_t i = 0; i < count; ++i) { + GPBUnknownField *value = pairs[i].value; + [value writeToOutput:output]; + } + } else { + [values[0] writeToOutput:output]; + } +} + +- (NSString *)description { + NSMutableString *description = [NSMutableString + stringWithFormat:@"<%@ %p>: TextFormat: {\n", [self class], self]; + NSString *textFormat = GPBTextFormatForUnknownFieldSet(self, @" "); + [description appendString:textFormat]; + [description appendString:@"}"]; + return description; +} + +static void GPBUnknownFieldSetSerializedSize(const void *key, const void *value, + void *context) { +#pragma unused(key) + GPBUnknownField *field = value; + size_t *result = context; + *result += [field serializedSize]; +} + +- (size_t)serializedSize { + size_t result = 0; + if (fields_) { + CFDictionaryApplyFunction(fields_, GPBUnknownFieldSetSerializedSize, + &result); + } + return result; +} + +static void GPBUnknownFieldSetWriteAsMessageSetTo(const void *key, + const void *value, + void *context) { +#pragma unused(key) + GPBUnknownField *field = value; + GPBCodedOutputStream *output = context; + [field writeAsMessageSetExtensionToOutput:output]; +} + +- (void)writeAsMessageSetTo:(GPBCodedOutputStream *)output { + if (fields_) { + CFDictionaryApplyFunction(fields_, GPBUnknownFieldSetWriteAsMessageSetTo, + output); + } +} + +static void GPBUnknownFieldSetSerializedSizeAsMessageSet(const void *key, + const void *value, + void *context) { +#pragma unused(key) + GPBUnknownField *field = value; + size_t *result = context; + *result += [field serializedSizeAsMessageSetExtension]; +} + +- (size_t)serializedSizeAsMessageSet { + size_t result = 0; + if (fields_) { + CFDictionaryApplyFunction( + fields_, GPBUnknownFieldSetSerializedSizeAsMessageSet, &result); + } + return result; +} + +- (NSData *)data { + NSMutableData *data = [NSMutableData dataWithLength:self.serializedSize]; + GPBCodedOutputStream *output = + [[GPBCodedOutputStream alloc] initWithData:data]; + [self writeToCodedOutputStream:output]; + [output release]; + return data; +} + ++ (BOOL)isFieldTag:(int32_t)tag { + return GPBWireFormatGetTagWireType(tag) != GPBWireFormatEndGroup; +} + +- (void)addField:(GPBUnknownField *)field { + int32_t number = [field number]; + checkNumber(number); + if (!fields_) { + // Use a custom dictionary here because the keys are numbers and conversion + // back and forth from NSNumber isn't worth the cost. + fields_ = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, + &kCFTypeDictionaryValueCallBacks); + } + ssize_t key = number; + CFDictionarySetValue(fields_, (const void *)key, field); +} + +- (GPBUnknownField *)mutableFieldForNumber:(int32_t)number create:(BOOL)create { + ssize_t key = number; + GPBUnknownField *existing = + fields_ ? CFDictionaryGetValue(fields_, (const void *)key) : nil; + if (!existing && create) { + existing = [[GPBUnknownField alloc] initWithNumber:number]; + // This retains existing. + [self addField:existing]; + [existing release]; + } + return existing; +} + +static void GPBUnknownFieldSetMergeUnknownFields(const void *key, + const void *value, + void *context) { +#pragma unused(key) + GPBUnknownField *field = value; + GPBUnknownFieldSet *self = context; + + int32_t number = [field number]; + checkNumber(number); + GPBUnknownField *oldField = [self mutableFieldForNumber:number create:NO]; + if (oldField) { + [oldField mergeFromField:field]; + } else { + // Merge only comes from GPBMessage's mergeFrom:, so it means we are on + // mutable message and are an mutable instance, so make sure we need + // mutable fields. + GPBUnknownField *fieldCopy = [field copy]; + [self addField:fieldCopy]; + [fieldCopy release]; + } +} + +- (void)mergeUnknownFields:(GPBUnknownFieldSet *)other { + if (other && other->fields_) { + CFDictionaryApplyFunction(other->fields_, + GPBUnknownFieldSetMergeUnknownFields, self); + } +} + +- (void)mergeFromData:(NSData *)data { + GPBCodedInputStream *input = [[GPBCodedInputStream alloc] initWithData:data]; + [self mergeFromCodedInputStream:input]; + [input checkLastTagWas:0]; + [input release]; +} + +- (void)mergeVarintField:(int32_t)number value:(int32_t)value { + checkNumber(number); + [[self mutableFieldForNumber:number create:YES] addVarint:value]; +} + +- (BOOL)mergeFieldFrom:(int32_t)tag input:(GPBCodedInputStream *)input { + NSAssert(GPBWireFormatIsValidTag(tag), @"Got passed an invalid tag"); + int32_t number = GPBWireFormatGetTagFieldNumber(tag); + GPBCodedInputStreamState *state = &input->state_; + switch (GPBWireFormatGetTagWireType(tag)) { + case GPBWireFormatVarint: { + GPBUnknownField *field = [self mutableFieldForNumber:number create:YES]; + [field addVarint:GPBCodedInputStreamReadInt64(state)]; + return YES; + } + case GPBWireFormatFixed64: { + GPBUnknownField *field = [self mutableFieldForNumber:number create:YES]; + [field addFixed64:GPBCodedInputStreamReadFixed64(state)]; + return YES; + } + case GPBWireFormatLengthDelimited: { + NSData *data = GPBCodedInputStreamReadRetainedBytes(state); + GPBUnknownField *field = [self mutableFieldForNumber:number create:YES]; + [field addLengthDelimited:data]; + [data release]; + return YES; + } + case GPBWireFormatStartGroup: { + GPBUnknownFieldSet *unknownFieldSet = [[GPBUnknownFieldSet alloc] init]; + [input readUnknownGroup:number message:unknownFieldSet]; + GPBUnknownField *field = [self mutableFieldForNumber:number create:YES]; + [field addGroup:unknownFieldSet]; + [unknownFieldSet release]; + return YES; + } + case GPBWireFormatEndGroup: + return NO; + case GPBWireFormatFixed32: { + GPBUnknownField *field = [self mutableFieldForNumber:number create:YES]; + [field addFixed32:GPBCodedInputStreamReadFixed32(state)]; + return YES; + } + } +} + +- (void)mergeMessageSetMessage:(int32_t)number data:(NSData *)messageData { + [[self mutableFieldForNumber:number create:YES] + addLengthDelimited:messageData]; +} + +- (void)addUnknownMapEntry:(int32_t)fieldNum value:(NSData *)data { + GPBUnknownField *field = [self mutableFieldForNumber:fieldNum create:YES]; + [field addLengthDelimited:data]; +} + +- (void)mergeFromCodedInputStream:(GPBCodedInputStream *)input { + while (YES) { + int32_t tag = GPBCodedInputStreamReadTag(&input->state_); + if (tag == 0 || ![self mergeFieldFrom:tag input:input]) { + break; + } + } +} + +- (void)getTags:(int32_t *)tags { + if (!fields_) return; + size_t count = CFDictionaryGetCount(fields_); + ssize_t keys[count]; + CFDictionaryGetKeysAndValues(fields_, (const void **)keys, NULL); + for (size_t i = 0; i < count; ++i) { + tags[i] = (int32_t)keys[i]; + } +} + +#pragma clang diagnostic pop + +@end diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBUnknownField_PackagePrivate.h b/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBUnknownField_PackagePrivate.h new file mode 100644 index 0000000..2b4c789 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBUnknownField_PackagePrivate.h @@ -0,0 +1,47 @@ +// 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. + +#import + +#import "GPBUnknownField.h" + +@class GPBCodedOutputStream; + +@interface GPBUnknownField () + +- (void)writeToOutput:(GPBCodedOutputStream *)output; +- (size_t)serializedSize; + +- (void)writeAsMessageSetExtensionToOutput:(GPBCodedOutputStream *)output; +- (size_t)serializedSizeAsMessageSetExtension; + +- (void)mergeFromField:(GPBUnknownField *)other; + +@end diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBWrappers.pbobjc.h b/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBWrappers.pbobjc.h new file mode 100644 index 0000000..713bafc --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/GPBWrappers.pbobjc.h @@ -0,0 +1,219 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/wrappers.proto + +// This CPP symbol can be defined to use imports that match up to the framework +// imports needed when using CocoaPods. +#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) + #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 +#endif + +#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS + #import + #import + #import +#else + #import "GPBDescriptor.h" + #import "GPBMessage.h" + #import "GPBRootObject.h" +#endif + +#if GOOGLE_PROTOBUF_OBJC_VERSION < 30004 +#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. +#endif +#if 30004 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION +#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. +#endif + +// @@protoc_insertion_point(imports) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +CF_EXTERN_C_BEGIN + +NS_ASSUME_NONNULL_BEGIN + +#pragma mark - GPBWrappersRoot + +/** + * Exposes the extension registry for this file. + * + * The base class provides: + * @code + * + (GPBExtensionRegistry *)extensionRegistry; + * @endcode + * which is a @c GPBExtensionRegistry that includes all the extensions defined by + * this file and all files that it depends on. + **/ +GPB_FINAL @interface GPBWrappersRoot : GPBRootObject +@end + +#pragma mark - GPBDoubleValue + +typedef GPB_ENUM(GPBDoubleValue_FieldNumber) { + GPBDoubleValue_FieldNumber_Value = 1, +}; + +/** + * Wrapper message for `double`. + * + * The JSON representation for `DoubleValue` is JSON number. + **/ +GPB_FINAL @interface GPBDoubleValue : GPBMessage + +/** The double value. */ +@property(nonatomic, readwrite) double value; + +@end + +#pragma mark - GPBFloatValue + +typedef GPB_ENUM(GPBFloatValue_FieldNumber) { + GPBFloatValue_FieldNumber_Value = 1, +}; + +/** + * Wrapper message for `float`. + * + * The JSON representation for `FloatValue` is JSON number. + **/ +GPB_FINAL @interface GPBFloatValue : GPBMessage + +/** The float value. */ +@property(nonatomic, readwrite) float value; + +@end + +#pragma mark - GPBInt64Value + +typedef GPB_ENUM(GPBInt64Value_FieldNumber) { + GPBInt64Value_FieldNumber_Value = 1, +}; + +/** + * Wrapper message for `int64`. + * + * The JSON representation for `Int64Value` is JSON string. + **/ +GPB_FINAL @interface GPBInt64Value : GPBMessage + +/** The int64 value. */ +@property(nonatomic, readwrite) int64_t value; + +@end + +#pragma mark - GPBUInt64Value + +typedef GPB_ENUM(GPBUInt64Value_FieldNumber) { + GPBUInt64Value_FieldNumber_Value = 1, +}; + +/** + * Wrapper message for `uint64`. + * + * The JSON representation for `UInt64Value` is JSON string. + **/ +GPB_FINAL @interface GPBUInt64Value : GPBMessage + +/** The uint64 value. */ +@property(nonatomic, readwrite) uint64_t value; + +@end + +#pragma mark - GPBInt32Value + +typedef GPB_ENUM(GPBInt32Value_FieldNumber) { + GPBInt32Value_FieldNumber_Value = 1, +}; + +/** + * Wrapper message for `int32`. + * + * The JSON representation for `Int32Value` is JSON number. + **/ +GPB_FINAL @interface GPBInt32Value : GPBMessage + +/** The int32 value. */ +@property(nonatomic, readwrite) int32_t value; + +@end + +#pragma mark - GPBUInt32Value + +typedef GPB_ENUM(GPBUInt32Value_FieldNumber) { + GPBUInt32Value_FieldNumber_Value = 1, +}; + +/** + * Wrapper message for `uint32`. + * + * The JSON representation for `UInt32Value` is JSON number. + **/ +GPB_FINAL @interface GPBUInt32Value : GPBMessage + +/** The uint32 value. */ +@property(nonatomic, readwrite) uint32_t value; + +@end + +#pragma mark - GPBBoolValue + +typedef GPB_ENUM(GPBBoolValue_FieldNumber) { + GPBBoolValue_FieldNumber_Value = 1, +}; + +/** + * Wrapper message for `bool`. + * + * The JSON representation for `BoolValue` is JSON `true` and `false`. + **/ +GPB_FINAL @interface GPBBoolValue : GPBMessage + +/** The bool value. */ +@property(nonatomic, readwrite) BOOL value; + +@end + +#pragma mark - GPBStringValue + +typedef GPB_ENUM(GPBStringValue_FieldNumber) { + GPBStringValue_FieldNumber_Value = 1, +}; + +/** + * Wrapper message for `string`. + * + * The JSON representation for `StringValue` is JSON string. + **/ +GPB_FINAL @interface GPBStringValue : GPBMessage + +/** The string value. */ +@property(nonatomic, readwrite, copy, null_resettable) NSString *value; + +@end + +#pragma mark - GPBBytesValue + +typedef GPB_ENUM(GPBBytesValue_FieldNumber) { + GPBBytesValue_FieldNumber_Value = 1, +}; + +/** + * Wrapper message for `bytes`. + * + * The JSON representation for `BytesValue` is JSON string. + **/ +GPB_FINAL @interface GPBBytesValue : GPBMessage + +/** The bytes value. */ +@property(nonatomic, readwrite, copy, null_resettable) NSData *value; + +@end + +NS_ASSUME_NONNULL_END + +CF_EXTERN_C_END + +#pragma clang diagnostic pop + +// @@protoc_insertion_point(global_scope) diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/ProtocolBuffers_OSX.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/tools/go-generator/cmd/generator/_protobuf/objectivec/ProtocolBuffers_OSX.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/ProtocolBuffers_OSX.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/ProtocolBuffers_iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/tools/go-generator/cmd/generator/_protobuf/objectivec/ProtocolBuffers_iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..037a91d --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/ProtocolBuffers_iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/ProtocolBuffers_tvOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme b/tools/go-generator/cmd/generator/_protobuf/objectivec/ProtocolBuffers_tvOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme new file mode 100644 index 0000000..25d047a --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/ProtocolBuffers_tvOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme @@ -0,0 +1,133 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/CocoaPods/OSXCocoaPodsTester/OSXCocoaPodsTester.xcodeproj/project.pbxproj b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/CocoaPods/OSXCocoaPodsTester/OSXCocoaPodsTester.xcodeproj/project.pbxproj new file mode 100644 index 0000000..b9df381 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/CocoaPods/OSXCocoaPodsTester/OSXCocoaPodsTester.xcodeproj/project.pbxproj @@ -0,0 +1,290 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + F4D5A0AE1CEE2D8F00562D79 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = F4D5A0AD1CEE2D8F00562D79 /* AppDelegate.m */; }; + F4D5A0B11CEE2D8F00562D79 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = F4D5A0B01CEE2D8F00562D79 /* main.m */; }; + F4D5A0B31CEE2D8F00562D79 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = F4D5A0B21CEE2D8F00562D79 /* Assets.xcassets */; }; + F4D5A0B61CEE2D8F00562D79 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = F4D5A0B41CEE2D8F00562D79 /* MainMenu.xib */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + F4D5A0A91CEE2D8F00562D79 /* OSXCocoaPodsTester.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = OSXCocoaPodsTester.app; sourceTree = BUILT_PRODUCTS_DIR; }; + F4D5A0AC1CEE2D8F00562D79 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; + F4D5A0AD1CEE2D8F00562D79 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; + F4D5A0B01CEE2D8F00562D79 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; + F4D5A0B21CEE2D8F00562D79 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + F4D5A0B51CEE2D8F00562D79 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + F4D5A0B71CEE2D8F00562D79 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + F4D5A0A61CEE2D8F00562D79 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + F4D5A0A01CEE2D8F00562D79 = { + isa = PBXGroup; + children = ( + F4D5A0AB1CEE2D8F00562D79 /* OSXCocoaPodsTester */, + F4D5A0AA1CEE2D8F00562D79 /* Products */, + ); + sourceTree = ""; + }; + F4D5A0AA1CEE2D8F00562D79 /* Products */ = { + isa = PBXGroup; + children = ( + F4D5A0A91CEE2D8F00562D79 /* OSXCocoaPodsTester.app */, + ); + name = Products; + sourceTree = ""; + }; + F4D5A0AB1CEE2D8F00562D79 /* OSXCocoaPodsTester */ = { + isa = PBXGroup; + children = ( + F4D5A0AC1CEE2D8F00562D79 /* AppDelegate.h */, + F4D5A0AD1CEE2D8F00562D79 /* AppDelegate.m */, + F4D5A0B21CEE2D8F00562D79 /* Assets.xcassets */, + F4D5A0B41CEE2D8F00562D79 /* MainMenu.xib */, + F4D5A0B71CEE2D8F00562D79 /* Info.plist */, + F4D5A0AF1CEE2D8F00562D79 /* Supporting Files */, + ); + path = OSXCocoaPodsTester; + sourceTree = ""; + }; + F4D5A0AF1CEE2D8F00562D79 /* Supporting Files */ = { + isa = PBXGroup; + children = ( + F4D5A0B01CEE2D8F00562D79 /* main.m */, + ); + name = "Supporting Files"; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + F4D5A0A81CEE2D8F00562D79 /* OSXCocoaPodsTester */ = { + isa = PBXNativeTarget; + buildConfigurationList = F4D5A0BA1CEE2D8F00562D79 /* Build configuration list for PBXNativeTarget "OSXCocoaPodsTester" */; + buildPhases = ( + F4D5A0A51CEE2D8F00562D79 /* Sources */, + F4D5A0A61CEE2D8F00562D79 /* Frameworks */, + F4D5A0A71CEE2D8F00562D79 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = OSXCocoaPodsTester; + productName = OSXCocoaPodsTester; + productReference = F4D5A0A91CEE2D8F00562D79 /* OSXCocoaPodsTester.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + F4D5A0A11CEE2D8F00562D79 /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 0730; + ORGANIZATIONNAME = Google; + TargetAttributes = { + F4D5A0A81CEE2D8F00562D79 = { + CreatedOnToolsVersion = 7.3.1; + }; + }; + }; + buildConfigurationList = F4D5A0A41CEE2D8F00562D79 /* Build configuration list for PBXProject "OSXCocoaPodsTester" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = F4D5A0A01CEE2D8F00562D79; + productRefGroup = F4D5A0AA1CEE2D8F00562D79 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + F4D5A0A81CEE2D8F00562D79 /* OSXCocoaPodsTester */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + F4D5A0A71CEE2D8F00562D79 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + F4D5A0B31CEE2D8F00562D79 /* Assets.xcassets in Resources */, + F4D5A0B61CEE2D8F00562D79 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + F4D5A0A51CEE2D8F00562D79 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + F4D5A0B11CEE2D8F00562D79 /* main.m in Sources */, + F4D5A0AE1CEE2D8F00562D79 /* AppDelegate.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + F4D5A0B41CEE2D8F00562D79 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + F4D5A0B51CEE2D8F00562D79 /* Base */, + ); + name = MainMenu.xib; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + F4D5A0B81CEE2D8F00562D79 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.11; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + }; + name = Debug; + }; + F4D5A0B91CEE2D8F00562D79 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.11; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + }; + name = Release; + }; + F4D5A0BB1CEE2D8F00562D79 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = OSXCocoaPodsTester/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.google.OSXCocoaPodsTester; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + F4D5A0BC1CEE2D8F00562D79 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = OSXCocoaPodsTester/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.google.OSXCocoaPodsTester; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + F4D5A0A41CEE2D8F00562D79 /* Build configuration list for PBXProject "OSXCocoaPodsTester" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F4D5A0B81CEE2D8F00562D79 /* Debug */, + F4D5A0B91CEE2D8F00562D79 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + F4D5A0BA1CEE2D8F00562D79 /* Build configuration list for PBXNativeTarget "OSXCocoaPodsTester" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F4D5A0BB1CEE2D8F00562D79 /* Debug */, + F4D5A0BC1CEE2D8F00562D79 /* Release */, + ); + defaultConfigurationIsVisible = 0; + }; +/* End XCConfigurationList section */ + }; + rootObject = F4D5A0A11CEE2D8F00562D79 /* Project object */; +} diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/CocoaPods/iOSCocoaPodsTester/iOSCocoaPodsTester/Base.lproj/Main.storyboard b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/CocoaPods/iOSCocoaPodsTester/iOSCocoaPodsTester/Base.lproj/Main.storyboard new file mode 100644 index 0000000..82cd159 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/CocoaPods/iOSCocoaPodsTester/iOSCocoaPodsTester/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/CocoaPods/iOSCocoaPodsTester/iOSCocoaPodsTester/main.m b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/CocoaPods/iOSCocoaPodsTester/iOSCocoaPodsTester/main.m new file mode 100644 index 0000000..4df0b76 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/CocoaPods/iOSCocoaPodsTester/iOSCocoaPodsTester/main.m @@ -0,0 +1,39 @@ +// +// Protocol Buffers - Google's data interchange format +// Copyright 2016 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. + +#import +#import "AppDelegate.h" + +int main(int argc, char * argv[]) { + @autoreleasepool { + return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/GPBArrayTests.m b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/GPBArrayTests.m new file mode 100644 index 0000000..9b004bc --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/GPBArrayTests.m @@ -0,0 +1,3731 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. + +#import +#import + +#import "GPBArray.h" +#import "GPBArray_PackagePrivate.h" + +#import "GPBTestUtilities.h" + +// To let the testing macros work, add some extra methods to simplify things. +@interface GPBEnumArray (TestingTweak) ++ (instancetype)arrayWithValue:(int32_t)value; ++ (instancetype)arrayWithCapacity:(NSUInteger)count; +- (instancetype)initWithValues:(const int32_t [])values + count:(NSUInteger)count; +@end + +static BOOL TestingEnum_IsValidValue(int32_t value) { + switch (value) { + case 71: + case 72: + case 73: + case 74: + return YES; + default: + return NO; + } +} + +static BOOL TestingEnum_IsValidValue2(int32_t value) { + switch (value) { + case 71: + case 72: + case 73: + return YES; + default: + return NO; + } +} + +@implementation GPBEnumArray (TestingTweak) ++ (instancetype)arrayWithValue:(int32_t)value { + return [[[self alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:&value + count:1] autorelease]; +} ++ (instancetype)arrayWithCapacity:(NSUInteger)count { + return [[[self alloc] initWithValidationFunction:TestingEnum_IsValidValue + capacity:count] autorelease]; +} +- (instancetype)initWithValues:(const int32_t [])values + count:(NSUInteger)count { + return [self initWithValidationFunction:TestingEnum_IsValidValue + rawValues:values + count:count]; +} +@end + +#pragma mark - PDDM Macros + +//%PDDM-DEFINE ARRAY_TESTS(NAME, TYPE, VAL1, VAL2, VAL3, VAL4) +//%ARRAY_TESTS2(NAME, TYPE, VAL1, VAL2, VAL3, VAL4, ) +//%PDDM-DEFINE ARRAY_TESTS2(NAME, TYPE, VAL1, VAL2, VAL3, VAL4, HELPER) +//%#pragma mark - NAME +//% +//%@interface GPB##NAME##ArrayTests : XCTestCase +//%@end +//% +//%@implementation GPB##NAME##ArrayTests +//% +//%- (void)testEmpty { +//% GPB##NAME##Array *array = [[GPB##NAME##Array alloc] init]; +//% XCTAssertNotNil(array); +//% XCTAssertEqual(array.count, 0U); +//% XCTAssertThrowsSpecificNamed([array valueAtIndex:0], NSException, NSRangeException); +//% [array enumerateValuesWithBlock:^(TYPE value, NSUInteger idx, BOOL *stop) { +//% #pragma unused(value, idx, stop) +//% XCTFail(@"Shouldn't get here!"); +//% }]; +//% [array enumerateValuesWithOptions:NSEnumerationReverse +//% usingBlock:^(TYPE value, NSUInteger idx, BOOL *stop) { +//% #pragma unused(value, idx, stop) +//% XCTFail(@"Shouldn't get here!"); +//% }]; +//% [array release]; +//%} +//% +//%- (void)testOne { +//% GPB##NAME##Array *array = [GPB##NAME##Array arrayWithValue:VAL1]; +//% XCTAssertNotNil(array); +//% XCTAssertEqual(array.count, 1U); +//% XCTAssertEqual([array valueAtIndex:0], VAL1); +//% XCTAssertThrowsSpecificNamed([array valueAtIndex:1], NSException, NSRangeException); +//% [array enumerateValuesWithBlock:^(TYPE value, NSUInteger idx, BOOL *stop) { +//% XCTAssertEqual(idx, 0U); +//% XCTAssertEqual(value, VAL1); +//% XCTAssertNotEqual(stop, NULL); +//% }]; +//% [array enumerateValuesWithOptions:NSEnumerationReverse +//% usingBlock:^(TYPE value, NSUInteger idx, BOOL *stop) { +//% XCTAssertEqual(idx, 0U); +//% XCTAssertEqual(value, VAL1); +//% XCTAssertNotEqual(stop, NULL); +//% }]; +//%} +//% +//%- (void)testBasics { +//% static const TYPE kValues[] = { VAL1, VAL2, VAL3, VAL4 }; +//% GPB##NAME##Array *array = +//% [[GPB##NAME##Array alloc] initWithValues:kValues +//% NAME$S count:GPBARRAYSIZE(kValues)]; +//% XCTAssertNotNil(array); +//% XCTAssertEqual(array.count, 4U); +//% XCTAssertEqual([array valueAtIndex:0], VAL1); +//% XCTAssertEqual([array valueAtIndex:1], VAL2); +//% XCTAssertEqual([array valueAtIndex:2], VAL3); +//% XCTAssertEqual([array valueAtIndex:3], VAL4); +//% XCTAssertThrowsSpecificNamed([array valueAtIndex:4], NSException, NSRangeException); +//% __block NSUInteger idx2 = 0; +//% [array enumerateValuesWithBlock:^(TYPE value, NSUInteger idx, BOOL *stop) { +//% XCTAssertEqual(idx, idx2); +//% XCTAssertEqual(value, kValues[idx]); +//% XCTAssertNotEqual(stop, NULL); +//% ++idx2; +//% }]; +//% idx2 = 0; +//% [array enumerateValuesWithOptions:NSEnumerationReverse +//% usingBlock:^(TYPE value, NSUInteger idx, BOOL *stop) { +//% XCTAssertEqual(idx, (3 - idx2)); +//% XCTAssertEqual(value, kValues[idx]); +//% XCTAssertNotEqual(stop, NULL); +//% ++idx2; +//% }]; +//% // Stopping the enumeration. +//% idx2 = 0; +//% [array enumerateValuesWithBlock:^(TYPE value, NSUInteger idx, BOOL *stop) { +//% XCTAssertEqual(idx, idx2); +//% XCTAssertEqual(value, kValues[idx]); +//% XCTAssertNotEqual(stop, NULL); +//% if (idx2 == 1) *stop = YES; +//% XCTAssertNotEqual(idx, 2U); +//% XCTAssertNotEqual(idx, 3U); +//% ++idx2; +//% }]; +//% idx2 = 0; +//% [array enumerateValuesWithOptions:NSEnumerationReverse +//% usingBlock:^(TYPE value, NSUInteger idx, BOOL *stop) { +//% XCTAssertEqual(idx, (3 - idx2)); +//% XCTAssertEqual(value, kValues[idx]); +//% XCTAssertNotEqual(stop, NULL); +//% if (idx2 == 1) *stop = YES; +//% XCTAssertNotEqual(idx, 1U); +//% XCTAssertNotEqual(idx, 0U); +//% ++idx2; +//% }]; +//% // Ensure description doesn't choke. +//% XCTAssertTrue(array.description.length > 10); +//% [array release]; +//%} +//% +//%- (void)testEquality { +//% const TYPE kValues1[] = { VAL1, VAL2, VAL3 }; +//% const TYPE kValues2[] = { VAL1, VAL4, VAL3 }; +//% const TYPE kValues3[] = { VAL1, VAL2, VAL3, VAL4 }; +//% GPB##NAME##Array *array1 = +//% [[GPB##NAME##Array alloc] initWithValues:kValues1 +//% NAME$S count:GPBARRAYSIZE(kValues1)]; +//% XCTAssertNotNil(array1); +//% GPB##NAME##Array *array1prime = +//% [[GPB##NAME##Array alloc] initWithValues:kValues1 +//% NAME$S count:GPBARRAYSIZE(kValues1)]; +//% XCTAssertNotNil(array1prime); +//% GPB##NAME##Array *array2 = +//% [[GPB##NAME##Array alloc] initWithValues:kValues2 +//% NAME$S count:GPBARRAYSIZE(kValues2)]; +//% XCTAssertNotNil(array2); +//% GPB##NAME##Array *array3 = +//% [[GPB##NAME##Array alloc] initWithValues:kValues3 +//% NAME$S count:GPBARRAYSIZE(kValues3)]; +//% XCTAssertNotNil(array3); +//% +//% // Identity +//% XCTAssertTrue([array1 isEqual:array1]); +//% // Wrong type doesn't blow up. +//% XCTAssertFalse([array1 isEqual:@"bogus"]); +//% // 1/1Prime should be different objects, but equal. +//% XCTAssertNotEqual(array1, array1prime); +//% XCTAssertEqualObjects(array1, array1prime); +//% // Equal, so they must have same hash. +//% XCTAssertEqual([array1 hash], [array1prime hash]); +//% +//% // 1/2/3 shouldn't be equal. +//% XCTAssertNotEqualObjects(array1, array2); +//% XCTAssertNotEqualObjects(array1, array3); +//% XCTAssertNotEqualObjects(array2, array3); +//% +//% [array1 release]; +//% [array1prime release]; +//% [array2 release]; +//% [array3 release]; +//%} +//% +//%- (void)testCopy { +//% const TYPE kValues[] = { VAL1, VAL2, VAL3, VAL4 }; +//% GPB##NAME##Array *array = +//% [[GPB##NAME##Array alloc] initWithValues:kValues +//% NAME$S count:GPBARRAYSIZE(kValues)]; +//% XCTAssertNotNil(array); +//% +//% GPB##NAME##Array *array2 = [array copy]; +//% XCTAssertNotNil(array2); +//% +//% // Should be new object but equal. +//% XCTAssertNotEqual(array, array2); +//% XCTAssertEqualObjects(array, array2); +//% [array2 release]; +//% [array release]; +//%} +//% +//%- (void)testArrayFromArray { +//% const TYPE kValues[] = { VAL1, VAL2, VAL3, VAL4 }; +//% GPB##NAME##Array *array = +//% [[GPB##NAME##Array alloc] initWithValues:kValues +//% NAME$S count:GPBARRAYSIZE(kValues)]; +//% XCTAssertNotNil(array); +//% +//% GPB##NAME##Array *array2 = [GPB##NAME##Array arrayWithValueArray:array]; +//% XCTAssertNotNil(array2); +//% +//% // Should be new pointer, but equal objects. +//% XCTAssertNotEqual(array, array2); +//% XCTAssertEqualObjects(array, array2); +//% [array release]; +//%} +//% +//%- (void)testAdds { +//% GPB##NAME##Array *array = [GPB##NAME##Array array]; +//% XCTAssertNotNil(array); +//% +//% XCTAssertEqual(array.count, 0U); +//% [array addValue:VAL1]; +//% XCTAssertEqual(array.count, 1U); +//% +//% const TYPE kValues1[] = { VAL2, VAL3 }; +//% [array addValues:kValues1 count:GPBARRAYSIZE(kValues1)]; +//% XCTAssertEqual(array.count, 3U); +//% +//% const TYPE kValues2[] = { VAL4, VAL1 }; +//% GPB##NAME##Array *array2 = +//% [[GPB##NAME##Array alloc] initWithValues:kValues2 +//% NAME$S count:GPBARRAYSIZE(kValues2)]; +//% XCTAssertNotNil(array2); +//% [array add##HELPER##ValuesFromArray:array2]; +//% XCTAssertEqual(array.count, 5U); +//% +//% // Zero/nil inputs do nothing. +//% [array addValues:kValues1 count:0]; +//% XCTAssertEqual(array.count, 5U); +//% [array addValues:NULL count:5]; +//% XCTAssertEqual(array.count, 5U); +//% +//% XCTAssertEqual([array valueAtIndex:0], VAL1); +//% XCTAssertEqual([array valueAtIndex:1], VAL2); +//% XCTAssertEqual([array valueAtIndex:2], VAL3); +//% XCTAssertEqual([array valueAtIndex:3], VAL4); +//% XCTAssertEqual([array valueAtIndex:4], VAL1); +//% [array2 release]; +//%} +//% +//%- (void)testInsert { +//% const TYPE kValues[] = { VAL1, VAL2, VAL3 }; +//% GPB##NAME##Array *array = +//% [[GPB##NAME##Array alloc] initWithValues:kValues +//% NAME$S count:GPBARRAYSIZE(kValues)]; +//% XCTAssertNotNil(array); +//% XCTAssertEqual(array.count, 3U); +//% +//% // First +//% [array insertValue:VAL4 atIndex:0]; +//% XCTAssertEqual(array.count, 4U); +//% +//% // Middle +//% [array insertValue:VAL4 atIndex:2]; +//% XCTAssertEqual(array.count, 5U); +//% +//% // End +//% [array insertValue:VAL4 atIndex:5]; +//% XCTAssertEqual(array.count, 6U); +//% +//% // Too far. +//% XCTAssertThrowsSpecificNamed([array insertValue:VAL4 atIndex:7], +//% NSException, NSRangeException); +//% +//% XCTAssertEqual([array valueAtIndex:0], VAL4); +//% XCTAssertEqual([array valueAtIndex:1], VAL1); +//% XCTAssertEqual([array valueAtIndex:2], VAL4); +//% XCTAssertEqual([array valueAtIndex:3], VAL2); +//% XCTAssertEqual([array valueAtIndex:4], VAL3); +//% XCTAssertEqual([array valueAtIndex:5], VAL4); +//% [array release]; +//%} +//% +//%- (void)testRemove { +//% const TYPE kValues[] = { VAL4, VAL1, VAL2, VAL4, VAL3, VAL4 }; +//% GPB##NAME##Array *array = +//% [[GPB##NAME##Array alloc] initWithValues:kValues +//% NAME$S count:GPBARRAYSIZE(kValues)]; +//% XCTAssertNotNil(array); +//% XCTAssertEqual(array.count, 6U); +//% +//% // First +//% [array removeValueAtIndex:0]; +//% XCTAssertEqual(array.count, 5U); +//% XCTAssertEqual([array valueAtIndex:0], VAL1); +//% +//% // Middle +//% [array removeValueAtIndex:2]; +//% XCTAssertEqual(array.count, 4U); +//% XCTAssertEqual([array valueAtIndex:2], VAL3); +//% +//% // End +//% [array removeValueAtIndex:3]; +//% XCTAssertEqual(array.count, 3U); +//% +//% XCTAssertEqual([array valueAtIndex:0], VAL1); +//% XCTAssertEqual([array valueAtIndex:1], VAL2); +//% XCTAssertEqual([array valueAtIndex:2], VAL3); +//% +//% // Too far. +//% XCTAssertThrowsSpecificNamed([array removeValueAtIndex:3], +//% NSException, NSRangeException); +//% +//% [array removeAll]; +//% XCTAssertEqual(array.count, 0U); +//% XCTAssertThrowsSpecificNamed([array removeValueAtIndex:0], +//% NSException, NSRangeException); +//% [array release]; +//%} +//% +//%- (void)testInplaceMutation { +//% const TYPE kValues[] = { VAL1, VAL1, VAL3, VAL3 }; +//% GPB##NAME##Array *array = +//% [[GPB##NAME##Array alloc] initWithValues:kValues +//% NAME$S count:GPBARRAYSIZE(kValues)]; +//% XCTAssertNotNil(array); +//% +//% [array replaceValueAtIndex:1 withValue:VAL2]; +//% [array replaceValueAtIndex:3 withValue:VAL4]; +//% XCTAssertEqual(array.count, 4U); +//% XCTAssertEqual([array valueAtIndex:0], VAL1); +//% XCTAssertEqual([array valueAtIndex:1], VAL2); +//% XCTAssertEqual([array valueAtIndex:2], VAL3); +//% XCTAssertEqual([array valueAtIndex:3], VAL4); +//% +//% XCTAssertThrowsSpecificNamed([array replaceValueAtIndex:4 withValue:VAL4], +//% NSException, NSRangeException); +//% +//% [array exchangeValueAtIndex:1 withValueAtIndex:3]; +//% XCTAssertEqual(array.count, 4U); +//% XCTAssertEqual([array valueAtIndex:0], VAL1); +//% XCTAssertEqual([array valueAtIndex:1], VAL4); +//% XCTAssertEqual([array valueAtIndex:2], VAL3); +//% XCTAssertEqual([array valueAtIndex:3], VAL2); +//% +//% [array exchangeValueAtIndex:2 withValueAtIndex:0]; +//% XCTAssertEqual(array.count, 4U); +//% XCTAssertEqual([array valueAtIndex:0], VAL3); +//% XCTAssertEqual([array valueAtIndex:1], VAL4); +//% XCTAssertEqual([array valueAtIndex:2], VAL1); +//% XCTAssertEqual([array valueAtIndex:3], VAL2); +//% +//% XCTAssertThrowsSpecificNamed([array exchangeValueAtIndex:4 withValueAtIndex:1], +//% NSException, NSRangeException); +//% XCTAssertThrowsSpecificNamed([array exchangeValueAtIndex:1 withValueAtIndex:4], +//% NSException, NSRangeException); +//% [array release]; +//%} +//% +//%- (void)testInternalResizing { +//% const TYPE kValues[] = { VAL1, VAL2, VAL3, VAL4 }; +//% GPB##NAME##Array *array = +//% [GPB##NAME##Array arrayWithCapacity:GPBARRAYSIZE(kValues)]; +//% XCTAssertNotNil(array); +//% [array addValues:kValues count:GPBARRAYSIZE(kValues)]; +//% +//% // Add/remove to trigger the intneral buffer to grow/shrink. +//% for (int i = 0; i < 100; ++i) { +//% [array addValues:kValues count:GPBARRAYSIZE(kValues)]; +//% } +//% XCTAssertEqual(array.count, 404U); +//% for (int i = 0; i < 100; ++i) { +//% [array removeValueAtIndex:(i * 2)]; +//% } +//% XCTAssertEqual(array.count, 304U); +//% for (int i = 0; i < 100; ++i) { +//% [array insertValue:VAL4 atIndex:(i * 3)]; +//% } +//% XCTAssertEqual(array.count, 404U); +//% [array removeAll]; +//% XCTAssertEqual(array.count, 0U); +//%} +//% +//%@end +//% +//%PDDM-EXPAND ARRAY_TESTS(Int32, int32_t, 1, 2, 3, 4) +// This block of code is generated, do not edit it directly. +// clang-format off + +#pragma mark - Int32 + +@interface GPBInt32ArrayTests : XCTestCase +@end + +@implementation GPBInt32ArrayTests + +- (void)testEmpty { + GPBInt32Array *array = [[GPBInt32Array alloc] init]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 0U); + XCTAssertThrowsSpecificNamed([array valueAtIndex:0], NSException, NSRangeException); + [array enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { + #pragma unused(value, idx, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { + #pragma unused(value, idx, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [array release]; +} + +- (void)testOne { + GPBInt32Array *array = [GPBInt32Array arrayWithValue:1]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 1U); + XCTAssertEqual([array valueAtIndex:0], 1); + XCTAssertThrowsSpecificNamed([array valueAtIndex:1], NSException, NSRangeException); + [array enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, 0U); + XCTAssertEqual(value, 1); + XCTAssertNotEqual(stop, NULL); + }]; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, 0U); + XCTAssertEqual(value, 1); + XCTAssertNotEqual(stop, NULL); + }]; +} + +- (void)testBasics { + static const int32_t kValues[] = { 1, 2, 3, 4 }; + GPBInt32Array *array = + [[GPBInt32Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 1); + XCTAssertEqual([array valueAtIndex:1], 2); + XCTAssertEqual([array valueAtIndex:2], 3); + XCTAssertEqual([array valueAtIndex:3], 4); + XCTAssertThrowsSpecificNamed([array valueAtIndex:4], NSException, NSRangeException); + __block NSUInteger idx2 = 0; + [array enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, idx2); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + ++idx2; + }]; + idx2 = 0; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, (3 - idx2)); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + ++idx2; + }]; + // Stopping the enumeration. + idx2 = 0; + [array enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, idx2); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + if (idx2 == 1) *stop = YES; + XCTAssertNotEqual(idx, 2U); + XCTAssertNotEqual(idx, 3U); + ++idx2; + }]; + idx2 = 0; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, (3 - idx2)); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + if (idx2 == 1) *stop = YES; + XCTAssertNotEqual(idx, 1U); + XCTAssertNotEqual(idx, 0U); + ++idx2; + }]; + // Ensure description doesn't choke. + XCTAssertTrue(array.description.length > 10); + [array release]; +} + +- (void)testEquality { + const int32_t kValues1[] = { 1, 2, 3 }; + const int32_t kValues2[] = { 1, 4, 3 }; + const int32_t kValues3[] = { 1, 2, 3, 4 }; + GPBInt32Array *array1 = + [[GPBInt32Array alloc] initWithValues:kValues1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(array1); + GPBInt32Array *array1prime = + [[GPBInt32Array alloc] initWithValues:kValues1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(array1prime); + GPBInt32Array *array2 = + [[GPBInt32Array alloc] initWithValues:kValues2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(array2); + GPBInt32Array *array3 = + [[GPBInt32Array alloc] initWithValues:kValues3 + count:GPBARRAYSIZE(kValues3)]; + XCTAssertNotNil(array3); + + // Identity + XCTAssertTrue([array1 isEqual:array1]); + // Wrong type doesn't blow up. + XCTAssertFalse([array1 isEqual:@"bogus"]); + // 1/1Prime should be different objects, but equal. + XCTAssertNotEqual(array1, array1prime); + XCTAssertEqualObjects(array1, array1prime); + // Equal, so they must have same hash. + XCTAssertEqual([array1 hash], [array1prime hash]); + + // 1/2/3 shouldn't be equal. + XCTAssertNotEqualObjects(array1, array2); + XCTAssertNotEqualObjects(array1, array3); + XCTAssertNotEqualObjects(array2, array3); + + [array1 release]; + [array1prime release]; + [array2 release]; + [array3 release]; +} + +- (void)testCopy { + const int32_t kValues[] = { 1, 2, 3, 4 }; + GPBInt32Array *array = + [[GPBInt32Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + GPBInt32Array *array2 = [array copy]; + XCTAssertNotNil(array2); + + // Should be new object but equal. + XCTAssertNotEqual(array, array2); + XCTAssertEqualObjects(array, array2); + [array2 release]; + [array release]; +} + +- (void)testArrayFromArray { + const int32_t kValues[] = { 1, 2, 3, 4 }; + GPBInt32Array *array = + [[GPBInt32Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + GPBInt32Array *array2 = [GPBInt32Array arrayWithValueArray:array]; + XCTAssertNotNil(array2); + + // Should be new pointer, but equal objects. + XCTAssertNotEqual(array, array2); + XCTAssertEqualObjects(array, array2); + [array release]; +} + +- (void)testAdds { + GPBInt32Array *array = [GPBInt32Array array]; + XCTAssertNotNil(array); + + XCTAssertEqual(array.count, 0U); + [array addValue:1]; + XCTAssertEqual(array.count, 1U); + + const int32_t kValues1[] = { 2, 3 }; + [array addValues:kValues1 count:GPBARRAYSIZE(kValues1)]; + XCTAssertEqual(array.count, 3U); + + const int32_t kValues2[] = { 4, 1 }; + GPBInt32Array *array2 = + [[GPBInt32Array alloc] initWithValues:kValues2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(array2); + [array addValuesFromArray:array2]; + XCTAssertEqual(array.count, 5U); + + // Zero/nil inputs do nothing. + [array addValues:kValues1 count:0]; + XCTAssertEqual(array.count, 5U); + [array addValues:NULL count:5]; + XCTAssertEqual(array.count, 5U); + + XCTAssertEqual([array valueAtIndex:0], 1); + XCTAssertEqual([array valueAtIndex:1], 2); + XCTAssertEqual([array valueAtIndex:2], 3); + XCTAssertEqual([array valueAtIndex:3], 4); + XCTAssertEqual([array valueAtIndex:4], 1); + [array2 release]; +} + +- (void)testInsert { + const int32_t kValues[] = { 1, 2, 3 }; + GPBInt32Array *array = + [[GPBInt32Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 3U); + + // First + [array insertValue:4 atIndex:0]; + XCTAssertEqual(array.count, 4U); + + // Middle + [array insertValue:4 atIndex:2]; + XCTAssertEqual(array.count, 5U); + + // End + [array insertValue:4 atIndex:5]; + XCTAssertEqual(array.count, 6U); + + // Too far. + XCTAssertThrowsSpecificNamed([array insertValue:4 atIndex:7], + NSException, NSRangeException); + + XCTAssertEqual([array valueAtIndex:0], 4); + XCTAssertEqual([array valueAtIndex:1], 1); + XCTAssertEqual([array valueAtIndex:2], 4); + XCTAssertEqual([array valueAtIndex:3], 2); + XCTAssertEqual([array valueAtIndex:4], 3); + XCTAssertEqual([array valueAtIndex:5], 4); + [array release]; +} + +- (void)testRemove { + const int32_t kValues[] = { 4, 1, 2, 4, 3, 4 }; + GPBInt32Array *array = + [[GPBInt32Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 6U); + + // First + [array removeValueAtIndex:0]; + XCTAssertEqual(array.count, 5U); + XCTAssertEqual([array valueAtIndex:0], 1); + + // Middle + [array removeValueAtIndex:2]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:2], 3); + + // End + [array removeValueAtIndex:3]; + XCTAssertEqual(array.count, 3U); + + XCTAssertEqual([array valueAtIndex:0], 1); + XCTAssertEqual([array valueAtIndex:1], 2); + XCTAssertEqual([array valueAtIndex:2], 3); + + // Too far. + XCTAssertThrowsSpecificNamed([array removeValueAtIndex:3], + NSException, NSRangeException); + + [array removeAll]; + XCTAssertEqual(array.count, 0U); + XCTAssertThrowsSpecificNamed([array removeValueAtIndex:0], + NSException, NSRangeException); + [array release]; +} + +- (void)testInplaceMutation { + const int32_t kValues[] = { 1, 1, 3, 3 }; + GPBInt32Array *array = + [[GPBInt32Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + [array replaceValueAtIndex:1 withValue:2]; + [array replaceValueAtIndex:3 withValue:4]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 1); + XCTAssertEqual([array valueAtIndex:1], 2); + XCTAssertEqual([array valueAtIndex:2], 3); + XCTAssertEqual([array valueAtIndex:3], 4); + + XCTAssertThrowsSpecificNamed([array replaceValueAtIndex:4 withValue:4], + NSException, NSRangeException); + + [array exchangeValueAtIndex:1 withValueAtIndex:3]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 1); + XCTAssertEqual([array valueAtIndex:1], 4); + XCTAssertEqual([array valueAtIndex:2], 3); + XCTAssertEqual([array valueAtIndex:3], 2); + + [array exchangeValueAtIndex:2 withValueAtIndex:0]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 3); + XCTAssertEqual([array valueAtIndex:1], 4); + XCTAssertEqual([array valueAtIndex:2], 1); + XCTAssertEqual([array valueAtIndex:3], 2); + + XCTAssertThrowsSpecificNamed([array exchangeValueAtIndex:4 withValueAtIndex:1], + NSException, NSRangeException); + XCTAssertThrowsSpecificNamed([array exchangeValueAtIndex:1 withValueAtIndex:4], + NSException, NSRangeException); + [array release]; +} + +- (void)testInternalResizing { + const int32_t kValues[] = { 1, 2, 3, 4 }; + GPBInt32Array *array = + [GPBInt32Array arrayWithCapacity:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + [array addValues:kValues count:GPBARRAYSIZE(kValues)]; + + // Add/remove to trigger the intneral buffer to grow/shrink. + for (int i = 0; i < 100; ++i) { + [array addValues:kValues count:GPBARRAYSIZE(kValues)]; + } + XCTAssertEqual(array.count, 404U); + for (int i = 0; i < 100; ++i) { + [array removeValueAtIndex:(i * 2)]; + } + XCTAssertEqual(array.count, 304U); + for (int i = 0; i < 100; ++i) { + [array insertValue:4 atIndex:(i * 3)]; + } + XCTAssertEqual(array.count, 404U); + [array removeAll]; + XCTAssertEqual(array.count, 0U); +} + +@end + +// clang-format on +//%PDDM-EXPAND ARRAY_TESTS(UInt32, uint32_t, 11U, 12U, 13U, 14U) +// This block of code is generated, do not edit it directly. +// clang-format off + +#pragma mark - UInt32 + +@interface GPBUInt32ArrayTests : XCTestCase +@end + +@implementation GPBUInt32ArrayTests + +- (void)testEmpty { + GPBUInt32Array *array = [[GPBUInt32Array alloc] init]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 0U); + XCTAssertThrowsSpecificNamed([array valueAtIndex:0], NSException, NSRangeException); + [array enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { + #pragma unused(value, idx, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { + #pragma unused(value, idx, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [array release]; +} + +- (void)testOne { + GPBUInt32Array *array = [GPBUInt32Array arrayWithValue:11U]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 1U); + XCTAssertEqual([array valueAtIndex:0], 11U); + XCTAssertThrowsSpecificNamed([array valueAtIndex:1], NSException, NSRangeException); + [array enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, 0U); + XCTAssertEqual(value, 11U); + XCTAssertNotEqual(stop, NULL); + }]; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, 0U); + XCTAssertEqual(value, 11U); + XCTAssertNotEqual(stop, NULL); + }]; +} + +- (void)testBasics { + static const uint32_t kValues[] = { 11U, 12U, 13U, 14U }; + GPBUInt32Array *array = + [[GPBUInt32Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 11U); + XCTAssertEqual([array valueAtIndex:1], 12U); + XCTAssertEqual([array valueAtIndex:2], 13U); + XCTAssertEqual([array valueAtIndex:3], 14U); + XCTAssertThrowsSpecificNamed([array valueAtIndex:4], NSException, NSRangeException); + __block NSUInteger idx2 = 0; + [array enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, idx2); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + ++idx2; + }]; + idx2 = 0; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, (3 - idx2)); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + ++idx2; + }]; + // Stopping the enumeration. + idx2 = 0; + [array enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, idx2); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + if (idx2 == 1) *stop = YES; + XCTAssertNotEqual(idx, 2U); + XCTAssertNotEqual(idx, 3U); + ++idx2; + }]; + idx2 = 0; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, (3 - idx2)); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + if (idx2 == 1) *stop = YES; + XCTAssertNotEqual(idx, 1U); + XCTAssertNotEqual(idx, 0U); + ++idx2; + }]; + // Ensure description doesn't choke. + XCTAssertTrue(array.description.length > 10); + [array release]; +} + +- (void)testEquality { + const uint32_t kValues1[] = { 11U, 12U, 13U }; + const uint32_t kValues2[] = { 11U, 14U, 13U }; + const uint32_t kValues3[] = { 11U, 12U, 13U, 14U }; + GPBUInt32Array *array1 = + [[GPBUInt32Array alloc] initWithValues:kValues1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(array1); + GPBUInt32Array *array1prime = + [[GPBUInt32Array alloc] initWithValues:kValues1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(array1prime); + GPBUInt32Array *array2 = + [[GPBUInt32Array alloc] initWithValues:kValues2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(array2); + GPBUInt32Array *array3 = + [[GPBUInt32Array alloc] initWithValues:kValues3 + count:GPBARRAYSIZE(kValues3)]; + XCTAssertNotNil(array3); + + // Identity + XCTAssertTrue([array1 isEqual:array1]); + // Wrong type doesn't blow up. + XCTAssertFalse([array1 isEqual:@"bogus"]); + // 1/1Prime should be different objects, but equal. + XCTAssertNotEqual(array1, array1prime); + XCTAssertEqualObjects(array1, array1prime); + // Equal, so they must have same hash. + XCTAssertEqual([array1 hash], [array1prime hash]); + + // 1/2/3 shouldn't be equal. + XCTAssertNotEqualObjects(array1, array2); + XCTAssertNotEqualObjects(array1, array3); + XCTAssertNotEqualObjects(array2, array3); + + [array1 release]; + [array1prime release]; + [array2 release]; + [array3 release]; +} + +- (void)testCopy { + const uint32_t kValues[] = { 11U, 12U, 13U, 14U }; + GPBUInt32Array *array = + [[GPBUInt32Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + GPBUInt32Array *array2 = [array copy]; + XCTAssertNotNil(array2); + + // Should be new object but equal. + XCTAssertNotEqual(array, array2); + XCTAssertEqualObjects(array, array2); + [array2 release]; + [array release]; +} + +- (void)testArrayFromArray { + const uint32_t kValues[] = { 11U, 12U, 13U, 14U }; + GPBUInt32Array *array = + [[GPBUInt32Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + GPBUInt32Array *array2 = [GPBUInt32Array arrayWithValueArray:array]; + XCTAssertNotNil(array2); + + // Should be new pointer, but equal objects. + XCTAssertNotEqual(array, array2); + XCTAssertEqualObjects(array, array2); + [array release]; +} + +- (void)testAdds { + GPBUInt32Array *array = [GPBUInt32Array array]; + XCTAssertNotNil(array); + + XCTAssertEqual(array.count, 0U); + [array addValue:11U]; + XCTAssertEqual(array.count, 1U); + + const uint32_t kValues1[] = { 12U, 13U }; + [array addValues:kValues1 count:GPBARRAYSIZE(kValues1)]; + XCTAssertEqual(array.count, 3U); + + const uint32_t kValues2[] = { 14U, 11U }; + GPBUInt32Array *array2 = + [[GPBUInt32Array alloc] initWithValues:kValues2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(array2); + [array addValuesFromArray:array2]; + XCTAssertEqual(array.count, 5U); + + // Zero/nil inputs do nothing. + [array addValues:kValues1 count:0]; + XCTAssertEqual(array.count, 5U); + [array addValues:NULL count:5]; + XCTAssertEqual(array.count, 5U); + + XCTAssertEqual([array valueAtIndex:0], 11U); + XCTAssertEqual([array valueAtIndex:1], 12U); + XCTAssertEqual([array valueAtIndex:2], 13U); + XCTAssertEqual([array valueAtIndex:3], 14U); + XCTAssertEqual([array valueAtIndex:4], 11U); + [array2 release]; +} + +- (void)testInsert { + const uint32_t kValues[] = { 11U, 12U, 13U }; + GPBUInt32Array *array = + [[GPBUInt32Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 3U); + + // First + [array insertValue:14U atIndex:0]; + XCTAssertEqual(array.count, 4U); + + // Middle + [array insertValue:14U atIndex:2]; + XCTAssertEqual(array.count, 5U); + + // End + [array insertValue:14U atIndex:5]; + XCTAssertEqual(array.count, 6U); + + // Too far. + XCTAssertThrowsSpecificNamed([array insertValue:14U atIndex:7], + NSException, NSRangeException); + + XCTAssertEqual([array valueAtIndex:0], 14U); + XCTAssertEqual([array valueAtIndex:1], 11U); + XCTAssertEqual([array valueAtIndex:2], 14U); + XCTAssertEqual([array valueAtIndex:3], 12U); + XCTAssertEqual([array valueAtIndex:4], 13U); + XCTAssertEqual([array valueAtIndex:5], 14U); + [array release]; +} + +- (void)testRemove { + const uint32_t kValues[] = { 14U, 11U, 12U, 14U, 13U, 14U }; + GPBUInt32Array *array = + [[GPBUInt32Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 6U); + + // First + [array removeValueAtIndex:0]; + XCTAssertEqual(array.count, 5U); + XCTAssertEqual([array valueAtIndex:0], 11U); + + // Middle + [array removeValueAtIndex:2]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:2], 13U); + + // End + [array removeValueAtIndex:3]; + XCTAssertEqual(array.count, 3U); + + XCTAssertEqual([array valueAtIndex:0], 11U); + XCTAssertEqual([array valueAtIndex:1], 12U); + XCTAssertEqual([array valueAtIndex:2], 13U); + + // Too far. + XCTAssertThrowsSpecificNamed([array removeValueAtIndex:3], + NSException, NSRangeException); + + [array removeAll]; + XCTAssertEqual(array.count, 0U); + XCTAssertThrowsSpecificNamed([array removeValueAtIndex:0], + NSException, NSRangeException); + [array release]; +} + +- (void)testInplaceMutation { + const uint32_t kValues[] = { 11U, 11U, 13U, 13U }; + GPBUInt32Array *array = + [[GPBUInt32Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + [array replaceValueAtIndex:1 withValue:12U]; + [array replaceValueAtIndex:3 withValue:14U]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 11U); + XCTAssertEqual([array valueAtIndex:1], 12U); + XCTAssertEqual([array valueAtIndex:2], 13U); + XCTAssertEqual([array valueAtIndex:3], 14U); + + XCTAssertThrowsSpecificNamed([array replaceValueAtIndex:4 withValue:14U], + NSException, NSRangeException); + + [array exchangeValueAtIndex:1 withValueAtIndex:3]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 11U); + XCTAssertEqual([array valueAtIndex:1], 14U); + XCTAssertEqual([array valueAtIndex:2], 13U); + XCTAssertEqual([array valueAtIndex:3], 12U); + + [array exchangeValueAtIndex:2 withValueAtIndex:0]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 13U); + XCTAssertEqual([array valueAtIndex:1], 14U); + XCTAssertEqual([array valueAtIndex:2], 11U); + XCTAssertEqual([array valueAtIndex:3], 12U); + + XCTAssertThrowsSpecificNamed([array exchangeValueAtIndex:4 withValueAtIndex:1], + NSException, NSRangeException); + XCTAssertThrowsSpecificNamed([array exchangeValueAtIndex:1 withValueAtIndex:4], + NSException, NSRangeException); + [array release]; +} + +- (void)testInternalResizing { + const uint32_t kValues[] = { 11U, 12U, 13U, 14U }; + GPBUInt32Array *array = + [GPBUInt32Array arrayWithCapacity:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + [array addValues:kValues count:GPBARRAYSIZE(kValues)]; + + // Add/remove to trigger the intneral buffer to grow/shrink. + for (int i = 0; i < 100; ++i) { + [array addValues:kValues count:GPBARRAYSIZE(kValues)]; + } + XCTAssertEqual(array.count, 404U); + for (int i = 0; i < 100; ++i) { + [array removeValueAtIndex:(i * 2)]; + } + XCTAssertEqual(array.count, 304U); + for (int i = 0; i < 100; ++i) { + [array insertValue:14U atIndex:(i * 3)]; + } + XCTAssertEqual(array.count, 404U); + [array removeAll]; + XCTAssertEqual(array.count, 0U); +} + +@end + +// clang-format on +//%PDDM-EXPAND ARRAY_TESTS(Int64, int64_t, 31LL, 32LL, 33LL, 34LL) +// This block of code is generated, do not edit it directly. +// clang-format off + +#pragma mark - Int64 + +@interface GPBInt64ArrayTests : XCTestCase +@end + +@implementation GPBInt64ArrayTests + +- (void)testEmpty { + GPBInt64Array *array = [[GPBInt64Array alloc] init]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 0U); + XCTAssertThrowsSpecificNamed([array valueAtIndex:0], NSException, NSRangeException); + [array enumerateValuesWithBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { + #pragma unused(value, idx, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { + #pragma unused(value, idx, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [array release]; +} + +- (void)testOne { + GPBInt64Array *array = [GPBInt64Array arrayWithValue:31LL]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 1U); + XCTAssertEqual([array valueAtIndex:0], 31LL); + XCTAssertThrowsSpecificNamed([array valueAtIndex:1], NSException, NSRangeException); + [array enumerateValuesWithBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, 0U); + XCTAssertEqual(value, 31LL); + XCTAssertNotEqual(stop, NULL); + }]; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, 0U); + XCTAssertEqual(value, 31LL); + XCTAssertNotEqual(stop, NULL); + }]; +} + +- (void)testBasics { + static const int64_t kValues[] = { 31LL, 32LL, 33LL, 34LL }; + GPBInt64Array *array = + [[GPBInt64Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 31LL); + XCTAssertEqual([array valueAtIndex:1], 32LL); + XCTAssertEqual([array valueAtIndex:2], 33LL); + XCTAssertEqual([array valueAtIndex:3], 34LL); + XCTAssertThrowsSpecificNamed([array valueAtIndex:4], NSException, NSRangeException); + __block NSUInteger idx2 = 0; + [array enumerateValuesWithBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, idx2); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + ++idx2; + }]; + idx2 = 0; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, (3 - idx2)); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + ++idx2; + }]; + // Stopping the enumeration. + idx2 = 0; + [array enumerateValuesWithBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, idx2); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + if (idx2 == 1) *stop = YES; + XCTAssertNotEqual(idx, 2U); + XCTAssertNotEqual(idx, 3U); + ++idx2; + }]; + idx2 = 0; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, (3 - idx2)); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + if (idx2 == 1) *stop = YES; + XCTAssertNotEqual(idx, 1U); + XCTAssertNotEqual(idx, 0U); + ++idx2; + }]; + // Ensure description doesn't choke. + XCTAssertTrue(array.description.length > 10); + [array release]; +} + +- (void)testEquality { + const int64_t kValues1[] = { 31LL, 32LL, 33LL }; + const int64_t kValues2[] = { 31LL, 34LL, 33LL }; + const int64_t kValues3[] = { 31LL, 32LL, 33LL, 34LL }; + GPBInt64Array *array1 = + [[GPBInt64Array alloc] initWithValues:kValues1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(array1); + GPBInt64Array *array1prime = + [[GPBInt64Array alloc] initWithValues:kValues1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(array1prime); + GPBInt64Array *array2 = + [[GPBInt64Array alloc] initWithValues:kValues2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(array2); + GPBInt64Array *array3 = + [[GPBInt64Array alloc] initWithValues:kValues3 + count:GPBARRAYSIZE(kValues3)]; + XCTAssertNotNil(array3); + + // Identity + XCTAssertTrue([array1 isEqual:array1]); + // Wrong type doesn't blow up. + XCTAssertFalse([array1 isEqual:@"bogus"]); + // 1/1Prime should be different objects, but equal. + XCTAssertNotEqual(array1, array1prime); + XCTAssertEqualObjects(array1, array1prime); + // Equal, so they must have same hash. + XCTAssertEqual([array1 hash], [array1prime hash]); + + // 1/2/3 shouldn't be equal. + XCTAssertNotEqualObjects(array1, array2); + XCTAssertNotEqualObjects(array1, array3); + XCTAssertNotEqualObjects(array2, array3); + + [array1 release]; + [array1prime release]; + [array2 release]; + [array3 release]; +} + +- (void)testCopy { + const int64_t kValues[] = { 31LL, 32LL, 33LL, 34LL }; + GPBInt64Array *array = + [[GPBInt64Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + GPBInt64Array *array2 = [array copy]; + XCTAssertNotNil(array2); + + // Should be new object but equal. + XCTAssertNotEqual(array, array2); + XCTAssertEqualObjects(array, array2); + [array2 release]; + [array release]; +} + +- (void)testArrayFromArray { + const int64_t kValues[] = { 31LL, 32LL, 33LL, 34LL }; + GPBInt64Array *array = + [[GPBInt64Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + GPBInt64Array *array2 = [GPBInt64Array arrayWithValueArray:array]; + XCTAssertNotNil(array2); + + // Should be new pointer, but equal objects. + XCTAssertNotEqual(array, array2); + XCTAssertEqualObjects(array, array2); + [array release]; +} + +- (void)testAdds { + GPBInt64Array *array = [GPBInt64Array array]; + XCTAssertNotNil(array); + + XCTAssertEqual(array.count, 0U); + [array addValue:31LL]; + XCTAssertEqual(array.count, 1U); + + const int64_t kValues1[] = { 32LL, 33LL }; + [array addValues:kValues1 count:GPBARRAYSIZE(kValues1)]; + XCTAssertEqual(array.count, 3U); + + const int64_t kValues2[] = { 34LL, 31LL }; + GPBInt64Array *array2 = + [[GPBInt64Array alloc] initWithValues:kValues2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(array2); + [array addValuesFromArray:array2]; + XCTAssertEqual(array.count, 5U); + + // Zero/nil inputs do nothing. + [array addValues:kValues1 count:0]; + XCTAssertEqual(array.count, 5U); + [array addValues:NULL count:5]; + XCTAssertEqual(array.count, 5U); + + XCTAssertEqual([array valueAtIndex:0], 31LL); + XCTAssertEqual([array valueAtIndex:1], 32LL); + XCTAssertEqual([array valueAtIndex:2], 33LL); + XCTAssertEqual([array valueAtIndex:3], 34LL); + XCTAssertEqual([array valueAtIndex:4], 31LL); + [array2 release]; +} + +- (void)testInsert { + const int64_t kValues[] = { 31LL, 32LL, 33LL }; + GPBInt64Array *array = + [[GPBInt64Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 3U); + + // First + [array insertValue:34LL atIndex:0]; + XCTAssertEqual(array.count, 4U); + + // Middle + [array insertValue:34LL atIndex:2]; + XCTAssertEqual(array.count, 5U); + + // End + [array insertValue:34LL atIndex:5]; + XCTAssertEqual(array.count, 6U); + + // Too far. + XCTAssertThrowsSpecificNamed([array insertValue:34LL atIndex:7], + NSException, NSRangeException); + + XCTAssertEqual([array valueAtIndex:0], 34LL); + XCTAssertEqual([array valueAtIndex:1], 31LL); + XCTAssertEqual([array valueAtIndex:2], 34LL); + XCTAssertEqual([array valueAtIndex:3], 32LL); + XCTAssertEqual([array valueAtIndex:4], 33LL); + XCTAssertEqual([array valueAtIndex:5], 34LL); + [array release]; +} + +- (void)testRemove { + const int64_t kValues[] = { 34LL, 31LL, 32LL, 34LL, 33LL, 34LL }; + GPBInt64Array *array = + [[GPBInt64Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 6U); + + // First + [array removeValueAtIndex:0]; + XCTAssertEqual(array.count, 5U); + XCTAssertEqual([array valueAtIndex:0], 31LL); + + // Middle + [array removeValueAtIndex:2]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:2], 33LL); + + // End + [array removeValueAtIndex:3]; + XCTAssertEqual(array.count, 3U); + + XCTAssertEqual([array valueAtIndex:0], 31LL); + XCTAssertEqual([array valueAtIndex:1], 32LL); + XCTAssertEqual([array valueAtIndex:2], 33LL); + + // Too far. + XCTAssertThrowsSpecificNamed([array removeValueAtIndex:3], + NSException, NSRangeException); + + [array removeAll]; + XCTAssertEqual(array.count, 0U); + XCTAssertThrowsSpecificNamed([array removeValueAtIndex:0], + NSException, NSRangeException); + [array release]; +} + +- (void)testInplaceMutation { + const int64_t kValues[] = { 31LL, 31LL, 33LL, 33LL }; + GPBInt64Array *array = + [[GPBInt64Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + [array replaceValueAtIndex:1 withValue:32LL]; + [array replaceValueAtIndex:3 withValue:34LL]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 31LL); + XCTAssertEqual([array valueAtIndex:1], 32LL); + XCTAssertEqual([array valueAtIndex:2], 33LL); + XCTAssertEqual([array valueAtIndex:3], 34LL); + + XCTAssertThrowsSpecificNamed([array replaceValueAtIndex:4 withValue:34LL], + NSException, NSRangeException); + + [array exchangeValueAtIndex:1 withValueAtIndex:3]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 31LL); + XCTAssertEqual([array valueAtIndex:1], 34LL); + XCTAssertEqual([array valueAtIndex:2], 33LL); + XCTAssertEqual([array valueAtIndex:3], 32LL); + + [array exchangeValueAtIndex:2 withValueAtIndex:0]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 33LL); + XCTAssertEqual([array valueAtIndex:1], 34LL); + XCTAssertEqual([array valueAtIndex:2], 31LL); + XCTAssertEqual([array valueAtIndex:3], 32LL); + + XCTAssertThrowsSpecificNamed([array exchangeValueAtIndex:4 withValueAtIndex:1], + NSException, NSRangeException); + XCTAssertThrowsSpecificNamed([array exchangeValueAtIndex:1 withValueAtIndex:4], + NSException, NSRangeException); + [array release]; +} + +- (void)testInternalResizing { + const int64_t kValues[] = { 31LL, 32LL, 33LL, 34LL }; + GPBInt64Array *array = + [GPBInt64Array arrayWithCapacity:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + [array addValues:kValues count:GPBARRAYSIZE(kValues)]; + + // Add/remove to trigger the intneral buffer to grow/shrink. + for (int i = 0; i < 100; ++i) { + [array addValues:kValues count:GPBARRAYSIZE(kValues)]; + } + XCTAssertEqual(array.count, 404U); + for (int i = 0; i < 100; ++i) { + [array removeValueAtIndex:(i * 2)]; + } + XCTAssertEqual(array.count, 304U); + for (int i = 0; i < 100; ++i) { + [array insertValue:34LL atIndex:(i * 3)]; + } + XCTAssertEqual(array.count, 404U); + [array removeAll]; + XCTAssertEqual(array.count, 0U); +} + +@end + +// clang-format on +//%PDDM-EXPAND ARRAY_TESTS(UInt64, uint64_t, 41ULL, 42ULL, 43ULL, 44ULL) +// This block of code is generated, do not edit it directly. +// clang-format off + +#pragma mark - UInt64 + +@interface GPBUInt64ArrayTests : XCTestCase +@end + +@implementation GPBUInt64ArrayTests + +- (void)testEmpty { + GPBUInt64Array *array = [[GPBUInt64Array alloc] init]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 0U); + XCTAssertThrowsSpecificNamed([array valueAtIndex:0], NSException, NSRangeException); + [array enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { + #pragma unused(value, idx, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { + #pragma unused(value, idx, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [array release]; +} + +- (void)testOne { + GPBUInt64Array *array = [GPBUInt64Array arrayWithValue:41ULL]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 1U); + XCTAssertEqual([array valueAtIndex:0], 41ULL); + XCTAssertThrowsSpecificNamed([array valueAtIndex:1], NSException, NSRangeException); + [array enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, 0U); + XCTAssertEqual(value, 41ULL); + XCTAssertNotEqual(stop, NULL); + }]; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, 0U); + XCTAssertEqual(value, 41ULL); + XCTAssertNotEqual(stop, NULL); + }]; +} + +- (void)testBasics { + static const uint64_t kValues[] = { 41ULL, 42ULL, 43ULL, 44ULL }; + GPBUInt64Array *array = + [[GPBUInt64Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 41ULL); + XCTAssertEqual([array valueAtIndex:1], 42ULL); + XCTAssertEqual([array valueAtIndex:2], 43ULL); + XCTAssertEqual([array valueAtIndex:3], 44ULL); + XCTAssertThrowsSpecificNamed([array valueAtIndex:4], NSException, NSRangeException); + __block NSUInteger idx2 = 0; + [array enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, idx2); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + ++idx2; + }]; + idx2 = 0; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, (3 - idx2)); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + ++idx2; + }]; + // Stopping the enumeration. + idx2 = 0; + [array enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, idx2); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + if (idx2 == 1) *stop = YES; + XCTAssertNotEqual(idx, 2U); + XCTAssertNotEqual(idx, 3U); + ++idx2; + }]; + idx2 = 0; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, (3 - idx2)); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + if (idx2 == 1) *stop = YES; + XCTAssertNotEqual(idx, 1U); + XCTAssertNotEqual(idx, 0U); + ++idx2; + }]; + // Ensure description doesn't choke. + XCTAssertTrue(array.description.length > 10); + [array release]; +} + +- (void)testEquality { + const uint64_t kValues1[] = { 41ULL, 42ULL, 43ULL }; + const uint64_t kValues2[] = { 41ULL, 44ULL, 43ULL }; + const uint64_t kValues3[] = { 41ULL, 42ULL, 43ULL, 44ULL }; + GPBUInt64Array *array1 = + [[GPBUInt64Array alloc] initWithValues:kValues1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(array1); + GPBUInt64Array *array1prime = + [[GPBUInt64Array alloc] initWithValues:kValues1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(array1prime); + GPBUInt64Array *array2 = + [[GPBUInt64Array alloc] initWithValues:kValues2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(array2); + GPBUInt64Array *array3 = + [[GPBUInt64Array alloc] initWithValues:kValues3 + count:GPBARRAYSIZE(kValues3)]; + XCTAssertNotNil(array3); + + // Identity + XCTAssertTrue([array1 isEqual:array1]); + // Wrong type doesn't blow up. + XCTAssertFalse([array1 isEqual:@"bogus"]); + // 1/1Prime should be different objects, but equal. + XCTAssertNotEqual(array1, array1prime); + XCTAssertEqualObjects(array1, array1prime); + // Equal, so they must have same hash. + XCTAssertEqual([array1 hash], [array1prime hash]); + + // 1/2/3 shouldn't be equal. + XCTAssertNotEqualObjects(array1, array2); + XCTAssertNotEqualObjects(array1, array3); + XCTAssertNotEqualObjects(array2, array3); + + [array1 release]; + [array1prime release]; + [array2 release]; + [array3 release]; +} + +- (void)testCopy { + const uint64_t kValues[] = { 41ULL, 42ULL, 43ULL, 44ULL }; + GPBUInt64Array *array = + [[GPBUInt64Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + GPBUInt64Array *array2 = [array copy]; + XCTAssertNotNil(array2); + + // Should be new object but equal. + XCTAssertNotEqual(array, array2); + XCTAssertEqualObjects(array, array2); + [array2 release]; + [array release]; +} + +- (void)testArrayFromArray { + const uint64_t kValues[] = { 41ULL, 42ULL, 43ULL, 44ULL }; + GPBUInt64Array *array = + [[GPBUInt64Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + GPBUInt64Array *array2 = [GPBUInt64Array arrayWithValueArray:array]; + XCTAssertNotNil(array2); + + // Should be new pointer, but equal objects. + XCTAssertNotEqual(array, array2); + XCTAssertEqualObjects(array, array2); + [array release]; +} + +- (void)testAdds { + GPBUInt64Array *array = [GPBUInt64Array array]; + XCTAssertNotNil(array); + + XCTAssertEqual(array.count, 0U); + [array addValue:41ULL]; + XCTAssertEqual(array.count, 1U); + + const uint64_t kValues1[] = { 42ULL, 43ULL }; + [array addValues:kValues1 count:GPBARRAYSIZE(kValues1)]; + XCTAssertEqual(array.count, 3U); + + const uint64_t kValues2[] = { 44ULL, 41ULL }; + GPBUInt64Array *array2 = + [[GPBUInt64Array alloc] initWithValues:kValues2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(array2); + [array addValuesFromArray:array2]; + XCTAssertEqual(array.count, 5U); + + // Zero/nil inputs do nothing. + [array addValues:kValues1 count:0]; + XCTAssertEqual(array.count, 5U); + [array addValues:NULL count:5]; + XCTAssertEqual(array.count, 5U); + + XCTAssertEqual([array valueAtIndex:0], 41ULL); + XCTAssertEqual([array valueAtIndex:1], 42ULL); + XCTAssertEqual([array valueAtIndex:2], 43ULL); + XCTAssertEqual([array valueAtIndex:3], 44ULL); + XCTAssertEqual([array valueAtIndex:4], 41ULL); + [array2 release]; +} + +- (void)testInsert { + const uint64_t kValues[] = { 41ULL, 42ULL, 43ULL }; + GPBUInt64Array *array = + [[GPBUInt64Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 3U); + + // First + [array insertValue:44ULL atIndex:0]; + XCTAssertEqual(array.count, 4U); + + // Middle + [array insertValue:44ULL atIndex:2]; + XCTAssertEqual(array.count, 5U); + + // End + [array insertValue:44ULL atIndex:5]; + XCTAssertEqual(array.count, 6U); + + // Too far. + XCTAssertThrowsSpecificNamed([array insertValue:44ULL atIndex:7], + NSException, NSRangeException); + + XCTAssertEqual([array valueAtIndex:0], 44ULL); + XCTAssertEqual([array valueAtIndex:1], 41ULL); + XCTAssertEqual([array valueAtIndex:2], 44ULL); + XCTAssertEqual([array valueAtIndex:3], 42ULL); + XCTAssertEqual([array valueAtIndex:4], 43ULL); + XCTAssertEqual([array valueAtIndex:5], 44ULL); + [array release]; +} + +- (void)testRemove { + const uint64_t kValues[] = { 44ULL, 41ULL, 42ULL, 44ULL, 43ULL, 44ULL }; + GPBUInt64Array *array = + [[GPBUInt64Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 6U); + + // First + [array removeValueAtIndex:0]; + XCTAssertEqual(array.count, 5U); + XCTAssertEqual([array valueAtIndex:0], 41ULL); + + // Middle + [array removeValueAtIndex:2]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:2], 43ULL); + + // End + [array removeValueAtIndex:3]; + XCTAssertEqual(array.count, 3U); + + XCTAssertEqual([array valueAtIndex:0], 41ULL); + XCTAssertEqual([array valueAtIndex:1], 42ULL); + XCTAssertEqual([array valueAtIndex:2], 43ULL); + + // Too far. + XCTAssertThrowsSpecificNamed([array removeValueAtIndex:3], + NSException, NSRangeException); + + [array removeAll]; + XCTAssertEqual(array.count, 0U); + XCTAssertThrowsSpecificNamed([array removeValueAtIndex:0], + NSException, NSRangeException); + [array release]; +} + +- (void)testInplaceMutation { + const uint64_t kValues[] = { 41ULL, 41ULL, 43ULL, 43ULL }; + GPBUInt64Array *array = + [[GPBUInt64Array alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + [array replaceValueAtIndex:1 withValue:42ULL]; + [array replaceValueAtIndex:3 withValue:44ULL]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 41ULL); + XCTAssertEqual([array valueAtIndex:1], 42ULL); + XCTAssertEqual([array valueAtIndex:2], 43ULL); + XCTAssertEqual([array valueAtIndex:3], 44ULL); + + XCTAssertThrowsSpecificNamed([array replaceValueAtIndex:4 withValue:44ULL], + NSException, NSRangeException); + + [array exchangeValueAtIndex:1 withValueAtIndex:3]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 41ULL); + XCTAssertEqual([array valueAtIndex:1], 44ULL); + XCTAssertEqual([array valueAtIndex:2], 43ULL); + XCTAssertEqual([array valueAtIndex:3], 42ULL); + + [array exchangeValueAtIndex:2 withValueAtIndex:0]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 43ULL); + XCTAssertEqual([array valueAtIndex:1], 44ULL); + XCTAssertEqual([array valueAtIndex:2], 41ULL); + XCTAssertEqual([array valueAtIndex:3], 42ULL); + + XCTAssertThrowsSpecificNamed([array exchangeValueAtIndex:4 withValueAtIndex:1], + NSException, NSRangeException); + XCTAssertThrowsSpecificNamed([array exchangeValueAtIndex:1 withValueAtIndex:4], + NSException, NSRangeException); + [array release]; +} + +- (void)testInternalResizing { + const uint64_t kValues[] = { 41ULL, 42ULL, 43ULL, 44ULL }; + GPBUInt64Array *array = + [GPBUInt64Array arrayWithCapacity:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + [array addValues:kValues count:GPBARRAYSIZE(kValues)]; + + // Add/remove to trigger the intneral buffer to grow/shrink. + for (int i = 0; i < 100; ++i) { + [array addValues:kValues count:GPBARRAYSIZE(kValues)]; + } + XCTAssertEqual(array.count, 404U); + for (int i = 0; i < 100; ++i) { + [array removeValueAtIndex:(i * 2)]; + } + XCTAssertEqual(array.count, 304U); + for (int i = 0; i < 100; ++i) { + [array insertValue:44ULL atIndex:(i * 3)]; + } + XCTAssertEqual(array.count, 404U); + [array removeAll]; + XCTAssertEqual(array.count, 0U); +} + +@end + +// clang-format on +//%PDDM-EXPAND ARRAY_TESTS(Float, float, 51.f, 52.f, 53.f, 54.f) +// This block of code is generated, do not edit it directly. +// clang-format off + +#pragma mark - Float + +@interface GPBFloatArrayTests : XCTestCase +@end + +@implementation GPBFloatArrayTests + +- (void)testEmpty { + GPBFloatArray *array = [[GPBFloatArray alloc] init]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 0U); + XCTAssertThrowsSpecificNamed([array valueAtIndex:0], NSException, NSRangeException); + [array enumerateValuesWithBlock:^(float value, NSUInteger idx, BOOL *stop) { + #pragma unused(value, idx, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(float value, NSUInteger idx, BOOL *stop) { + #pragma unused(value, idx, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [array release]; +} + +- (void)testOne { + GPBFloatArray *array = [GPBFloatArray arrayWithValue:51.f]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 1U); + XCTAssertEqual([array valueAtIndex:0], 51.f); + XCTAssertThrowsSpecificNamed([array valueAtIndex:1], NSException, NSRangeException); + [array enumerateValuesWithBlock:^(float value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, 0U); + XCTAssertEqual(value, 51.f); + XCTAssertNotEqual(stop, NULL); + }]; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(float value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, 0U); + XCTAssertEqual(value, 51.f); + XCTAssertNotEqual(stop, NULL); + }]; +} + +- (void)testBasics { + static const float kValues[] = { 51.f, 52.f, 53.f, 54.f }; + GPBFloatArray *array = + [[GPBFloatArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 51.f); + XCTAssertEqual([array valueAtIndex:1], 52.f); + XCTAssertEqual([array valueAtIndex:2], 53.f); + XCTAssertEqual([array valueAtIndex:3], 54.f); + XCTAssertThrowsSpecificNamed([array valueAtIndex:4], NSException, NSRangeException); + __block NSUInteger idx2 = 0; + [array enumerateValuesWithBlock:^(float value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, idx2); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + ++idx2; + }]; + idx2 = 0; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(float value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, (3 - idx2)); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + ++idx2; + }]; + // Stopping the enumeration. + idx2 = 0; + [array enumerateValuesWithBlock:^(float value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, idx2); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + if (idx2 == 1) *stop = YES; + XCTAssertNotEqual(idx, 2U); + XCTAssertNotEqual(idx, 3U); + ++idx2; + }]; + idx2 = 0; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(float value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, (3 - idx2)); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + if (idx2 == 1) *stop = YES; + XCTAssertNotEqual(idx, 1U); + XCTAssertNotEqual(idx, 0U); + ++idx2; + }]; + // Ensure description doesn't choke. + XCTAssertTrue(array.description.length > 10); + [array release]; +} + +- (void)testEquality { + const float kValues1[] = { 51.f, 52.f, 53.f }; + const float kValues2[] = { 51.f, 54.f, 53.f }; + const float kValues3[] = { 51.f, 52.f, 53.f, 54.f }; + GPBFloatArray *array1 = + [[GPBFloatArray alloc] initWithValues:kValues1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(array1); + GPBFloatArray *array1prime = + [[GPBFloatArray alloc] initWithValues:kValues1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(array1prime); + GPBFloatArray *array2 = + [[GPBFloatArray alloc] initWithValues:kValues2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(array2); + GPBFloatArray *array3 = + [[GPBFloatArray alloc] initWithValues:kValues3 + count:GPBARRAYSIZE(kValues3)]; + XCTAssertNotNil(array3); + + // Identity + XCTAssertTrue([array1 isEqual:array1]); + // Wrong type doesn't blow up. + XCTAssertFalse([array1 isEqual:@"bogus"]); + // 1/1Prime should be different objects, but equal. + XCTAssertNotEqual(array1, array1prime); + XCTAssertEqualObjects(array1, array1prime); + // Equal, so they must have same hash. + XCTAssertEqual([array1 hash], [array1prime hash]); + + // 1/2/3 shouldn't be equal. + XCTAssertNotEqualObjects(array1, array2); + XCTAssertNotEqualObjects(array1, array3); + XCTAssertNotEqualObjects(array2, array3); + + [array1 release]; + [array1prime release]; + [array2 release]; + [array3 release]; +} + +- (void)testCopy { + const float kValues[] = { 51.f, 52.f, 53.f, 54.f }; + GPBFloatArray *array = + [[GPBFloatArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + GPBFloatArray *array2 = [array copy]; + XCTAssertNotNil(array2); + + // Should be new object but equal. + XCTAssertNotEqual(array, array2); + XCTAssertEqualObjects(array, array2); + [array2 release]; + [array release]; +} + +- (void)testArrayFromArray { + const float kValues[] = { 51.f, 52.f, 53.f, 54.f }; + GPBFloatArray *array = + [[GPBFloatArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + GPBFloatArray *array2 = [GPBFloatArray arrayWithValueArray:array]; + XCTAssertNotNil(array2); + + // Should be new pointer, but equal objects. + XCTAssertNotEqual(array, array2); + XCTAssertEqualObjects(array, array2); + [array release]; +} + +- (void)testAdds { + GPBFloatArray *array = [GPBFloatArray array]; + XCTAssertNotNil(array); + + XCTAssertEqual(array.count, 0U); + [array addValue:51.f]; + XCTAssertEqual(array.count, 1U); + + const float kValues1[] = { 52.f, 53.f }; + [array addValues:kValues1 count:GPBARRAYSIZE(kValues1)]; + XCTAssertEqual(array.count, 3U); + + const float kValues2[] = { 54.f, 51.f }; + GPBFloatArray *array2 = + [[GPBFloatArray alloc] initWithValues:kValues2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(array2); + [array addValuesFromArray:array2]; + XCTAssertEqual(array.count, 5U); + + // Zero/nil inputs do nothing. + [array addValues:kValues1 count:0]; + XCTAssertEqual(array.count, 5U); + [array addValues:NULL count:5]; + XCTAssertEqual(array.count, 5U); + + XCTAssertEqual([array valueAtIndex:0], 51.f); + XCTAssertEqual([array valueAtIndex:1], 52.f); + XCTAssertEqual([array valueAtIndex:2], 53.f); + XCTAssertEqual([array valueAtIndex:3], 54.f); + XCTAssertEqual([array valueAtIndex:4], 51.f); + [array2 release]; +} + +- (void)testInsert { + const float kValues[] = { 51.f, 52.f, 53.f }; + GPBFloatArray *array = + [[GPBFloatArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 3U); + + // First + [array insertValue:54.f atIndex:0]; + XCTAssertEqual(array.count, 4U); + + // Middle + [array insertValue:54.f atIndex:2]; + XCTAssertEqual(array.count, 5U); + + // End + [array insertValue:54.f atIndex:5]; + XCTAssertEqual(array.count, 6U); + + // Too far. + XCTAssertThrowsSpecificNamed([array insertValue:54.f atIndex:7], + NSException, NSRangeException); + + XCTAssertEqual([array valueAtIndex:0], 54.f); + XCTAssertEqual([array valueAtIndex:1], 51.f); + XCTAssertEqual([array valueAtIndex:2], 54.f); + XCTAssertEqual([array valueAtIndex:3], 52.f); + XCTAssertEqual([array valueAtIndex:4], 53.f); + XCTAssertEqual([array valueAtIndex:5], 54.f); + [array release]; +} + +- (void)testRemove { + const float kValues[] = { 54.f, 51.f, 52.f, 54.f, 53.f, 54.f }; + GPBFloatArray *array = + [[GPBFloatArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 6U); + + // First + [array removeValueAtIndex:0]; + XCTAssertEqual(array.count, 5U); + XCTAssertEqual([array valueAtIndex:0], 51.f); + + // Middle + [array removeValueAtIndex:2]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:2], 53.f); + + // End + [array removeValueAtIndex:3]; + XCTAssertEqual(array.count, 3U); + + XCTAssertEqual([array valueAtIndex:0], 51.f); + XCTAssertEqual([array valueAtIndex:1], 52.f); + XCTAssertEqual([array valueAtIndex:2], 53.f); + + // Too far. + XCTAssertThrowsSpecificNamed([array removeValueAtIndex:3], + NSException, NSRangeException); + + [array removeAll]; + XCTAssertEqual(array.count, 0U); + XCTAssertThrowsSpecificNamed([array removeValueAtIndex:0], + NSException, NSRangeException); + [array release]; +} + +- (void)testInplaceMutation { + const float kValues[] = { 51.f, 51.f, 53.f, 53.f }; + GPBFloatArray *array = + [[GPBFloatArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + [array replaceValueAtIndex:1 withValue:52.f]; + [array replaceValueAtIndex:3 withValue:54.f]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 51.f); + XCTAssertEqual([array valueAtIndex:1], 52.f); + XCTAssertEqual([array valueAtIndex:2], 53.f); + XCTAssertEqual([array valueAtIndex:3], 54.f); + + XCTAssertThrowsSpecificNamed([array replaceValueAtIndex:4 withValue:54.f], + NSException, NSRangeException); + + [array exchangeValueAtIndex:1 withValueAtIndex:3]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 51.f); + XCTAssertEqual([array valueAtIndex:1], 54.f); + XCTAssertEqual([array valueAtIndex:2], 53.f); + XCTAssertEqual([array valueAtIndex:3], 52.f); + + [array exchangeValueAtIndex:2 withValueAtIndex:0]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 53.f); + XCTAssertEqual([array valueAtIndex:1], 54.f); + XCTAssertEqual([array valueAtIndex:2], 51.f); + XCTAssertEqual([array valueAtIndex:3], 52.f); + + XCTAssertThrowsSpecificNamed([array exchangeValueAtIndex:4 withValueAtIndex:1], + NSException, NSRangeException); + XCTAssertThrowsSpecificNamed([array exchangeValueAtIndex:1 withValueAtIndex:4], + NSException, NSRangeException); + [array release]; +} + +- (void)testInternalResizing { + const float kValues[] = { 51.f, 52.f, 53.f, 54.f }; + GPBFloatArray *array = + [GPBFloatArray arrayWithCapacity:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + [array addValues:kValues count:GPBARRAYSIZE(kValues)]; + + // Add/remove to trigger the intneral buffer to grow/shrink. + for (int i = 0; i < 100; ++i) { + [array addValues:kValues count:GPBARRAYSIZE(kValues)]; + } + XCTAssertEqual(array.count, 404U); + for (int i = 0; i < 100; ++i) { + [array removeValueAtIndex:(i * 2)]; + } + XCTAssertEqual(array.count, 304U); + for (int i = 0; i < 100; ++i) { + [array insertValue:54.f atIndex:(i * 3)]; + } + XCTAssertEqual(array.count, 404U); + [array removeAll]; + XCTAssertEqual(array.count, 0U); +} + +@end + +// clang-format on +//%PDDM-EXPAND ARRAY_TESTS(Double, double, 61., 62., 63., 64.) +// This block of code is generated, do not edit it directly. +// clang-format off + +#pragma mark - Double + +@interface GPBDoubleArrayTests : XCTestCase +@end + +@implementation GPBDoubleArrayTests + +- (void)testEmpty { + GPBDoubleArray *array = [[GPBDoubleArray alloc] init]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 0U); + XCTAssertThrowsSpecificNamed([array valueAtIndex:0], NSException, NSRangeException); + [array enumerateValuesWithBlock:^(double value, NSUInteger idx, BOOL *stop) { + #pragma unused(value, idx, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(double value, NSUInteger idx, BOOL *stop) { + #pragma unused(value, idx, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [array release]; +} + +- (void)testOne { + GPBDoubleArray *array = [GPBDoubleArray arrayWithValue:61.]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 1U); + XCTAssertEqual([array valueAtIndex:0], 61.); + XCTAssertThrowsSpecificNamed([array valueAtIndex:1], NSException, NSRangeException); + [array enumerateValuesWithBlock:^(double value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, 0U); + XCTAssertEqual(value, 61.); + XCTAssertNotEqual(stop, NULL); + }]; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(double value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, 0U); + XCTAssertEqual(value, 61.); + XCTAssertNotEqual(stop, NULL); + }]; +} + +- (void)testBasics { + static const double kValues[] = { 61., 62., 63., 64. }; + GPBDoubleArray *array = + [[GPBDoubleArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 61.); + XCTAssertEqual([array valueAtIndex:1], 62.); + XCTAssertEqual([array valueAtIndex:2], 63.); + XCTAssertEqual([array valueAtIndex:3], 64.); + XCTAssertThrowsSpecificNamed([array valueAtIndex:4], NSException, NSRangeException); + __block NSUInteger idx2 = 0; + [array enumerateValuesWithBlock:^(double value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, idx2); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + ++idx2; + }]; + idx2 = 0; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(double value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, (3 - idx2)); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + ++idx2; + }]; + // Stopping the enumeration. + idx2 = 0; + [array enumerateValuesWithBlock:^(double value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, idx2); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + if (idx2 == 1) *stop = YES; + XCTAssertNotEqual(idx, 2U); + XCTAssertNotEqual(idx, 3U); + ++idx2; + }]; + idx2 = 0; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(double value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, (3 - idx2)); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + if (idx2 == 1) *stop = YES; + XCTAssertNotEqual(idx, 1U); + XCTAssertNotEqual(idx, 0U); + ++idx2; + }]; + // Ensure description doesn't choke. + XCTAssertTrue(array.description.length > 10); + [array release]; +} + +- (void)testEquality { + const double kValues1[] = { 61., 62., 63. }; + const double kValues2[] = { 61., 64., 63. }; + const double kValues3[] = { 61., 62., 63., 64. }; + GPBDoubleArray *array1 = + [[GPBDoubleArray alloc] initWithValues:kValues1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(array1); + GPBDoubleArray *array1prime = + [[GPBDoubleArray alloc] initWithValues:kValues1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(array1prime); + GPBDoubleArray *array2 = + [[GPBDoubleArray alloc] initWithValues:kValues2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(array2); + GPBDoubleArray *array3 = + [[GPBDoubleArray alloc] initWithValues:kValues3 + count:GPBARRAYSIZE(kValues3)]; + XCTAssertNotNil(array3); + + // Identity + XCTAssertTrue([array1 isEqual:array1]); + // Wrong type doesn't blow up. + XCTAssertFalse([array1 isEqual:@"bogus"]); + // 1/1Prime should be different objects, but equal. + XCTAssertNotEqual(array1, array1prime); + XCTAssertEqualObjects(array1, array1prime); + // Equal, so they must have same hash. + XCTAssertEqual([array1 hash], [array1prime hash]); + + // 1/2/3 shouldn't be equal. + XCTAssertNotEqualObjects(array1, array2); + XCTAssertNotEqualObjects(array1, array3); + XCTAssertNotEqualObjects(array2, array3); + + [array1 release]; + [array1prime release]; + [array2 release]; + [array3 release]; +} + +- (void)testCopy { + const double kValues[] = { 61., 62., 63., 64. }; + GPBDoubleArray *array = + [[GPBDoubleArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + GPBDoubleArray *array2 = [array copy]; + XCTAssertNotNil(array2); + + // Should be new object but equal. + XCTAssertNotEqual(array, array2); + XCTAssertEqualObjects(array, array2); + [array2 release]; + [array release]; +} + +- (void)testArrayFromArray { + const double kValues[] = { 61., 62., 63., 64. }; + GPBDoubleArray *array = + [[GPBDoubleArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + GPBDoubleArray *array2 = [GPBDoubleArray arrayWithValueArray:array]; + XCTAssertNotNil(array2); + + // Should be new pointer, but equal objects. + XCTAssertNotEqual(array, array2); + XCTAssertEqualObjects(array, array2); + [array release]; +} + +- (void)testAdds { + GPBDoubleArray *array = [GPBDoubleArray array]; + XCTAssertNotNil(array); + + XCTAssertEqual(array.count, 0U); + [array addValue:61.]; + XCTAssertEqual(array.count, 1U); + + const double kValues1[] = { 62., 63. }; + [array addValues:kValues1 count:GPBARRAYSIZE(kValues1)]; + XCTAssertEqual(array.count, 3U); + + const double kValues2[] = { 64., 61. }; + GPBDoubleArray *array2 = + [[GPBDoubleArray alloc] initWithValues:kValues2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(array2); + [array addValuesFromArray:array2]; + XCTAssertEqual(array.count, 5U); + + // Zero/nil inputs do nothing. + [array addValues:kValues1 count:0]; + XCTAssertEqual(array.count, 5U); + [array addValues:NULL count:5]; + XCTAssertEqual(array.count, 5U); + + XCTAssertEqual([array valueAtIndex:0], 61.); + XCTAssertEqual([array valueAtIndex:1], 62.); + XCTAssertEqual([array valueAtIndex:2], 63.); + XCTAssertEqual([array valueAtIndex:3], 64.); + XCTAssertEqual([array valueAtIndex:4], 61.); + [array2 release]; +} + +- (void)testInsert { + const double kValues[] = { 61., 62., 63. }; + GPBDoubleArray *array = + [[GPBDoubleArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 3U); + + // First + [array insertValue:64. atIndex:0]; + XCTAssertEqual(array.count, 4U); + + // Middle + [array insertValue:64. atIndex:2]; + XCTAssertEqual(array.count, 5U); + + // End + [array insertValue:64. atIndex:5]; + XCTAssertEqual(array.count, 6U); + + // Too far. + XCTAssertThrowsSpecificNamed([array insertValue:64. atIndex:7], + NSException, NSRangeException); + + XCTAssertEqual([array valueAtIndex:0], 64.); + XCTAssertEqual([array valueAtIndex:1], 61.); + XCTAssertEqual([array valueAtIndex:2], 64.); + XCTAssertEqual([array valueAtIndex:3], 62.); + XCTAssertEqual([array valueAtIndex:4], 63.); + XCTAssertEqual([array valueAtIndex:5], 64.); + [array release]; +} + +- (void)testRemove { + const double kValues[] = { 64., 61., 62., 64., 63., 64. }; + GPBDoubleArray *array = + [[GPBDoubleArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 6U); + + // First + [array removeValueAtIndex:0]; + XCTAssertEqual(array.count, 5U); + XCTAssertEqual([array valueAtIndex:0], 61.); + + // Middle + [array removeValueAtIndex:2]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:2], 63.); + + // End + [array removeValueAtIndex:3]; + XCTAssertEqual(array.count, 3U); + + XCTAssertEqual([array valueAtIndex:0], 61.); + XCTAssertEqual([array valueAtIndex:1], 62.); + XCTAssertEqual([array valueAtIndex:2], 63.); + + // Too far. + XCTAssertThrowsSpecificNamed([array removeValueAtIndex:3], + NSException, NSRangeException); + + [array removeAll]; + XCTAssertEqual(array.count, 0U); + XCTAssertThrowsSpecificNamed([array removeValueAtIndex:0], + NSException, NSRangeException); + [array release]; +} + +- (void)testInplaceMutation { + const double kValues[] = { 61., 61., 63., 63. }; + GPBDoubleArray *array = + [[GPBDoubleArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + [array replaceValueAtIndex:1 withValue:62.]; + [array replaceValueAtIndex:3 withValue:64.]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 61.); + XCTAssertEqual([array valueAtIndex:1], 62.); + XCTAssertEqual([array valueAtIndex:2], 63.); + XCTAssertEqual([array valueAtIndex:3], 64.); + + XCTAssertThrowsSpecificNamed([array replaceValueAtIndex:4 withValue:64.], + NSException, NSRangeException); + + [array exchangeValueAtIndex:1 withValueAtIndex:3]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 61.); + XCTAssertEqual([array valueAtIndex:1], 64.); + XCTAssertEqual([array valueAtIndex:2], 63.); + XCTAssertEqual([array valueAtIndex:3], 62.); + + [array exchangeValueAtIndex:2 withValueAtIndex:0]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 63.); + XCTAssertEqual([array valueAtIndex:1], 64.); + XCTAssertEqual([array valueAtIndex:2], 61.); + XCTAssertEqual([array valueAtIndex:3], 62.); + + XCTAssertThrowsSpecificNamed([array exchangeValueAtIndex:4 withValueAtIndex:1], + NSException, NSRangeException); + XCTAssertThrowsSpecificNamed([array exchangeValueAtIndex:1 withValueAtIndex:4], + NSException, NSRangeException); + [array release]; +} + +- (void)testInternalResizing { + const double kValues[] = { 61., 62., 63., 64. }; + GPBDoubleArray *array = + [GPBDoubleArray arrayWithCapacity:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + [array addValues:kValues count:GPBARRAYSIZE(kValues)]; + + // Add/remove to trigger the intneral buffer to grow/shrink. + for (int i = 0; i < 100; ++i) { + [array addValues:kValues count:GPBARRAYSIZE(kValues)]; + } + XCTAssertEqual(array.count, 404U); + for (int i = 0; i < 100; ++i) { + [array removeValueAtIndex:(i * 2)]; + } + XCTAssertEqual(array.count, 304U); + for (int i = 0; i < 100; ++i) { + [array insertValue:64. atIndex:(i * 3)]; + } + XCTAssertEqual(array.count, 404U); + [array removeAll]; + XCTAssertEqual(array.count, 0U); +} + +@end + +// clang-format on +//%PDDM-EXPAND ARRAY_TESTS(Bool, BOOL, TRUE, TRUE, FALSE, FALSE) +// This block of code is generated, do not edit it directly. +// clang-format off + +#pragma mark - Bool + +@interface GPBBoolArrayTests : XCTestCase +@end + +@implementation GPBBoolArrayTests + +- (void)testEmpty { + GPBBoolArray *array = [[GPBBoolArray alloc] init]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 0U); + XCTAssertThrowsSpecificNamed([array valueAtIndex:0], NSException, NSRangeException); + [array enumerateValuesWithBlock:^(BOOL value, NSUInteger idx, BOOL *stop) { + #pragma unused(value, idx, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(BOOL value, NSUInteger idx, BOOL *stop) { + #pragma unused(value, idx, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [array release]; +} + +- (void)testOne { + GPBBoolArray *array = [GPBBoolArray arrayWithValue:TRUE]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 1U); + XCTAssertEqual([array valueAtIndex:0], TRUE); + XCTAssertThrowsSpecificNamed([array valueAtIndex:1], NSException, NSRangeException); + [array enumerateValuesWithBlock:^(BOOL value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, 0U); + XCTAssertEqual(value, TRUE); + XCTAssertNotEqual(stop, NULL); + }]; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(BOOL value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, 0U); + XCTAssertEqual(value, TRUE); + XCTAssertNotEqual(stop, NULL); + }]; +} + +- (void)testBasics { + static const BOOL kValues[] = { TRUE, TRUE, FALSE, FALSE }; + GPBBoolArray *array = + [[GPBBoolArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], TRUE); + XCTAssertEqual([array valueAtIndex:1], TRUE); + XCTAssertEqual([array valueAtIndex:2], FALSE); + XCTAssertEqual([array valueAtIndex:3], FALSE); + XCTAssertThrowsSpecificNamed([array valueAtIndex:4], NSException, NSRangeException); + __block NSUInteger idx2 = 0; + [array enumerateValuesWithBlock:^(BOOL value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, idx2); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + ++idx2; + }]; + idx2 = 0; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(BOOL value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, (3 - idx2)); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + ++idx2; + }]; + // Stopping the enumeration. + idx2 = 0; + [array enumerateValuesWithBlock:^(BOOL value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, idx2); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + if (idx2 == 1) *stop = YES; + XCTAssertNotEqual(idx, 2U); + XCTAssertNotEqual(idx, 3U); + ++idx2; + }]; + idx2 = 0; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(BOOL value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, (3 - idx2)); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + if (idx2 == 1) *stop = YES; + XCTAssertNotEqual(idx, 1U); + XCTAssertNotEqual(idx, 0U); + ++idx2; + }]; + // Ensure description doesn't choke. + XCTAssertTrue(array.description.length > 10); + [array release]; +} + +- (void)testEquality { + const BOOL kValues1[] = { TRUE, TRUE, FALSE }; + const BOOL kValues2[] = { TRUE, FALSE, FALSE }; + const BOOL kValues3[] = { TRUE, TRUE, FALSE, FALSE }; + GPBBoolArray *array1 = + [[GPBBoolArray alloc] initWithValues:kValues1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(array1); + GPBBoolArray *array1prime = + [[GPBBoolArray alloc] initWithValues:kValues1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(array1prime); + GPBBoolArray *array2 = + [[GPBBoolArray alloc] initWithValues:kValues2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(array2); + GPBBoolArray *array3 = + [[GPBBoolArray alloc] initWithValues:kValues3 + count:GPBARRAYSIZE(kValues3)]; + XCTAssertNotNil(array3); + + // Identity + XCTAssertTrue([array1 isEqual:array1]); + // Wrong type doesn't blow up. + XCTAssertFalse([array1 isEqual:@"bogus"]); + // 1/1Prime should be different objects, but equal. + XCTAssertNotEqual(array1, array1prime); + XCTAssertEqualObjects(array1, array1prime); + // Equal, so they must have same hash. + XCTAssertEqual([array1 hash], [array1prime hash]); + + // 1/2/3 shouldn't be equal. + XCTAssertNotEqualObjects(array1, array2); + XCTAssertNotEqualObjects(array1, array3); + XCTAssertNotEqualObjects(array2, array3); + + [array1 release]; + [array1prime release]; + [array2 release]; + [array3 release]; +} + +- (void)testCopy { + const BOOL kValues[] = { TRUE, TRUE, FALSE, FALSE }; + GPBBoolArray *array = + [[GPBBoolArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + GPBBoolArray *array2 = [array copy]; + XCTAssertNotNil(array2); + + // Should be new object but equal. + XCTAssertNotEqual(array, array2); + XCTAssertEqualObjects(array, array2); + [array2 release]; + [array release]; +} + +- (void)testArrayFromArray { + const BOOL kValues[] = { TRUE, TRUE, FALSE, FALSE }; + GPBBoolArray *array = + [[GPBBoolArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + GPBBoolArray *array2 = [GPBBoolArray arrayWithValueArray:array]; + XCTAssertNotNil(array2); + + // Should be new pointer, but equal objects. + XCTAssertNotEqual(array, array2); + XCTAssertEqualObjects(array, array2); + [array release]; +} + +- (void)testAdds { + GPBBoolArray *array = [GPBBoolArray array]; + XCTAssertNotNil(array); + + XCTAssertEqual(array.count, 0U); + [array addValue:TRUE]; + XCTAssertEqual(array.count, 1U); + + const BOOL kValues1[] = { TRUE, FALSE }; + [array addValues:kValues1 count:GPBARRAYSIZE(kValues1)]; + XCTAssertEqual(array.count, 3U); + + const BOOL kValues2[] = { FALSE, TRUE }; + GPBBoolArray *array2 = + [[GPBBoolArray alloc] initWithValues:kValues2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(array2); + [array addValuesFromArray:array2]; + XCTAssertEqual(array.count, 5U); + + // Zero/nil inputs do nothing. + [array addValues:kValues1 count:0]; + XCTAssertEqual(array.count, 5U); + [array addValues:NULL count:5]; + XCTAssertEqual(array.count, 5U); + + XCTAssertEqual([array valueAtIndex:0], TRUE); + XCTAssertEqual([array valueAtIndex:1], TRUE); + XCTAssertEqual([array valueAtIndex:2], FALSE); + XCTAssertEqual([array valueAtIndex:3], FALSE); + XCTAssertEqual([array valueAtIndex:4], TRUE); + [array2 release]; +} + +- (void)testInsert { + const BOOL kValues[] = { TRUE, TRUE, FALSE }; + GPBBoolArray *array = + [[GPBBoolArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 3U); + + // First + [array insertValue:FALSE atIndex:0]; + XCTAssertEqual(array.count, 4U); + + // Middle + [array insertValue:FALSE atIndex:2]; + XCTAssertEqual(array.count, 5U); + + // End + [array insertValue:FALSE atIndex:5]; + XCTAssertEqual(array.count, 6U); + + // Too far. + XCTAssertThrowsSpecificNamed([array insertValue:FALSE atIndex:7], + NSException, NSRangeException); + + XCTAssertEqual([array valueAtIndex:0], FALSE); + XCTAssertEqual([array valueAtIndex:1], TRUE); + XCTAssertEqual([array valueAtIndex:2], FALSE); + XCTAssertEqual([array valueAtIndex:3], TRUE); + XCTAssertEqual([array valueAtIndex:4], FALSE); + XCTAssertEqual([array valueAtIndex:5], FALSE); + [array release]; +} + +- (void)testRemove { + const BOOL kValues[] = { FALSE, TRUE, TRUE, FALSE, FALSE, FALSE }; + GPBBoolArray *array = + [[GPBBoolArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 6U); + + // First + [array removeValueAtIndex:0]; + XCTAssertEqual(array.count, 5U); + XCTAssertEqual([array valueAtIndex:0], TRUE); + + // Middle + [array removeValueAtIndex:2]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:2], FALSE); + + // End + [array removeValueAtIndex:3]; + XCTAssertEqual(array.count, 3U); + + XCTAssertEqual([array valueAtIndex:0], TRUE); + XCTAssertEqual([array valueAtIndex:1], TRUE); + XCTAssertEqual([array valueAtIndex:2], FALSE); + + // Too far. + XCTAssertThrowsSpecificNamed([array removeValueAtIndex:3], + NSException, NSRangeException); + + [array removeAll]; + XCTAssertEqual(array.count, 0U); + XCTAssertThrowsSpecificNamed([array removeValueAtIndex:0], + NSException, NSRangeException); + [array release]; +} + +- (void)testInplaceMutation { + const BOOL kValues[] = { TRUE, TRUE, FALSE, FALSE }; + GPBBoolArray *array = + [[GPBBoolArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + [array replaceValueAtIndex:1 withValue:TRUE]; + [array replaceValueAtIndex:3 withValue:FALSE]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], TRUE); + XCTAssertEqual([array valueAtIndex:1], TRUE); + XCTAssertEqual([array valueAtIndex:2], FALSE); + XCTAssertEqual([array valueAtIndex:3], FALSE); + + XCTAssertThrowsSpecificNamed([array replaceValueAtIndex:4 withValue:FALSE], + NSException, NSRangeException); + + [array exchangeValueAtIndex:1 withValueAtIndex:3]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], TRUE); + XCTAssertEqual([array valueAtIndex:1], FALSE); + XCTAssertEqual([array valueAtIndex:2], FALSE); + XCTAssertEqual([array valueAtIndex:3], TRUE); + + [array exchangeValueAtIndex:2 withValueAtIndex:0]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], FALSE); + XCTAssertEqual([array valueAtIndex:1], FALSE); + XCTAssertEqual([array valueAtIndex:2], TRUE); + XCTAssertEqual([array valueAtIndex:3], TRUE); + + XCTAssertThrowsSpecificNamed([array exchangeValueAtIndex:4 withValueAtIndex:1], + NSException, NSRangeException); + XCTAssertThrowsSpecificNamed([array exchangeValueAtIndex:1 withValueAtIndex:4], + NSException, NSRangeException); + [array release]; +} + +- (void)testInternalResizing { + const BOOL kValues[] = { TRUE, TRUE, FALSE, FALSE }; + GPBBoolArray *array = + [GPBBoolArray arrayWithCapacity:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + [array addValues:kValues count:GPBARRAYSIZE(kValues)]; + + // Add/remove to trigger the intneral buffer to grow/shrink. + for (int i = 0; i < 100; ++i) { + [array addValues:kValues count:GPBARRAYSIZE(kValues)]; + } + XCTAssertEqual(array.count, 404U); + for (int i = 0; i < 100; ++i) { + [array removeValueAtIndex:(i * 2)]; + } + XCTAssertEqual(array.count, 304U); + for (int i = 0; i < 100; ++i) { + [array insertValue:FALSE atIndex:(i * 3)]; + } + XCTAssertEqual(array.count, 404U); + [array removeAll]; + XCTAssertEqual(array.count, 0U); +} + +@end + +// clang-format on +//%PDDM-EXPAND ARRAY_TESTS2(Enum, int32_t, 71, 72, 73, 74, Raw) +// This block of code is generated, do not edit it directly. +// clang-format off + +#pragma mark - Enum + +@interface GPBEnumArrayTests : XCTestCase +@end + +@implementation GPBEnumArrayTests + +- (void)testEmpty { + GPBEnumArray *array = [[GPBEnumArray alloc] init]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 0U); + XCTAssertThrowsSpecificNamed([array valueAtIndex:0], NSException, NSRangeException); + [array enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { + #pragma unused(value, idx, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { + #pragma unused(value, idx, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [array release]; +} + +- (void)testOne { + GPBEnumArray *array = [GPBEnumArray arrayWithValue:71]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 1U); + XCTAssertEqual([array valueAtIndex:0], 71); + XCTAssertThrowsSpecificNamed([array valueAtIndex:1], NSException, NSRangeException); + [array enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, 0U); + XCTAssertEqual(value, 71); + XCTAssertNotEqual(stop, NULL); + }]; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, 0U); + XCTAssertEqual(value, 71); + XCTAssertNotEqual(stop, NULL); + }]; +} + +- (void)testBasics { + static const int32_t kValues[] = { 71, 72, 73, 74 }; + GPBEnumArray *array = + [[GPBEnumArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 71); + XCTAssertEqual([array valueAtIndex:1], 72); + XCTAssertEqual([array valueAtIndex:2], 73); + XCTAssertEqual([array valueAtIndex:3], 74); + XCTAssertThrowsSpecificNamed([array valueAtIndex:4], NSException, NSRangeException); + __block NSUInteger idx2 = 0; + [array enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, idx2); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + ++idx2; + }]; + idx2 = 0; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, (3 - idx2)); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + ++idx2; + }]; + // Stopping the enumeration. + idx2 = 0; + [array enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, idx2); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + if (idx2 == 1) *stop = YES; + XCTAssertNotEqual(idx, 2U); + XCTAssertNotEqual(idx, 3U); + ++idx2; + }]; + idx2 = 0; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, (3 - idx2)); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + if (idx2 == 1) *stop = YES; + XCTAssertNotEqual(idx, 1U); + XCTAssertNotEqual(idx, 0U); + ++idx2; + }]; + // Ensure description doesn't choke. + XCTAssertTrue(array.description.length > 10); + [array release]; +} + +- (void)testEquality { + const int32_t kValues1[] = { 71, 72, 73 }; + const int32_t kValues2[] = { 71, 74, 73 }; + const int32_t kValues3[] = { 71, 72, 73, 74 }; + GPBEnumArray *array1 = + [[GPBEnumArray alloc] initWithValues:kValues1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(array1); + GPBEnumArray *array1prime = + [[GPBEnumArray alloc] initWithValues:kValues1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(array1prime); + GPBEnumArray *array2 = + [[GPBEnumArray alloc] initWithValues:kValues2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(array2); + GPBEnumArray *array3 = + [[GPBEnumArray alloc] initWithValues:kValues3 + count:GPBARRAYSIZE(kValues3)]; + XCTAssertNotNil(array3); + + // Identity + XCTAssertTrue([array1 isEqual:array1]); + // Wrong type doesn't blow up. + XCTAssertFalse([array1 isEqual:@"bogus"]); + // 1/1Prime should be different objects, but equal. + XCTAssertNotEqual(array1, array1prime); + XCTAssertEqualObjects(array1, array1prime); + // Equal, so they must have same hash. + XCTAssertEqual([array1 hash], [array1prime hash]); + + // 1/2/3 shouldn't be equal. + XCTAssertNotEqualObjects(array1, array2); + XCTAssertNotEqualObjects(array1, array3); + XCTAssertNotEqualObjects(array2, array3); + + [array1 release]; + [array1prime release]; + [array2 release]; + [array3 release]; +} + +- (void)testCopy { + const int32_t kValues[] = { 71, 72, 73, 74 }; + GPBEnumArray *array = + [[GPBEnumArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + GPBEnumArray *array2 = [array copy]; + XCTAssertNotNil(array2); + + // Should be new object but equal. + XCTAssertNotEqual(array, array2); + XCTAssertEqualObjects(array, array2); + [array2 release]; + [array release]; +} + +- (void)testArrayFromArray { + const int32_t kValues[] = { 71, 72, 73, 74 }; + GPBEnumArray *array = + [[GPBEnumArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + GPBEnumArray *array2 = [GPBEnumArray arrayWithValueArray:array]; + XCTAssertNotNil(array2); + + // Should be new pointer, but equal objects. + XCTAssertNotEqual(array, array2); + XCTAssertEqualObjects(array, array2); + [array release]; +} + +- (void)testAdds { + GPBEnumArray *array = [GPBEnumArray array]; + XCTAssertNotNil(array); + + XCTAssertEqual(array.count, 0U); + [array addValue:71]; + XCTAssertEqual(array.count, 1U); + + const int32_t kValues1[] = { 72, 73 }; + [array addValues:kValues1 count:GPBARRAYSIZE(kValues1)]; + XCTAssertEqual(array.count, 3U); + + const int32_t kValues2[] = { 74, 71 }; + GPBEnumArray *array2 = + [[GPBEnumArray alloc] initWithValues:kValues2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(array2); + [array addRawValuesFromArray:array2]; + XCTAssertEqual(array.count, 5U); + + // Zero/nil inputs do nothing. + [array addValues:kValues1 count:0]; + XCTAssertEqual(array.count, 5U); + [array addValues:NULL count:5]; + XCTAssertEqual(array.count, 5U); + + XCTAssertEqual([array valueAtIndex:0], 71); + XCTAssertEqual([array valueAtIndex:1], 72); + XCTAssertEqual([array valueAtIndex:2], 73); + XCTAssertEqual([array valueAtIndex:3], 74); + XCTAssertEqual([array valueAtIndex:4], 71); + [array2 release]; +} + +- (void)testInsert { + const int32_t kValues[] = { 71, 72, 73 }; + GPBEnumArray *array = + [[GPBEnumArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 3U); + + // First + [array insertValue:74 atIndex:0]; + XCTAssertEqual(array.count, 4U); + + // Middle + [array insertValue:74 atIndex:2]; + XCTAssertEqual(array.count, 5U); + + // End + [array insertValue:74 atIndex:5]; + XCTAssertEqual(array.count, 6U); + + // Too far. + XCTAssertThrowsSpecificNamed([array insertValue:74 atIndex:7], + NSException, NSRangeException); + + XCTAssertEqual([array valueAtIndex:0], 74); + XCTAssertEqual([array valueAtIndex:1], 71); + XCTAssertEqual([array valueAtIndex:2], 74); + XCTAssertEqual([array valueAtIndex:3], 72); + XCTAssertEqual([array valueAtIndex:4], 73); + XCTAssertEqual([array valueAtIndex:5], 74); + [array release]; +} + +- (void)testRemove { + const int32_t kValues[] = { 74, 71, 72, 74, 73, 74 }; + GPBEnumArray *array = + [[GPBEnumArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 6U); + + // First + [array removeValueAtIndex:0]; + XCTAssertEqual(array.count, 5U); + XCTAssertEqual([array valueAtIndex:0], 71); + + // Middle + [array removeValueAtIndex:2]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:2], 73); + + // End + [array removeValueAtIndex:3]; + XCTAssertEqual(array.count, 3U); + + XCTAssertEqual([array valueAtIndex:0], 71); + XCTAssertEqual([array valueAtIndex:1], 72); + XCTAssertEqual([array valueAtIndex:2], 73); + + // Too far. + XCTAssertThrowsSpecificNamed([array removeValueAtIndex:3], + NSException, NSRangeException); + + [array removeAll]; + XCTAssertEqual(array.count, 0U); + XCTAssertThrowsSpecificNamed([array removeValueAtIndex:0], + NSException, NSRangeException); + [array release]; +} + +- (void)testInplaceMutation { + const int32_t kValues[] = { 71, 71, 73, 73 }; + GPBEnumArray *array = + [[GPBEnumArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + [array replaceValueAtIndex:1 withValue:72]; + [array replaceValueAtIndex:3 withValue:74]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 71); + XCTAssertEqual([array valueAtIndex:1], 72); + XCTAssertEqual([array valueAtIndex:2], 73); + XCTAssertEqual([array valueAtIndex:3], 74); + + XCTAssertThrowsSpecificNamed([array replaceValueAtIndex:4 withValue:74], + NSException, NSRangeException); + + [array exchangeValueAtIndex:1 withValueAtIndex:3]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 71); + XCTAssertEqual([array valueAtIndex:1], 74); + XCTAssertEqual([array valueAtIndex:2], 73); + XCTAssertEqual([array valueAtIndex:3], 72); + + [array exchangeValueAtIndex:2 withValueAtIndex:0]; + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 73); + XCTAssertEqual([array valueAtIndex:1], 74); + XCTAssertEqual([array valueAtIndex:2], 71); + XCTAssertEqual([array valueAtIndex:3], 72); + + XCTAssertThrowsSpecificNamed([array exchangeValueAtIndex:4 withValueAtIndex:1], + NSException, NSRangeException); + XCTAssertThrowsSpecificNamed([array exchangeValueAtIndex:1 withValueAtIndex:4], + NSException, NSRangeException); + [array release]; +} + +- (void)testInternalResizing { + const int32_t kValues[] = { 71, 72, 73, 74 }; + GPBEnumArray *array = + [GPBEnumArray arrayWithCapacity:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + [array addValues:kValues count:GPBARRAYSIZE(kValues)]; + + // Add/remove to trigger the intneral buffer to grow/shrink. + for (int i = 0; i < 100; ++i) { + [array addValues:kValues count:GPBARRAYSIZE(kValues)]; + } + XCTAssertEqual(array.count, 404U); + for (int i = 0; i < 100; ++i) { + [array removeValueAtIndex:(i * 2)]; + } + XCTAssertEqual(array.count, 304U); + for (int i = 0; i < 100; ++i) { + [array insertValue:74 atIndex:(i * 3)]; + } + XCTAssertEqual(array.count, 404U); + [array removeAll]; + XCTAssertEqual(array.count, 0U); +} + +@end + +// clang-format on +//%PDDM-EXPAND-END (8 expansions) + +#pragma mark - Non macro-based Enum tests + +// These are hand written tests to cover the verification and raw methods. + +@interface GPBEnumArrayCustomTests : XCTestCase +@end + +@implementation GPBEnumArrayCustomTests + +- (void)testRawBasics { + static const int32_t kValues[] = { 71, 272, 73, 374 }; + static const int32_t kValuesFiltered[] = { + 71, kGPBUnrecognizedEnumeratorValue, 73, kGPBUnrecognizedEnumeratorValue + }; + XCTAssertEqual(GPBARRAYSIZE(kValues), GPBARRAYSIZE(kValuesFiltered)); + GPBEnumArray *array = + [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 4U); + GPBEnumValidationFunc func = TestingEnum_IsValidValue; + XCTAssertEqual(array.validationFunc, func); + XCTAssertEqual([array rawValueAtIndex:0], 71); + XCTAssertEqual([array rawValueAtIndex:1], 272); + XCTAssertEqual([array valueAtIndex:1], kGPBUnrecognizedEnumeratorValue); + XCTAssertEqual([array rawValueAtIndex:2], 73); + XCTAssertEqual([array rawValueAtIndex:3], 374); + XCTAssertEqual([array valueAtIndex:3], kGPBUnrecognizedEnumeratorValue); + XCTAssertThrowsSpecificNamed([array rawValueAtIndex:4], NSException, NSRangeException); + __block NSUInteger idx2 = 0; + [array enumerateRawValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, idx2); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + ++idx2; + }]; + idx2 = 0; + [array enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, idx2); + XCTAssertEqual(value, kValuesFiltered[idx]); + XCTAssertNotEqual(stop, NULL); + ++idx2; + }]; + idx2 = 0; + [array enumerateRawValuesWithOptions:NSEnumerationReverse + usingBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, (3 - idx2)); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + ++idx2; + }]; + idx2 = 0; + [array enumerateValuesWithOptions:NSEnumerationReverse + usingBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, (3 - idx2)); + XCTAssertEqual(value, kValuesFiltered[idx]); + XCTAssertNotEqual(stop, NULL); + ++idx2; + }]; + // Stopping the enumeration. + idx2 = 0; + [array enumerateRawValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, idx2); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + if (idx2 == 1) *stop = YES; + XCTAssertNotEqual(idx, 2U); + XCTAssertNotEqual(idx, 3U); + ++idx2; + }]; + idx2 = 0; + [array enumerateRawValuesWithOptions:NSEnumerationReverse + usingBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { + XCTAssertEqual(idx, (3 - idx2)); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + if (idx2 == 1) *stop = YES; + XCTAssertNotEqual(idx, 1U); + XCTAssertNotEqual(idx, 0U); + ++idx2; + }]; + [array release]; +} + +- (void)testEquality { + const int32_t kValues1[] = { 71, 72, 173 }; // With unknown value + const int32_t kValues2[] = { 71, 74, 173 }; // With unknown value + const int32_t kValues3[] = { 71, 72, 173, 74 }; // With unknown value + GPBEnumArray *array1 = + [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(array1); + GPBEnumArray *array1prime = + [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue2 + rawValues:kValues1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(array1prime); + GPBEnumArray *array2 = + [[GPBEnumArray alloc] initWithValues:kValues2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(array2); + GPBEnumArray *array3 = + [[GPBEnumArray alloc] initWithValues:kValues3 + count:GPBARRAYSIZE(kValues3)]; + XCTAssertNotNil(array3); + + // 1/1Prime should be different objects, but equal. + XCTAssertNotEqual(array1, array1prime); + XCTAssertEqualObjects(array1, array1prime); + // Equal, so they must have same hash. + XCTAssertEqual([array1 hash], [array1prime hash]); + // But different validation functions. + XCTAssertNotEqual(array1.validationFunc, array1prime.validationFunc); + + // 1/2/3 shouldn't be equal. + XCTAssertNotEqualObjects(array1, array2); + XCTAssertNotEqualObjects(array1, array3); + XCTAssertNotEqualObjects(array2, array3); + + [array1 release]; + [array1prime release]; + [array2 release]; + [array3 release]; +} + +- (void)testCopy { + const int32_t kValues[] = { 71, 72 }; + GPBEnumArray *array = + [[GPBEnumArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + [array addRawValue:1000]; // Unknown + XCTAssertEqual(array.count, 3U); + XCTAssertEqual([array rawValueAtIndex:0], 71); + XCTAssertEqual([array rawValueAtIndex:1], 72); + XCTAssertEqual([array rawValueAtIndex:2], 1000); + XCTAssertEqual([array valueAtIndex:2], kGPBUnrecognizedEnumeratorValue); + + GPBEnumArray *array2 = [array copy]; + XCTAssertNotNil(array2); + + // Should be new object but equal. + XCTAssertNotEqual(array, array2); + XCTAssertEqualObjects(array, array2); + XCTAssertEqual(array.validationFunc, array2.validationFunc); + XCTAssertTrue([array2 isKindOfClass:[GPBEnumArray class]]); + XCTAssertEqual(array2.count, 3U); + XCTAssertEqual([array2 rawValueAtIndex:0], 71); + XCTAssertEqual([array2 rawValueAtIndex:1], 72); + XCTAssertEqual([array2 rawValueAtIndex:2], 1000); + XCTAssertEqual([array2 valueAtIndex:2], kGPBUnrecognizedEnumeratorValue); + [array2 release]; + [array release]; +} + +- (void)testArrayFromArray { + const int32_t kValues[] = { 71, 172, 173, 74 }; // Unknowns + GPBEnumArray *array = + [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + GPBEnumArray *array2 = [GPBEnumArray arrayWithValueArray:array]; + XCTAssertNotNil(array2); + + // Should be new pointer, but equal objects. + XCTAssertNotEqual(array, array2); + XCTAssertEqualObjects(array, array2); + XCTAssertEqual(array.validationFunc, array2.validationFunc); + [array release]; +} + +- (void)testUnknownAdds { + GPBEnumArray *array = + [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue]; + XCTAssertNotNil(array); + + XCTAssertThrowsSpecificNamed([array addValue:172], + NSException, NSInvalidArgumentException); + XCTAssertEqual(array.count, 0U); + + const int32_t kValues1[] = { 172, 173 }; // Unknown + XCTAssertThrowsSpecificNamed([array addValues:kValues1 count:GPBARRAYSIZE(kValues1)], + NSException, NSInvalidArgumentException); + XCTAssertEqual(array.count, 0U); + [array release]; +} + +- (void)testRawAdds { + GPBEnumArray *array = + [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue]; + XCTAssertNotNil(array); + + XCTAssertEqual(array.count, 0U); + [array addRawValue:71]; // Valid + XCTAssertEqual(array.count, 1U); + + const int32_t kValues1[] = { 172, 173 }; // Unknown + [array addRawValues:kValues1 count:GPBARRAYSIZE(kValues1)]; + XCTAssertEqual(array.count, 3U); + + const int32_t kValues2[] = { 74, 71 }; + GPBEnumArray *array2 = + [[GPBEnumArray alloc] initWithValues:kValues2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(array2); + [array addRawValuesFromArray:array2]; + XCTAssertEqual(array.count, 5U); + + XCTAssertEqual([array rawValueAtIndex:0], 71); + XCTAssertEqual([array rawValueAtIndex:1], 172); + XCTAssertEqual([array valueAtIndex:1], kGPBUnrecognizedEnumeratorValue); + XCTAssertEqual([array rawValueAtIndex:2], 173); + XCTAssertEqual([array valueAtIndex:2], kGPBUnrecognizedEnumeratorValue); + XCTAssertEqual([array rawValueAtIndex:3], 74); + XCTAssertEqual([array rawValueAtIndex:4], 71); + [array release]; +} + +- (void)testUnknownInserts { + const int32_t kValues[] = { 71, 72, 73 }; + GPBEnumArray *array = + [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 3U); + + // First + XCTAssertThrowsSpecificNamed([array insertValue:174 atIndex:0], + NSException, NSInvalidArgumentException); + XCTAssertEqual(array.count, 3U); + + // Middle + XCTAssertThrowsSpecificNamed([array insertValue:274 atIndex:1], + NSException, NSInvalidArgumentException); + XCTAssertEqual(array.count, 3U); + + // End + XCTAssertThrowsSpecificNamed([array insertValue:374 atIndex:3], + NSException, NSInvalidArgumentException); + XCTAssertEqual(array.count, 3U); + [array release]; +} + +- (void)testRawInsert { + const int32_t kValues[] = { 71, 72, 73 }; + GPBEnumArray *array = + [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + XCTAssertEqual(array.count, 3U); + + // First + [array insertRawValue:174 atIndex:0]; // Unknown + XCTAssertEqual(array.count, 4U); + + // Middle + [array insertRawValue:274 atIndex:2]; // Unknown + XCTAssertEqual(array.count, 5U); + + // End + [array insertRawValue:374 atIndex:5]; // Unknown + XCTAssertEqual(array.count, 6U); + + // Too far. + XCTAssertThrowsSpecificNamed([array insertRawValue:74 atIndex:7], + NSException, NSRangeException); + + XCTAssertEqual([array rawValueAtIndex:0], 174); + XCTAssertEqual([array valueAtIndex:0], kGPBUnrecognizedEnumeratorValue); + XCTAssertEqual([array rawValueAtIndex:1], 71); + XCTAssertEqual([array rawValueAtIndex:2], 274); + XCTAssertEqual([array valueAtIndex:2], kGPBUnrecognizedEnumeratorValue); + XCTAssertEqual([array rawValueAtIndex:3], 72); + XCTAssertEqual([array rawValueAtIndex:4], 73); + XCTAssertEqual([array rawValueAtIndex:5], 374); + XCTAssertEqual([array valueAtIndex:5], kGPBUnrecognizedEnumeratorValue); + [array release]; +} + +- (void)testUnknownInplaceMutation { + const int32_t kValues[] = { 71, 72, 73, 74 }; + GPBEnumArray *array = + [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + XCTAssertThrowsSpecificNamed([array replaceValueAtIndex:1 withValue:172], + NSException, NSInvalidArgumentException); + XCTAssertThrowsSpecificNamed([array replaceValueAtIndex:3 withValue:274], + NSException, NSInvalidArgumentException); + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array valueAtIndex:0], 71); + XCTAssertEqual([array valueAtIndex:1], 72); + XCTAssertEqual([array valueAtIndex:2], 73); + XCTAssertEqual([array valueAtIndex:3], 74); + [array release]; +} + + +- (void)testRawInplaceMutation { + const int32_t kValues[] = { 71, 72, 73, 74 }; + GPBEnumArray *array = + [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + [array replaceValueAtIndex:1 withRawValue:172]; // Unknown + [array replaceValueAtIndex:3 withRawValue:274]; // Unknown + XCTAssertEqual(array.count, 4U); + XCTAssertEqual([array rawValueAtIndex:0], 71); + XCTAssertEqual([array rawValueAtIndex:1], 172); + XCTAssertEqual([array valueAtIndex:1], kGPBUnrecognizedEnumeratorValue); + XCTAssertEqual([array rawValueAtIndex:2], 73); + XCTAssertEqual([array rawValueAtIndex:3], 274); + XCTAssertEqual([array valueAtIndex:3], kGPBUnrecognizedEnumeratorValue); + + XCTAssertThrowsSpecificNamed([array replaceValueAtIndex:4 withRawValue:74], + NSException, NSRangeException); + [array release]; +} + +- (void)testRawInternalResizing { + const int32_t kValues[] = { 71, 172, 173, 74 }; // Unknown + GPBEnumArray *array = + [[GPBEnumArray alloc] initWithValues:kValues + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(array); + + // Add/remove to trigger the intneral buffer to grow/shrink. + for (int i = 0; i < 100; ++i) { + [array addRawValues:kValues count:GPBARRAYSIZE(kValues)]; + } + XCTAssertEqual(array.count, 404U); + for (int i = 0; i < 100; ++i) { + [array removeValueAtIndex:(i * 2)]; + } + XCTAssertEqual(array.count, 304U); + for (int i = 0; i < 100; ++i) { + [array insertRawValue:274 atIndex:(i * 3)]; // Unknown + } + XCTAssertEqual(array.count, 404U); + [array removeAll]; + XCTAssertEqual(array.count, 0U); + [array release]; +} + +@end + +#pragma mark - GPBAutocreatedArray Tests + +// These are hand written tests to double check some behaviors of the +// GPBAutocreatedArray. + +// NOTE: GPBAutocreatedArray is private to the library, users of the library +// should never have to directly deal with this class. + +@interface GPBAutocreatedArrayTests : XCTestCase +@end + +@implementation GPBAutocreatedArrayTests + +- (void)testEquality { + GPBAutocreatedArray *array = [[GPBAutocreatedArray alloc] init]; + + XCTAssertTrue([array isEqual:@[]]); + XCTAssertTrue([array isEqualToArray:@[]]); + + XCTAssertFalse([array isEqual:@[ @"foo" ]]); + XCTAssertFalse([array isEqualToArray:@[ @"foo" ]]); + + [array addObject:@"foo"]; + + XCTAssertFalse([array isEqual:@[]]); + XCTAssertFalse([array isEqualToArray:@[]]); + XCTAssertTrue([array isEqual:@[ @"foo" ]]); + XCTAssertTrue([array isEqualToArray:@[ @"foo" ]]); + XCTAssertFalse([array isEqual:@[ @"bar" ]]); + XCTAssertFalse([array isEqualToArray:@[ @"bar" ]]); + + GPBAutocreatedArray *array2 = [[GPBAutocreatedArray alloc] init]; + + XCTAssertFalse([array isEqual:array2]); + XCTAssertFalse([array isEqualToArray:array2]); + + [array2 addObject:@"bar"]; + XCTAssertFalse([array isEqual:array2]); + XCTAssertFalse([array isEqualToArray:array2]); + + [array2 replaceObjectAtIndex:0 withObject:@"foo"]; + XCTAssertTrue([array isEqual:array2]); + XCTAssertTrue([array isEqualToArray:array2]); + + [array2 release]; + [array release]; +} + +- (void)testCopy { + { + GPBAutocreatedArray *array = [[GPBAutocreatedArray alloc] init]; + + NSArray *cpy = [array copy]; + XCTAssertTrue(cpy != array); // Ptr compare + XCTAssertTrue([cpy isKindOfClass:[NSArray class]]); + XCTAssertFalse([cpy isKindOfClass:[GPBAutocreatedArray class]]); + XCTAssertEqual(cpy.count, (NSUInteger)0); + + NSArray *cpy2 = [array copy]; + XCTAssertTrue(cpy2 != array); // Ptr compare + // Can't compare cpy and cpy2 because NSArray has a singleton empty + // array it uses, so the ptrs are the same. + XCTAssertTrue([cpy2 isKindOfClass:[NSArray class]]); + XCTAssertFalse([cpy2 isKindOfClass:[GPBAutocreatedArray class]]); + XCTAssertEqual(cpy2.count, (NSUInteger)0); + + [cpy2 release]; + [cpy release]; + [array release]; + } + + { + GPBAutocreatedArray *array = [[GPBAutocreatedArray alloc] init]; + + NSMutableArray *cpy = [array mutableCopy]; + XCTAssertTrue(cpy != array); // Ptr compare + XCTAssertTrue([cpy isKindOfClass:[NSMutableArray class]]); + XCTAssertFalse([cpy isKindOfClass:[GPBAutocreatedArray class]]); + XCTAssertEqual(cpy.count, (NSUInteger)0); + + NSMutableArray *cpy2 = [array mutableCopy]; + XCTAssertTrue(cpy2 != array); // Ptr compare + XCTAssertTrue(cpy2 != cpy); // Ptr compare + XCTAssertTrue([cpy2 isKindOfClass:[NSMutableArray class]]); + XCTAssertFalse([cpy2 isKindOfClass:[GPBAutocreatedArray class]]); + XCTAssertEqual(cpy2.count, (NSUInteger)0); + + [cpy2 release]; + [cpy release]; + [array release]; + } + + { + GPBAutocreatedArray *array = [[GPBAutocreatedArray alloc] init]; + [array addObject:@"foo"]; + [array addObject:@"bar"]; + + NSArray *cpy = [array copy]; + XCTAssertTrue(cpy != array); // Ptr compare + XCTAssertTrue([cpy isKindOfClass:[NSArray class]]); + XCTAssertFalse([cpy isKindOfClass:[GPBAutocreatedArray class]]); + XCTAssertEqual(cpy.count, (NSUInteger)2); + XCTAssertEqualObjects(cpy[0], @"foo"); + XCTAssertEqualObjects(cpy[1], @"bar"); + + NSArray *cpy2 = [array copy]; + XCTAssertTrue(cpy2 != array); // Ptr compare + XCTAssertTrue(cpy2 != cpy); // Ptr compare + XCTAssertTrue([cpy2 isKindOfClass:[NSArray class]]); + XCTAssertFalse([cpy2 isKindOfClass:[GPBAutocreatedArray class]]); + XCTAssertEqual(cpy2.count, (NSUInteger)2); + XCTAssertEqualObjects(cpy2[0], @"foo"); + XCTAssertEqualObjects(cpy2[1], @"bar"); + + [cpy2 release]; + [cpy release]; + [array release]; + } + + { + GPBAutocreatedArray *array = [[GPBAutocreatedArray alloc] init]; + [array addObject:@"foo"]; + [array addObject:@"bar"]; + + NSMutableArray *cpy = [array mutableCopy]; + XCTAssertTrue(cpy != array); // Ptr compare + XCTAssertTrue([cpy isKindOfClass:[NSArray class]]); + XCTAssertFalse([cpy isKindOfClass:[GPBAutocreatedArray class]]); + XCTAssertEqual(cpy.count, (NSUInteger)2); + XCTAssertEqualObjects(cpy[0], @"foo"); + XCTAssertEqualObjects(cpy[1], @"bar"); + + NSMutableArray *cpy2 = [array mutableCopy]; + XCTAssertTrue(cpy2 != array); // Ptr compare + XCTAssertTrue(cpy2 != cpy); // Ptr compare + XCTAssertTrue([cpy2 isKindOfClass:[NSArray class]]); + XCTAssertFalse([cpy2 isKindOfClass:[GPBAutocreatedArray class]]); + XCTAssertEqual(cpy2.count, (NSUInteger)2); + XCTAssertEqualObjects(cpy2[0], @"foo"); + XCTAssertEqualObjects(cpy2[1], @"bar"); + + [cpy2 release]; + [cpy release]; + [array release]; + } +} + +- (void)testIndexedSubscriptSupport { + // The base NSArray/NSMutableArray behaviors for *IndexedSubscript methods + // should still work via the methods that one has to override to make an + // NSMutableArray subclass. i.e. - this should "just work" and if these + // crash/fail, then something is wrong in how NSMutableArray is subclassed. + + GPBAutocreatedArray *array = [[GPBAutocreatedArray alloc] init]; + + [array addObject:@"foo"]; + [array addObject:@"bar"]; + XCTAssertEqual(array.count, (NSUInteger)2); + XCTAssertEqualObjects(array[0], @"foo"); + XCTAssertEqualObjects(array[1], @"bar"); + array[0] = @"foo2"; + array[2] = @"baz"; + XCTAssertEqual(array.count, (NSUInteger)3); + XCTAssertEqualObjects(array[0], @"foo2"); + XCTAssertEqualObjects(array[1], @"bar"); + XCTAssertEqualObjects(array[2], @"baz"); + + [array release]; +} + +@end diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/GPBCompileTest15.m b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/GPBCompileTest15.m new file mode 100644 index 0000000..2eaedb2 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/GPBCompileTest15.m @@ -0,0 +1,40 @@ +// 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. + + +// This is a test including a single public header to ensure things build. +// It helps test that imports are complete/ordered correctly. + +#import "GPBApi.pbobjc.h" + + +// Something in the body of this file so the compiler/linker won't complain +// about an empty .o file. +__attribute__((visibility("default"))) char dummy_symbol_15 = 0; diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/GPBCompileTest21.m b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/GPBCompileTest21.m new file mode 100644 index 0000000..766d890 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/GPBCompileTest21.m @@ -0,0 +1,40 @@ +// 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. + + +// This is a test including a single public header to ensure things build. +// It helps test that imports are complete/ordered correctly. + +#import "GPBTimestamp.pbobjc.h" + + +// Something in the body of this file so the compiler/linker won't complain +// about an empty .o file. +__attribute__((visibility("default"))) char dummy_symbol_21 = 0; diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/GPBDictionaryTests+UInt32.m b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/GPBDictionaryTests+UInt32.m new file mode 100644 index 0000000..f607538 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/GPBDictionaryTests+UInt32.m @@ -0,0 +1,3678 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. + +#import +#import + +#import "GPBDictionary.h" + +#import "GPBTestUtilities.h" +#import "google/protobuf/UnittestRuntimeProto2.pbobjc.h" + +// Pull in the macros (using an external file because expanding all tests +// in a single file makes a file that is failing to work with within Xcode. +//%PDDM-IMPORT-DEFINES GPBDictionaryTests.pddm + +//%PDDM-EXPAND TEST_FOR_POD_KEY(UInt32, uint32_t, 1U, 2U, 3U, 4U) +// This block of code is generated, do not edit it directly. +// clang-format off + +// To let the testing macros work, add some extra methods to simplify things. +@interface GPBUInt32EnumDictionary (TestingTweak) +- (instancetype)initWithEnums:(const int32_t [])values + forKeys:(const uint32_t [])keys + count:(NSUInteger)count; +@end + +static BOOL TestingEnum_IsValidValue(int32_t value) { + switch (value) { + case 700: + case 701: + case 702: + case 703: + return YES; + default: + return NO; + } +} + +@implementation GPBUInt32EnumDictionary (TestingTweak) +- (instancetype)initWithEnums:(const int32_t [])values + forKeys:(const uint32_t [])keys + count:(NSUInteger)count { + return [self initWithValidationFunction:TestingEnum_IsValidValue + rawValues:values + forKeys:keys + count:count]; +} +@end + + +#pragma mark - UInt32 -> UInt32 + +@interface GPBUInt32UInt32DictionaryTests : XCTestCase +@end + +@implementation GPBUInt32UInt32DictionaryTests + +- (void)testEmpty { + GPBUInt32UInt32Dictionary *dict = [[GPBUInt32UInt32Dictionary alloc] init]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 0U); + XCTAssertFalse([dict getUInt32:NULL forKey:1U]); + [dict enumerateKeysAndUInt32sUsingBlock:^(uint32_t aKey, uint32_t aValue, BOOL *stop) { + #pragma unused(aKey, aValue, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [dict release]; +} + +- (void)testOne { + GPBUInt32UInt32Dictionary *dict = [[GPBUInt32UInt32Dictionary alloc] init]; + [dict setUInt32:100U forKey:1U]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 1U); + uint32_t value; + XCTAssertTrue([dict getUInt32:NULL forKey:1U]); + XCTAssertTrue([dict getUInt32:&value forKey:1U]); + XCTAssertEqual(value, 100U); + XCTAssertFalse([dict getUInt32:NULL forKey:2U]); + [dict enumerateKeysAndUInt32sUsingBlock:^(uint32_t aKey, uint32_t aValue, BOOL *stop) { + XCTAssertEqual(aKey, 1U); + XCTAssertEqual(aValue, 100U); + XCTAssertNotEqual(stop, NULL); + }]; + [dict release]; +} + +- (void)testBasics { + const uint32_t kKeys[] = { 1U, 2U, 3U }; + const uint32_t kValues[] = { 100U, 101U, 102U }; + GPBUInt32UInt32Dictionary *dict = + [[GPBUInt32UInt32Dictionary alloc] initWithUInt32s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 3U); + uint32_t value; + XCTAssertTrue([dict getUInt32:NULL forKey:1U]); + XCTAssertTrue([dict getUInt32:&value forKey:1U]); + XCTAssertEqual(value, 100U); + XCTAssertTrue([dict getUInt32:NULL forKey:2U]); + XCTAssertTrue([dict getUInt32:&value forKey:2U]); + XCTAssertEqual(value, 101U); + XCTAssertTrue([dict getUInt32:NULL forKey:3U]); + XCTAssertTrue([dict getUInt32:&value forKey:3U]); + XCTAssertEqual(value, 102U); + XCTAssertFalse([dict getUInt32:NULL forKey:4U]); + + __block NSUInteger idx = 0; + uint32_t *seenKeys = malloc(3 * sizeof(uint32_t)); + uint32_t *seenValues = malloc(3 * sizeof(uint32_t)); + [dict enumerateKeysAndUInt32sUsingBlock:^(uint32_t aKey, uint32_t aValue, BOOL *stop) { + XCTAssertLessThan(idx, 3U); + seenKeys[idx] = aKey; + seenValues[idx] = aValue; + XCTAssertNotEqual(stop, NULL); + ++idx; + }]; + for (int i = 0; i < 3; ++i) { + BOOL foundKey = NO; + for (int j = 0; (j < 3) && !foundKey; ++j) { + if (kKeys[i] == seenKeys[j]) { + foundKey = YES; + XCTAssertEqual(kValues[i], seenValues[j], @"i = %d, j = %d", i, j); + } + } + XCTAssertTrue(foundKey, @"i = %d", i); + } + free(seenKeys); + free(seenValues); + + // Stopping the enumeration. + idx = 0; + [dict enumerateKeysAndUInt32sUsingBlock:^(uint32_t aKey, uint32_t aValue, BOOL *stop) { + #pragma unused(aKey, aValue) + if (idx == 1) *stop = YES; + XCTAssertNotEqual(idx, 2U); + ++idx; + }]; + [dict release]; +} + +- (void)testEquality { + const uint32_t kKeys1[] = { 1U, 2U, 3U, 4U }; + const uint32_t kKeys2[] = { 2U, 1U, 4U }; + const uint32_t kValues1[] = { 100U, 101U, 102U }; + const uint32_t kValues2[] = { 100U, 103U, 102U }; + const uint32_t kValues3[] = { 100U, 101U, 102U, 103U }; + GPBUInt32UInt32Dictionary *dict1 = + [[GPBUInt32UInt32Dictionary alloc] initWithUInt32s:kValues1 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict1); + GPBUInt32UInt32Dictionary *dict1prime = + [[GPBUInt32UInt32Dictionary alloc] initWithUInt32s:kValues1 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict1prime); + GPBUInt32UInt32Dictionary *dict2 = + [[GPBUInt32UInt32Dictionary alloc] initWithUInt32s:kValues2 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(dict2); + GPBUInt32UInt32Dictionary *dict3 = + [[GPBUInt32UInt32Dictionary alloc] initWithUInt32s:kValues1 + forKeys:kKeys2 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict3); + GPBUInt32UInt32Dictionary *dict4 = + [[GPBUInt32UInt32Dictionary alloc] initWithUInt32s:kValues3 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues3)]; + XCTAssertNotNil(dict4); + + // 1/1Prime should be different objects, but equal. + XCTAssertNotEqual(dict1, dict1prime); + XCTAssertEqualObjects(dict1, dict1prime); + // Equal, so they must have same hash. + XCTAssertEqual([dict1 hash], [dict1prime hash]); + + // 2 is same keys, different values; not equal. + XCTAssertNotEqualObjects(dict1, dict2); + + // 3 is different keys, same values; not equal. + XCTAssertNotEqualObjects(dict1, dict3); + + // 4 extra pair; not equal + XCTAssertNotEqualObjects(dict1, dict4); + + [dict1 release]; + [dict1prime release]; + [dict2 release]; + [dict3 release]; + [dict4 release]; +} + +- (void)testCopy { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const uint32_t kValues[] = { 100U, 101U, 102U, 103U }; + GPBUInt32UInt32Dictionary *dict = + [[GPBUInt32UInt32Dictionary alloc] initWithUInt32s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + + GPBUInt32UInt32Dictionary *dict2 = [dict copy]; + XCTAssertNotNil(dict2); + + // Should be new object but equal. + XCTAssertNotEqual(dict, dict2); + XCTAssertEqualObjects(dict, dict2); + XCTAssertTrue([dict2 isKindOfClass:[GPBUInt32UInt32Dictionary class]]); + + [dict2 release]; + [dict release]; +} + +- (void)testDictionaryFromDictionary { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const uint32_t kValues[] = { 100U, 101U, 102U, 103U }; + GPBUInt32UInt32Dictionary *dict = + [[GPBUInt32UInt32Dictionary alloc] initWithUInt32s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + + GPBUInt32UInt32Dictionary *dict2 = + [[GPBUInt32UInt32Dictionary alloc] initWithDictionary:dict]; + XCTAssertNotNil(dict2); + + // Should be new pointer, but equal objects. + XCTAssertNotEqual(dict, dict2); + XCTAssertEqualObjects(dict, dict2); + [dict2 release]; + [dict release]; +} + +- (void)testAdds { + GPBUInt32UInt32Dictionary *dict = [[GPBUInt32UInt32Dictionary alloc] init]; + XCTAssertNotNil(dict); + + XCTAssertEqual(dict.count, 0U); + [dict setUInt32:100U forKey:1U]; + XCTAssertEqual(dict.count, 1U); + + const uint32_t kKeys[] = { 2U, 3U, 4U }; + const uint32_t kValues[] = { 101U, 102U, 103U }; + GPBUInt32UInt32Dictionary *dict2 = + [[GPBUInt32UInt32Dictionary alloc] initWithUInt32s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict2); + [dict addEntriesFromDictionary:dict2]; + XCTAssertEqual(dict.count, 4U); + + uint32_t value; + XCTAssertTrue([dict getUInt32:NULL forKey:1U]); + XCTAssertTrue([dict getUInt32:&value forKey:1U]); + XCTAssertEqual(value, 100U); + XCTAssertTrue([dict getUInt32:NULL forKey:2U]); + XCTAssertTrue([dict getUInt32:&value forKey:2U]); + XCTAssertEqual(value, 101U); + XCTAssertTrue([dict getUInt32:NULL forKey:3U]); + XCTAssertTrue([dict getUInt32:&value forKey:3U]); + XCTAssertEqual(value, 102U); + XCTAssertTrue([dict getUInt32:NULL forKey:4U]); + XCTAssertTrue([dict getUInt32:&value forKey:4U]); + XCTAssertEqual(value, 103U); + [dict2 release]; + [dict release]; +} + +- (void)testRemove { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const uint32_t kValues[] = { 100U, 101U, 102U, 103U }; + GPBUInt32UInt32Dictionary *dict = + [[GPBUInt32UInt32Dictionary alloc] initWithUInt32s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 4U); + + [dict removeUInt32ForKey:2U]; + XCTAssertEqual(dict.count, 3U); + uint32_t value; + XCTAssertTrue([dict getUInt32:NULL forKey:1U]); + XCTAssertTrue([dict getUInt32:&value forKey:1U]); + XCTAssertEqual(value, 100U); + XCTAssertFalse([dict getUInt32:NULL forKey:2U]); + XCTAssertTrue([dict getUInt32:NULL forKey:3U]); + XCTAssertTrue([dict getUInt32:&value forKey:3U]); + XCTAssertEqual(value, 102U); + XCTAssertTrue([dict getUInt32:NULL forKey:4U]); + XCTAssertTrue([dict getUInt32:&value forKey:4U]); + XCTAssertEqual(value, 103U); + + // Remove again does nothing. + [dict removeUInt32ForKey:2U]; + XCTAssertEqual(dict.count, 3U); + XCTAssertTrue([dict getUInt32:NULL forKey:1U]); + XCTAssertTrue([dict getUInt32:&value forKey:1U]); + XCTAssertEqual(value, 100U); + XCTAssertFalse([dict getUInt32:NULL forKey:2U]); + XCTAssertTrue([dict getUInt32:NULL forKey:3U]); + XCTAssertTrue([dict getUInt32:&value forKey:3U]); + XCTAssertEqual(value, 102U); + XCTAssertTrue([dict getUInt32:NULL forKey:4U]); + XCTAssertTrue([dict getUInt32:&value forKey:4U]); + XCTAssertEqual(value, 103U); + + [dict removeUInt32ForKey:4U]; + XCTAssertEqual(dict.count, 2U); + XCTAssertTrue([dict getUInt32:NULL forKey:1U]); + XCTAssertTrue([dict getUInt32:&value forKey:1U]); + XCTAssertEqual(value, 100U); + XCTAssertFalse([dict getUInt32:NULL forKey:2U]); + XCTAssertTrue([dict getUInt32:NULL forKey:3U]); + XCTAssertTrue([dict getUInt32:&value forKey:3U]); + XCTAssertEqual(value, 102U); + XCTAssertFalse([dict getUInt32:NULL forKey:4U]); + + [dict removeAll]; + XCTAssertEqual(dict.count, 0U); + XCTAssertFalse([dict getUInt32:NULL forKey:1U]); + XCTAssertFalse([dict getUInt32:NULL forKey:2U]); + XCTAssertFalse([dict getUInt32:NULL forKey:3U]); + XCTAssertFalse([dict getUInt32:NULL forKey:4U]); + [dict release]; +} + +- (void)testInplaceMutation { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const uint32_t kValues[] = { 100U, 101U, 102U, 103U }; + GPBUInt32UInt32Dictionary *dict = + [[GPBUInt32UInt32Dictionary alloc] initWithUInt32s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 4U); + uint32_t value; + XCTAssertTrue([dict getUInt32:NULL forKey:1U]); + XCTAssertTrue([dict getUInt32:&value forKey:1U]); + XCTAssertEqual(value, 100U); + XCTAssertTrue([dict getUInt32:NULL forKey:2U]); + XCTAssertTrue([dict getUInt32:&value forKey:2U]); + XCTAssertEqual(value, 101U); + XCTAssertTrue([dict getUInt32:NULL forKey:3U]); + XCTAssertTrue([dict getUInt32:&value forKey:3U]); + XCTAssertEqual(value, 102U); + XCTAssertTrue([dict getUInt32:NULL forKey:4U]); + XCTAssertTrue([dict getUInt32:&value forKey:4U]); + XCTAssertEqual(value, 103U); + + [dict setUInt32:103U forKey:1U]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getUInt32:NULL forKey:1U]); + XCTAssertTrue([dict getUInt32:&value forKey:1U]); + XCTAssertEqual(value, 103U); + XCTAssertTrue([dict getUInt32:NULL forKey:2U]); + XCTAssertTrue([dict getUInt32:&value forKey:2U]); + XCTAssertEqual(value, 101U); + XCTAssertTrue([dict getUInt32:NULL forKey:3U]); + XCTAssertTrue([dict getUInt32:&value forKey:3U]); + XCTAssertEqual(value, 102U); + XCTAssertTrue([dict getUInt32:NULL forKey:4U]); + XCTAssertTrue([dict getUInt32:&value forKey:4U]); + XCTAssertEqual(value, 103U); + + [dict setUInt32:101U forKey:4U]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getUInt32:NULL forKey:1U]); + XCTAssertTrue([dict getUInt32:&value forKey:1U]); + XCTAssertEqual(value, 103U); + XCTAssertTrue([dict getUInt32:NULL forKey:2U]); + XCTAssertTrue([dict getUInt32:&value forKey:2U]); + XCTAssertEqual(value, 101U); + XCTAssertTrue([dict getUInt32:NULL forKey:3U]); + XCTAssertTrue([dict getUInt32:&value forKey:3U]); + XCTAssertEqual(value, 102U); + XCTAssertTrue([dict getUInt32:NULL forKey:4U]); + XCTAssertTrue([dict getUInt32:&value forKey:4U]); + XCTAssertEqual(value, 101U); + + const uint32_t kKeys2[] = { 2U, 3U }; + const uint32_t kValues2[] = { 102U, 100U }; + GPBUInt32UInt32Dictionary *dict2 = + [[GPBUInt32UInt32Dictionary alloc] initWithUInt32s:kValues2 + forKeys:kKeys2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(dict2); + [dict addEntriesFromDictionary:dict2]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getUInt32:NULL forKey:1U]); + XCTAssertTrue([dict getUInt32:&value forKey:1U]); + XCTAssertEqual(value, 103U); + XCTAssertTrue([dict getUInt32:NULL forKey:2U]); + XCTAssertTrue([dict getUInt32:&value forKey:2U]); + XCTAssertEqual(value, 102U); + XCTAssertTrue([dict getUInt32:NULL forKey:3U]); + XCTAssertTrue([dict getUInt32:&value forKey:3U]); + XCTAssertEqual(value, 100U); + XCTAssertTrue([dict getUInt32:NULL forKey:4U]); + XCTAssertTrue([dict getUInt32:&value forKey:4U]); + XCTAssertEqual(value, 101U); + + [dict2 release]; + [dict release]; +} + +@end + +#pragma mark - UInt32 -> Int32 + +@interface GPBUInt32Int32DictionaryTests : XCTestCase +@end + +@implementation GPBUInt32Int32DictionaryTests + +- (void)testEmpty { + GPBUInt32Int32Dictionary *dict = [[GPBUInt32Int32Dictionary alloc] init]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 0U); + XCTAssertFalse([dict getInt32:NULL forKey:1U]); + [dict enumerateKeysAndInt32sUsingBlock:^(uint32_t aKey, int32_t aValue, BOOL *stop) { + #pragma unused(aKey, aValue, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [dict release]; +} + +- (void)testOne { + GPBUInt32Int32Dictionary *dict = [[GPBUInt32Int32Dictionary alloc] init]; + [dict setInt32:200 forKey:1U]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 1U); + int32_t value; + XCTAssertTrue([dict getInt32:NULL forKey:1U]); + XCTAssertTrue([dict getInt32:&value forKey:1U]); + XCTAssertEqual(value, 200); + XCTAssertFalse([dict getInt32:NULL forKey:2U]); + [dict enumerateKeysAndInt32sUsingBlock:^(uint32_t aKey, int32_t aValue, BOOL *stop) { + XCTAssertEqual(aKey, 1U); + XCTAssertEqual(aValue, 200); + XCTAssertNotEqual(stop, NULL); + }]; + [dict release]; +} + +- (void)testBasics { + const uint32_t kKeys[] = { 1U, 2U, 3U }; + const int32_t kValues[] = { 200, 201, 202 }; + GPBUInt32Int32Dictionary *dict = + [[GPBUInt32Int32Dictionary alloc] initWithInt32s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 3U); + int32_t value; + XCTAssertTrue([dict getInt32:NULL forKey:1U]); + XCTAssertTrue([dict getInt32:&value forKey:1U]); + XCTAssertEqual(value, 200); + XCTAssertTrue([dict getInt32:NULL forKey:2U]); + XCTAssertTrue([dict getInt32:&value forKey:2U]); + XCTAssertEqual(value, 201); + XCTAssertTrue([dict getInt32:NULL forKey:3U]); + XCTAssertTrue([dict getInt32:&value forKey:3U]); + XCTAssertEqual(value, 202); + XCTAssertFalse([dict getInt32:NULL forKey:4U]); + + __block NSUInteger idx = 0; + uint32_t *seenKeys = malloc(3 * sizeof(uint32_t)); + int32_t *seenValues = malloc(3 * sizeof(int32_t)); + [dict enumerateKeysAndInt32sUsingBlock:^(uint32_t aKey, int32_t aValue, BOOL *stop) { + XCTAssertLessThan(idx, 3U); + seenKeys[idx] = aKey; + seenValues[idx] = aValue; + XCTAssertNotEqual(stop, NULL); + ++idx; + }]; + for (int i = 0; i < 3; ++i) { + BOOL foundKey = NO; + for (int j = 0; (j < 3) && !foundKey; ++j) { + if (kKeys[i] == seenKeys[j]) { + foundKey = YES; + XCTAssertEqual(kValues[i], seenValues[j], @"i = %d, j = %d", i, j); + } + } + XCTAssertTrue(foundKey, @"i = %d", i); + } + free(seenKeys); + free(seenValues); + + // Stopping the enumeration. + idx = 0; + [dict enumerateKeysAndInt32sUsingBlock:^(uint32_t aKey, int32_t aValue, BOOL *stop) { + #pragma unused(aKey, aValue) + if (idx == 1) *stop = YES; + XCTAssertNotEqual(idx, 2U); + ++idx; + }]; + [dict release]; +} + +- (void)testEquality { + const uint32_t kKeys1[] = { 1U, 2U, 3U, 4U }; + const uint32_t kKeys2[] = { 2U, 1U, 4U }; + const int32_t kValues1[] = { 200, 201, 202 }; + const int32_t kValues2[] = { 200, 203, 202 }; + const int32_t kValues3[] = { 200, 201, 202, 203 }; + GPBUInt32Int32Dictionary *dict1 = + [[GPBUInt32Int32Dictionary alloc] initWithInt32s:kValues1 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict1); + GPBUInt32Int32Dictionary *dict1prime = + [[GPBUInt32Int32Dictionary alloc] initWithInt32s:kValues1 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict1prime); + GPBUInt32Int32Dictionary *dict2 = + [[GPBUInt32Int32Dictionary alloc] initWithInt32s:kValues2 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(dict2); + GPBUInt32Int32Dictionary *dict3 = + [[GPBUInt32Int32Dictionary alloc] initWithInt32s:kValues1 + forKeys:kKeys2 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict3); + GPBUInt32Int32Dictionary *dict4 = + [[GPBUInt32Int32Dictionary alloc] initWithInt32s:kValues3 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues3)]; + XCTAssertNotNil(dict4); + + // 1/1Prime should be different objects, but equal. + XCTAssertNotEqual(dict1, dict1prime); + XCTAssertEqualObjects(dict1, dict1prime); + // Equal, so they must have same hash. + XCTAssertEqual([dict1 hash], [dict1prime hash]); + + // 2 is same keys, different values; not equal. + XCTAssertNotEqualObjects(dict1, dict2); + + // 3 is different keys, same values; not equal. + XCTAssertNotEqualObjects(dict1, dict3); + + // 4 extra pair; not equal + XCTAssertNotEqualObjects(dict1, dict4); + + [dict1 release]; + [dict1prime release]; + [dict2 release]; + [dict3 release]; + [dict4 release]; +} + +- (void)testCopy { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const int32_t kValues[] = { 200, 201, 202, 203 }; + GPBUInt32Int32Dictionary *dict = + [[GPBUInt32Int32Dictionary alloc] initWithInt32s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + + GPBUInt32Int32Dictionary *dict2 = [dict copy]; + XCTAssertNotNil(dict2); + + // Should be new object but equal. + XCTAssertNotEqual(dict, dict2); + XCTAssertEqualObjects(dict, dict2); + XCTAssertTrue([dict2 isKindOfClass:[GPBUInt32Int32Dictionary class]]); + + [dict2 release]; + [dict release]; +} + +- (void)testDictionaryFromDictionary { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const int32_t kValues[] = { 200, 201, 202, 203 }; + GPBUInt32Int32Dictionary *dict = + [[GPBUInt32Int32Dictionary alloc] initWithInt32s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + + GPBUInt32Int32Dictionary *dict2 = + [[GPBUInt32Int32Dictionary alloc] initWithDictionary:dict]; + XCTAssertNotNil(dict2); + + // Should be new pointer, but equal objects. + XCTAssertNotEqual(dict, dict2); + XCTAssertEqualObjects(dict, dict2); + [dict2 release]; + [dict release]; +} + +- (void)testAdds { + GPBUInt32Int32Dictionary *dict = [[GPBUInt32Int32Dictionary alloc] init]; + XCTAssertNotNil(dict); + + XCTAssertEqual(dict.count, 0U); + [dict setInt32:200 forKey:1U]; + XCTAssertEqual(dict.count, 1U); + + const uint32_t kKeys[] = { 2U, 3U, 4U }; + const int32_t kValues[] = { 201, 202, 203 }; + GPBUInt32Int32Dictionary *dict2 = + [[GPBUInt32Int32Dictionary alloc] initWithInt32s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict2); + [dict addEntriesFromDictionary:dict2]; + XCTAssertEqual(dict.count, 4U); + + int32_t value; + XCTAssertTrue([dict getInt32:NULL forKey:1U]); + XCTAssertTrue([dict getInt32:&value forKey:1U]); + XCTAssertEqual(value, 200); + XCTAssertTrue([dict getInt32:NULL forKey:2U]); + XCTAssertTrue([dict getInt32:&value forKey:2U]); + XCTAssertEqual(value, 201); + XCTAssertTrue([dict getInt32:NULL forKey:3U]); + XCTAssertTrue([dict getInt32:&value forKey:3U]); + XCTAssertEqual(value, 202); + XCTAssertTrue([dict getInt32:NULL forKey:4U]); + XCTAssertTrue([dict getInt32:&value forKey:4U]); + XCTAssertEqual(value, 203); + [dict2 release]; + [dict release]; +} + +- (void)testRemove { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const int32_t kValues[] = { 200, 201, 202, 203 }; + GPBUInt32Int32Dictionary *dict = + [[GPBUInt32Int32Dictionary alloc] initWithInt32s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 4U); + + [dict removeInt32ForKey:2U]; + XCTAssertEqual(dict.count, 3U); + int32_t value; + XCTAssertTrue([dict getInt32:NULL forKey:1U]); + XCTAssertTrue([dict getInt32:&value forKey:1U]); + XCTAssertEqual(value, 200); + XCTAssertFalse([dict getInt32:NULL forKey:2U]); + XCTAssertTrue([dict getInt32:NULL forKey:3U]); + XCTAssertTrue([dict getInt32:&value forKey:3U]); + XCTAssertEqual(value, 202); + XCTAssertTrue([dict getInt32:NULL forKey:4U]); + XCTAssertTrue([dict getInt32:&value forKey:4U]); + XCTAssertEqual(value, 203); + + // Remove again does nothing. + [dict removeInt32ForKey:2U]; + XCTAssertEqual(dict.count, 3U); + XCTAssertTrue([dict getInt32:NULL forKey:1U]); + XCTAssertTrue([dict getInt32:&value forKey:1U]); + XCTAssertEqual(value, 200); + XCTAssertFalse([dict getInt32:NULL forKey:2U]); + XCTAssertTrue([dict getInt32:NULL forKey:3U]); + XCTAssertTrue([dict getInt32:&value forKey:3U]); + XCTAssertEqual(value, 202); + XCTAssertTrue([dict getInt32:NULL forKey:4U]); + XCTAssertTrue([dict getInt32:&value forKey:4U]); + XCTAssertEqual(value, 203); + + [dict removeInt32ForKey:4U]; + XCTAssertEqual(dict.count, 2U); + XCTAssertTrue([dict getInt32:NULL forKey:1U]); + XCTAssertTrue([dict getInt32:&value forKey:1U]); + XCTAssertEqual(value, 200); + XCTAssertFalse([dict getInt32:NULL forKey:2U]); + XCTAssertTrue([dict getInt32:NULL forKey:3U]); + XCTAssertTrue([dict getInt32:&value forKey:3U]); + XCTAssertEqual(value, 202); + XCTAssertFalse([dict getInt32:NULL forKey:4U]); + + [dict removeAll]; + XCTAssertEqual(dict.count, 0U); + XCTAssertFalse([dict getInt32:NULL forKey:1U]); + XCTAssertFalse([dict getInt32:NULL forKey:2U]); + XCTAssertFalse([dict getInt32:NULL forKey:3U]); + XCTAssertFalse([dict getInt32:NULL forKey:4U]); + [dict release]; +} + +- (void)testInplaceMutation { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const int32_t kValues[] = { 200, 201, 202, 203 }; + GPBUInt32Int32Dictionary *dict = + [[GPBUInt32Int32Dictionary alloc] initWithInt32s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 4U); + int32_t value; + XCTAssertTrue([dict getInt32:NULL forKey:1U]); + XCTAssertTrue([dict getInt32:&value forKey:1U]); + XCTAssertEqual(value, 200); + XCTAssertTrue([dict getInt32:NULL forKey:2U]); + XCTAssertTrue([dict getInt32:&value forKey:2U]); + XCTAssertEqual(value, 201); + XCTAssertTrue([dict getInt32:NULL forKey:3U]); + XCTAssertTrue([dict getInt32:&value forKey:3U]); + XCTAssertEqual(value, 202); + XCTAssertTrue([dict getInt32:NULL forKey:4U]); + XCTAssertTrue([dict getInt32:&value forKey:4U]); + XCTAssertEqual(value, 203); + + [dict setInt32:203 forKey:1U]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getInt32:NULL forKey:1U]); + XCTAssertTrue([dict getInt32:&value forKey:1U]); + XCTAssertEqual(value, 203); + XCTAssertTrue([dict getInt32:NULL forKey:2U]); + XCTAssertTrue([dict getInt32:&value forKey:2U]); + XCTAssertEqual(value, 201); + XCTAssertTrue([dict getInt32:NULL forKey:3U]); + XCTAssertTrue([dict getInt32:&value forKey:3U]); + XCTAssertEqual(value, 202); + XCTAssertTrue([dict getInt32:NULL forKey:4U]); + XCTAssertTrue([dict getInt32:&value forKey:4U]); + XCTAssertEqual(value, 203); + + [dict setInt32:201 forKey:4U]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getInt32:NULL forKey:1U]); + XCTAssertTrue([dict getInt32:&value forKey:1U]); + XCTAssertEqual(value, 203); + XCTAssertTrue([dict getInt32:NULL forKey:2U]); + XCTAssertTrue([dict getInt32:&value forKey:2U]); + XCTAssertEqual(value, 201); + XCTAssertTrue([dict getInt32:NULL forKey:3U]); + XCTAssertTrue([dict getInt32:&value forKey:3U]); + XCTAssertEqual(value, 202); + XCTAssertTrue([dict getInt32:NULL forKey:4U]); + XCTAssertTrue([dict getInt32:&value forKey:4U]); + XCTAssertEqual(value, 201); + + const uint32_t kKeys2[] = { 2U, 3U }; + const int32_t kValues2[] = { 202, 200 }; + GPBUInt32Int32Dictionary *dict2 = + [[GPBUInt32Int32Dictionary alloc] initWithInt32s:kValues2 + forKeys:kKeys2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(dict2); + [dict addEntriesFromDictionary:dict2]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getInt32:NULL forKey:1U]); + XCTAssertTrue([dict getInt32:&value forKey:1U]); + XCTAssertEqual(value, 203); + XCTAssertTrue([dict getInt32:NULL forKey:2U]); + XCTAssertTrue([dict getInt32:&value forKey:2U]); + XCTAssertEqual(value, 202); + XCTAssertTrue([dict getInt32:NULL forKey:3U]); + XCTAssertTrue([dict getInt32:&value forKey:3U]); + XCTAssertEqual(value, 200); + XCTAssertTrue([dict getInt32:NULL forKey:4U]); + XCTAssertTrue([dict getInt32:&value forKey:4U]); + XCTAssertEqual(value, 201); + + [dict2 release]; + [dict release]; +} + +@end + +#pragma mark - UInt32 -> UInt64 + +@interface GPBUInt32UInt64DictionaryTests : XCTestCase +@end + +@implementation GPBUInt32UInt64DictionaryTests + +- (void)testEmpty { + GPBUInt32UInt64Dictionary *dict = [[GPBUInt32UInt64Dictionary alloc] init]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 0U); + XCTAssertFalse([dict getUInt64:NULL forKey:1U]); + [dict enumerateKeysAndUInt64sUsingBlock:^(uint32_t aKey, uint64_t aValue, BOOL *stop) { + #pragma unused(aKey, aValue, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [dict release]; +} + +- (void)testOne { + GPBUInt32UInt64Dictionary *dict = [[GPBUInt32UInt64Dictionary alloc] init]; + [dict setUInt64:300U forKey:1U]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 1U); + uint64_t value; + XCTAssertTrue([dict getUInt64:NULL forKey:1U]); + XCTAssertTrue([dict getUInt64:&value forKey:1U]); + XCTAssertEqual(value, 300U); + XCTAssertFalse([dict getUInt64:NULL forKey:2U]); + [dict enumerateKeysAndUInt64sUsingBlock:^(uint32_t aKey, uint64_t aValue, BOOL *stop) { + XCTAssertEqual(aKey, 1U); + XCTAssertEqual(aValue, 300U); + XCTAssertNotEqual(stop, NULL); + }]; + [dict release]; +} + +- (void)testBasics { + const uint32_t kKeys[] = { 1U, 2U, 3U }; + const uint64_t kValues[] = { 300U, 301U, 302U }; + GPBUInt32UInt64Dictionary *dict = + [[GPBUInt32UInt64Dictionary alloc] initWithUInt64s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 3U); + uint64_t value; + XCTAssertTrue([dict getUInt64:NULL forKey:1U]); + XCTAssertTrue([dict getUInt64:&value forKey:1U]); + XCTAssertEqual(value, 300U); + XCTAssertTrue([dict getUInt64:NULL forKey:2U]); + XCTAssertTrue([dict getUInt64:&value forKey:2U]); + XCTAssertEqual(value, 301U); + XCTAssertTrue([dict getUInt64:NULL forKey:3U]); + XCTAssertTrue([dict getUInt64:&value forKey:3U]); + XCTAssertEqual(value, 302U); + XCTAssertFalse([dict getUInt64:NULL forKey:4U]); + + __block NSUInteger idx = 0; + uint32_t *seenKeys = malloc(3 * sizeof(uint32_t)); + uint64_t *seenValues = malloc(3 * sizeof(uint64_t)); + [dict enumerateKeysAndUInt64sUsingBlock:^(uint32_t aKey, uint64_t aValue, BOOL *stop) { + XCTAssertLessThan(idx, 3U); + seenKeys[idx] = aKey; + seenValues[idx] = aValue; + XCTAssertNotEqual(stop, NULL); + ++idx; + }]; + for (int i = 0; i < 3; ++i) { + BOOL foundKey = NO; + for (int j = 0; (j < 3) && !foundKey; ++j) { + if (kKeys[i] == seenKeys[j]) { + foundKey = YES; + XCTAssertEqual(kValues[i], seenValues[j], @"i = %d, j = %d", i, j); + } + } + XCTAssertTrue(foundKey, @"i = %d", i); + } + free(seenKeys); + free(seenValues); + + // Stopping the enumeration. + idx = 0; + [dict enumerateKeysAndUInt64sUsingBlock:^(uint32_t aKey, uint64_t aValue, BOOL *stop) { + #pragma unused(aKey, aValue) + if (idx == 1) *stop = YES; + XCTAssertNotEqual(idx, 2U); + ++idx; + }]; + [dict release]; +} + +- (void)testEquality { + const uint32_t kKeys1[] = { 1U, 2U, 3U, 4U }; + const uint32_t kKeys2[] = { 2U, 1U, 4U }; + const uint64_t kValues1[] = { 300U, 301U, 302U }; + const uint64_t kValues2[] = { 300U, 303U, 302U }; + const uint64_t kValues3[] = { 300U, 301U, 302U, 303U }; + GPBUInt32UInt64Dictionary *dict1 = + [[GPBUInt32UInt64Dictionary alloc] initWithUInt64s:kValues1 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict1); + GPBUInt32UInt64Dictionary *dict1prime = + [[GPBUInt32UInt64Dictionary alloc] initWithUInt64s:kValues1 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict1prime); + GPBUInt32UInt64Dictionary *dict2 = + [[GPBUInt32UInt64Dictionary alloc] initWithUInt64s:kValues2 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(dict2); + GPBUInt32UInt64Dictionary *dict3 = + [[GPBUInt32UInt64Dictionary alloc] initWithUInt64s:kValues1 + forKeys:kKeys2 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict3); + GPBUInt32UInt64Dictionary *dict4 = + [[GPBUInt32UInt64Dictionary alloc] initWithUInt64s:kValues3 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues3)]; + XCTAssertNotNil(dict4); + + // 1/1Prime should be different objects, but equal. + XCTAssertNotEqual(dict1, dict1prime); + XCTAssertEqualObjects(dict1, dict1prime); + // Equal, so they must have same hash. + XCTAssertEqual([dict1 hash], [dict1prime hash]); + + // 2 is same keys, different values; not equal. + XCTAssertNotEqualObjects(dict1, dict2); + + // 3 is different keys, same values; not equal. + XCTAssertNotEqualObjects(dict1, dict3); + + // 4 extra pair; not equal + XCTAssertNotEqualObjects(dict1, dict4); + + [dict1 release]; + [dict1prime release]; + [dict2 release]; + [dict3 release]; + [dict4 release]; +} + +- (void)testCopy { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const uint64_t kValues[] = { 300U, 301U, 302U, 303U }; + GPBUInt32UInt64Dictionary *dict = + [[GPBUInt32UInt64Dictionary alloc] initWithUInt64s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + + GPBUInt32UInt64Dictionary *dict2 = [dict copy]; + XCTAssertNotNil(dict2); + + // Should be new object but equal. + XCTAssertNotEqual(dict, dict2); + XCTAssertEqualObjects(dict, dict2); + XCTAssertTrue([dict2 isKindOfClass:[GPBUInt32UInt64Dictionary class]]); + + [dict2 release]; + [dict release]; +} + +- (void)testDictionaryFromDictionary { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const uint64_t kValues[] = { 300U, 301U, 302U, 303U }; + GPBUInt32UInt64Dictionary *dict = + [[GPBUInt32UInt64Dictionary alloc] initWithUInt64s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + + GPBUInt32UInt64Dictionary *dict2 = + [[GPBUInt32UInt64Dictionary alloc] initWithDictionary:dict]; + XCTAssertNotNil(dict2); + + // Should be new pointer, but equal objects. + XCTAssertNotEqual(dict, dict2); + XCTAssertEqualObjects(dict, dict2); + [dict2 release]; + [dict release]; +} + +- (void)testAdds { + GPBUInt32UInt64Dictionary *dict = [[GPBUInt32UInt64Dictionary alloc] init]; + XCTAssertNotNil(dict); + + XCTAssertEqual(dict.count, 0U); + [dict setUInt64:300U forKey:1U]; + XCTAssertEqual(dict.count, 1U); + + const uint32_t kKeys[] = { 2U, 3U, 4U }; + const uint64_t kValues[] = { 301U, 302U, 303U }; + GPBUInt32UInt64Dictionary *dict2 = + [[GPBUInt32UInt64Dictionary alloc] initWithUInt64s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict2); + [dict addEntriesFromDictionary:dict2]; + XCTAssertEqual(dict.count, 4U); + + uint64_t value; + XCTAssertTrue([dict getUInt64:NULL forKey:1U]); + XCTAssertTrue([dict getUInt64:&value forKey:1U]); + XCTAssertEqual(value, 300U); + XCTAssertTrue([dict getUInt64:NULL forKey:2U]); + XCTAssertTrue([dict getUInt64:&value forKey:2U]); + XCTAssertEqual(value, 301U); + XCTAssertTrue([dict getUInt64:NULL forKey:3U]); + XCTAssertTrue([dict getUInt64:&value forKey:3U]); + XCTAssertEqual(value, 302U); + XCTAssertTrue([dict getUInt64:NULL forKey:4U]); + XCTAssertTrue([dict getUInt64:&value forKey:4U]); + XCTAssertEqual(value, 303U); + [dict2 release]; + [dict release]; +} + +- (void)testRemove { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const uint64_t kValues[] = { 300U, 301U, 302U, 303U }; + GPBUInt32UInt64Dictionary *dict = + [[GPBUInt32UInt64Dictionary alloc] initWithUInt64s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 4U); + + [dict removeUInt64ForKey:2U]; + XCTAssertEqual(dict.count, 3U); + uint64_t value; + XCTAssertTrue([dict getUInt64:NULL forKey:1U]); + XCTAssertTrue([dict getUInt64:&value forKey:1U]); + XCTAssertEqual(value, 300U); + XCTAssertFalse([dict getUInt64:NULL forKey:2U]); + XCTAssertTrue([dict getUInt64:NULL forKey:3U]); + XCTAssertTrue([dict getUInt64:&value forKey:3U]); + XCTAssertEqual(value, 302U); + XCTAssertTrue([dict getUInt64:NULL forKey:4U]); + XCTAssertTrue([dict getUInt64:&value forKey:4U]); + XCTAssertEqual(value, 303U); + + // Remove again does nothing. + [dict removeUInt64ForKey:2U]; + XCTAssertEqual(dict.count, 3U); + XCTAssertTrue([dict getUInt64:NULL forKey:1U]); + XCTAssertTrue([dict getUInt64:&value forKey:1U]); + XCTAssertEqual(value, 300U); + XCTAssertFalse([dict getUInt64:NULL forKey:2U]); + XCTAssertTrue([dict getUInt64:NULL forKey:3U]); + XCTAssertTrue([dict getUInt64:&value forKey:3U]); + XCTAssertEqual(value, 302U); + XCTAssertTrue([dict getUInt64:NULL forKey:4U]); + XCTAssertTrue([dict getUInt64:&value forKey:4U]); + XCTAssertEqual(value, 303U); + + [dict removeUInt64ForKey:4U]; + XCTAssertEqual(dict.count, 2U); + XCTAssertTrue([dict getUInt64:NULL forKey:1U]); + XCTAssertTrue([dict getUInt64:&value forKey:1U]); + XCTAssertEqual(value, 300U); + XCTAssertFalse([dict getUInt64:NULL forKey:2U]); + XCTAssertTrue([dict getUInt64:NULL forKey:3U]); + XCTAssertTrue([dict getUInt64:&value forKey:3U]); + XCTAssertEqual(value, 302U); + XCTAssertFalse([dict getUInt64:NULL forKey:4U]); + + [dict removeAll]; + XCTAssertEqual(dict.count, 0U); + XCTAssertFalse([dict getUInt64:NULL forKey:1U]); + XCTAssertFalse([dict getUInt64:NULL forKey:2U]); + XCTAssertFalse([dict getUInt64:NULL forKey:3U]); + XCTAssertFalse([dict getUInt64:NULL forKey:4U]); + [dict release]; +} + +- (void)testInplaceMutation { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const uint64_t kValues[] = { 300U, 301U, 302U, 303U }; + GPBUInt32UInt64Dictionary *dict = + [[GPBUInt32UInt64Dictionary alloc] initWithUInt64s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 4U); + uint64_t value; + XCTAssertTrue([dict getUInt64:NULL forKey:1U]); + XCTAssertTrue([dict getUInt64:&value forKey:1U]); + XCTAssertEqual(value, 300U); + XCTAssertTrue([dict getUInt64:NULL forKey:2U]); + XCTAssertTrue([dict getUInt64:&value forKey:2U]); + XCTAssertEqual(value, 301U); + XCTAssertTrue([dict getUInt64:NULL forKey:3U]); + XCTAssertTrue([dict getUInt64:&value forKey:3U]); + XCTAssertEqual(value, 302U); + XCTAssertTrue([dict getUInt64:NULL forKey:4U]); + XCTAssertTrue([dict getUInt64:&value forKey:4U]); + XCTAssertEqual(value, 303U); + + [dict setUInt64:303U forKey:1U]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getUInt64:NULL forKey:1U]); + XCTAssertTrue([dict getUInt64:&value forKey:1U]); + XCTAssertEqual(value, 303U); + XCTAssertTrue([dict getUInt64:NULL forKey:2U]); + XCTAssertTrue([dict getUInt64:&value forKey:2U]); + XCTAssertEqual(value, 301U); + XCTAssertTrue([dict getUInt64:NULL forKey:3U]); + XCTAssertTrue([dict getUInt64:&value forKey:3U]); + XCTAssertEqual(value, 302U); + XCTAssertTrue([dict getUInt64:NULL forKey:4U]); + XCTAssertTrue([dict getUInt64:&value forKey:4U]); + XCTAssertEqual(value, 303U); + + [dict setUInt64:301U forKey:4U]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getUInt64:NULL forKey:1U]); + XCTAssertTrue([dict getUInt64:&value forKey:1U]); + XCTAssertEqual(value, 303U); + XCTAssertTrue([dict getUInt64:NULL forKey:2U]); + XCTAssertTrue([dict getUInt64:&value forKey:2U]); + XCTAssertEqual(value, 301U); + XCTAssertTrue([dict getUInt64:NULL forKey:3U]); + XCTAssertTrue([dict getUInt64:&value forKey:3U]); + XCTAssertEqual(value, 302U); + XCTAssertTrue([dict getUInt64:NULL forKey:4U]); + XCTAssertTrue([dict getUInt64:&value forKey:4U]); + XCTAssertEqual(value, 301U); + + const uint32_t kKeys2[] = { 2U, 3U }; + const uint64_t kValues2[] = { 302U, 300U }; + GPBUInt32UInt64Dictionary *dict2 = + [[GPBUInt32UInt64Dictionary alloc] initWithUInt64s:kValues2 + forKeys:kKeys2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(dict2); + [dict addEntriesFromDictionary:dict2]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getUInt64:NULL forKey:1U]); + XCTAssertTrue([dict getUInt64:&value forKey:1U]); + XCTAssertEqual(value, 303U); + XCTAssertTrue([dict getUInt64:NULL forKey:2U]); + XCTAssertTrue([dict getUInt64:&value forKey:2U]); + XCTAssertEqual(value, 302U); + XCTAssertTrue([dict getUInt64:NULL forKey:3U]); + XCTAssertTrue([dict getUInt64:&value forKey:3U]); + XCTAssertEqual(value, 300U); + XCTAssertTrue([dict getUInt64:NULL forKey:4U]); + XCTAssertTrue([dict getUInt64:&value forKey:4U]); + XCTAssertEqual(value, 301U); + + [dict2 release]; + [dict release]; +} + +@end + +#pragma mark - UInt32 -> Int64 + +@interface GPBUInt32Int64DictionaryTests : XCTestCase +@end + +@implementation GPBUInt32Int64DictionaryTests + +- (void)testEmpty { + GPBUInt32Int64Dictionary *dict = [[GPBUInt32Int64Dictionary alloc] init]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 0U); + XCTAssertFalse([dict getInt64:NULL forKey:1U]); + [dict enumerateKeysAndInt64sUsingBlock:^(uint32_t aKey, int64_t aValue, BOOL *stop) { + #pragma unused(aKey, aValue, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [dict release]; +} + +- (void)testOne { + GPBUInt32Int64Dictionary *dict = [[GPBUInt32Int64Dictionary alloc] init]; + [dict setInt64:400 forKey:1U]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 1U); + int64_t value; + XCTAssertTrue([dict getInt64:NULL forKey:1U]); + XCTAssertTrue([dict getInt64:&value forKey:1U]); + XCTAssertEqual(value, 400); + XCTAssertFalse([dict getInt64:NULL forKey:2U]); + [dict enumerateKeysAndInt64sUsingBlock:^(uint32_t aKey, int64_t aValue, BOOL *stop) { + XCTAssertEqual(aKey, 1U); + XCTAssertEqual(aValue, 400); + XCTAssertNotEqual(stop, NULL); + }]; + [dict release]; +} + +- (void)testBasics { + const uint32_t kKeys[] = { 1U, 2U, 3U }; + const int64_t kValues[] = { 400, 401, 402 }; + GPBUInt32Int64Dictionary *dict = + [[GPBUInt32Int64Dictionary alloc] initWithInt64s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 3U); + int64_t value; + XCTAssertTrue([dict getInt64:NULL forKey:1U]); + XCTAssertTrue([dict getInt64:&value forKey:1U]); + XCTAssertEqual(value, 400); + XCTAssertTrue([dict getInt64:NULL forKey:2U]); + XCTAssertTrue([dict getInt64:&value forKey:2U]); + XCTAssertEqual(value, 401); + XCTAssertTrue([dict getInt64:NULL forKey:3U]); + XCTAssertTrue([dict getInt64:&value forKey:3U]); + XCTAssertEqual(value, 402); + XCTAssertFalse([dict getInt64:NULL forKey:4U]); + + __block NSUInteger idx = 0; + uint32_t *seenKeys = malloc(3 * sizeof(uint32_t)); + int64_t *seenValues = malloc(3 * sizeof(int64_t)); + [dict enumerateKeysAndInt64sUsingBlock:^(uint32_t aKey, int64_t aValue, BOOL *stop) { + XCTAssertLessThan(idx, 3U); + seenKeys[idx] = aKey; + seenValues[idx] = aValue; + XCTAssertNotEqual(stop, NULL); + ++idx; + }]; + for (int i = 0; i < 3; ++i) { + BOOL foundKey = NO; + for (int j = 0; (j < 3) && !foundKey; ++j) { + if (kKeys[i] == seenKeys[j]) { + foundKey = YES; + XCTAssertEqual(kValues[i], seenValues[j], @"i = %d, j = %d", i, j); + } + } + XCTAssertTrue(foundKey, @"i = %d", i); + } + free(seenKeys); + free(seenValues); + + // Stopping the enumeration. + idx = 0; + [dict enumerateKeysAndInt64sUsingBlock:^(uint32_t aKey, int64_t aValue, BOOL *stop) { + #pragma unused(aKey, aValue) + if (idx == 1) *stop = YES; + XCTAssertNotEqual(idx, 2U); + ++idx; + }]; + [dict release]; +} + +- (void)testEquality { + const uint32_t kKeys1[] = { 1U, 2U, 3U, 4U }; + const uint32_t kKeys2[] = { 2U, 1U, 4U }; + const int64_t kValues1[] = { 400, 401, 402 }; + const int64_t kValues2[] = { 400, 403, 402 }; + const int64_t kValues3[] = { 400, 401, 402, 403 }; + GPBUInt32Int64Dictionary *dict1 = + [[GPBUInt32Int64Dictionary alloc] initWithInt64s:kValues1 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict1); + GPBUInt32Int64Dictionary *dict1prime = + [[GPBUInt32Int64Dictionary alloc] initWithInt64s:kValues1 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict1prime); + GPBUInt32Int64Dictionary *dict2 = + [[GPBUInt32Int64Dictionary alloc] initWithInt64s:kValues2 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(dict2); + GPBUInt32Int64Dictionary *dict3 = + [[GPBUInt32Int64Dictionary alloc] initWithInt64s:kValues1 + forKeys:kKeys2 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict3); + GPBUInt32Int64Dictionary *dict4 = + [[GPBUInt32Int64Dictionary alloc] initWithInt64s:kValues3 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues3)]; + XCTAssertNotNil(dict4); + + // 1/1Prime should be different objects, but equal. + XCTAssertNotEqual(dict1, dict1prime); + XCTAssertEqualObjects(dict1, dict1prime); + // Equal, so they must have same hash. + XCTAssertEqual([dict1 hash], [dict1prime hash]); + + // 2 is same keys, different values; not equal. + XCTAssertNotEqualObjects(dict1, dict2); + + // 3 is different keys, same values; not equal. + XCTAssertNotEqualObjects(dict1, dict3); + + // 4 extra pair; not equal + XCTAssertNotEqualObjects(dict1, dict4); + + [dict1 release]; + [dict1prime release]; + [dict2 release]; + [dict3 release]; + [dict4 release]; +} + +- (void)testCopy { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const int64_t kValues[] = { 400, 401, 402, 403 }; + GPBUInt32Int64Dictionary *dict = + [[GPBUInt32Int64Dictionary alloc] initWithInt64s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + + GPBUInt32Int64Dictionary *dict2 = [dict copy]; + XCTAssertNotNil(dict2); + + // Should be new object but equal. + XCTAssertNotEqual(dict, dict2); + XCTAssertEqualObjects(dict, dict2); + XCTAssertTrue([dict2 isKindOfClass:[GPBUInt32Int64Dictionary class]]); + + [dict2 release]; + [dict release]; +} + +- (void)testDictionaryFromDictionary { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const int64_t kValues[] = { 400, 401, 402, 403 }; + GPBUInt32Int64Dictionary *dict = + [[GPBUInt32Int64Dictionary alloc] initWithInt64s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + + GPBUInt32Int64Dictionary *dict2 = + [[GPBUInt32Int64Dictionary alloc] initWithDictionary:dict]; + XCTAssertNotNil(dict2); + + // Should be new pointer, but equal objects. + XCTAssertNotEqual(dict, dict2); + XCTAssertEqualObjects(dict, dict2); + [dict2 release]; + [dict release]; +} + +- (void)testAdds { + GPBUInt32Int64Dictionary *dict = [[GPBUInt32Int64Dictionary alloc] init]; + XCTAssertNotNil(dict); + + XCTAssertEqual(dict.count, 0U); + [dict setInt64:400 forKey:1U]; + XCTAssertEqual(dict.count, 1U); + + const uint32_t kKeys[] = { 2U, 3U, 4U }; + const int64_t kValues[] = { 401, 402, 403 }; + GPBUInt32Int64Dictionary *dict2 = + [[GPBUInt32Int64Dictionary alloc] initWithInt64s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict2); + [dict addEntriesFromDictionary:dict2]; + XCTAssertEqual(dict.count, 4U); + + int64_t value; + XCTAssertTrue([dict getInt64:NULL forKey:1U]); + XCTAssertTrue([dict getInt64:&value forKey:1U]); + XCTAssertEqual(value, 400); + XCTAssertTrue([dict getInt64:NULL forKey:2U]); + XCTAssertTrue([dict getInt64:&value forKey:2U]); + XCTAssertEqual(value, 401); + XCTAssertTrue([dict getInt64:NULL forKey:3U]); + XCTAssertTrue([dict getInt64:&value forKey:3U]); + XCTAssertEqual(value, 402); + XCTAssertTrue([dict getInt64:NULL forKey:4U]); + XCTAssertTrue([dict getInt64:&value forKey:4U]); + XCTAssertEqual(value, 403); + [dict2 release]; + [dict release]; +} + +- (void)testRemove { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const int64_t kValues[] = { 400, 401, 402, 403 }; + GPBUInt32Int64Dictionary *dict = + [[GPBUInt32Int64Dictionary alloc] initWithInt64s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 4U); + + [dict removeInt64ForKey:2U]; + XCTAssertEqual(dict.count, 3U); + int64_t value; + XCTAssertTrue([dict getInt64:NULL forKey:1U]); + XCTAssertTrue([dict getInt64:&value forKey:1U]); + XCTAssertEqual(value, 400); + XCTAssertFalse([dict getInt64:NULL forKey:2U]); + XCTAssertTrue([dict getInt64:NULL forKey:3U]); + XCTAssertTrue([dict getInt64:&value forKey:3U]); + XCTAssertEqual(value, 402); + XCTAssertTrue([dict getInt64:NULL forKey:4U]); + XCTAssertTrue([dict getInt64:&value forKey:4U]); + XCTAssertEqual(value, 403); + + // Remove again does nothing. + [dict removeInt64ForKey:2U]; + XCTAssertEqual(dict.count, 3U); + XCTAssertTrue([dict getInt64:NULL forKey:1U]); + XCTAssertTrue([dict getInt64:&value forKey:1U]); + XCTAssertEqual(value, 400); + XCTAssertFalse([dict getInt64:NULL forKey:2U]); + XCTAssertTrue([dict getInt64:NULL forKey:3U]); + XCTAssertTrue([dict getInt64:&value forKey:3U]); + XCTAssertEqual(value, 402); + XCTAssertTrue([dict getInt64:NULL forKey:4U]); + XCTAssertTrue([dict getInt64:&value forKey:4U]); + XCTAssertEqual(value, 403); + + [dict removeInt64ForKey:4U]; + XCTAssertEqual(dict.count, 2U); + XCTAssertTrue([dict getInt64:NULL forKey:1U]); + XCTAssertTrue([dict getInt64:&value forKey:1U]); + XCTAssertEqual(value, 400); + XCTAssertFalse([dict getInt64:NULL forKey:2U]); + XCTAssertTrue([dict getInt64:NULL forKey:3U]); + XCTAssertTrue([dict getInt64:&value forKey:3U]); + XCTAssertEqual(value, 402); + XCTAssertFalse([dict getInt64:NULL forKey:4U]); + + [dict removeAll]; + XCTAssertEqual(dict.count, 0U); + XCTAssertFalse([dict getInt64:NULL forKey:1U]); + XCTAssertFalse([dict getInt64:NULL forKey:2U]); + XCTAssertFalse([dict getInt64:NULL forKey:3U]); + XCTAssertFalse([dict getInt64:NULL forKey:4U]); + [dict release]; +} + +- (void)testInplaceMutation { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const int64_t kValues[] = { 400, 401, 402, 403 }; + GPBUInt32Int64Dictionary *dict = + [[GPBUInt32Int64Dictionary alloc] initWithInt64s:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 4U); + int64_t value; + XCTAssertTrue([dict getInt64:NULL forKey:1U]); + XCTAssertTrue([dict getInt64:&value forKey:1U]); + XCTAssertEqual(value, 400); + XCTAssertTrue([dict getInt64:NULL forKey:2U]); + XCTAssertTrue([dict getInt64:&value forKey:2U]); + XCTAssertEqual(value, 401); + XCTAssertTrue([dict getInt64:NULL forKey:3U]); + XCTAssertTrue([dict getInt64:&value forKey:3U]); + XCTAssertEqual(value, 402); + XCTAssertTrue([dict getInt64:NULL forKey:4U]); + XCTAssertTrue([dict getInt64:&value forKey:4U]); + XCTAssertEqual(value, 403); + + [dict setInt64:403 forKey:1U]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getInt64:NULL forKey:1U]); + XCTAssertTrue([dict getInt64:&value forKey:1U]); + XCTAssertEqual(value, 403); + XCTAssertTrue([dict getInt64:NULL forKey:2U]); + XCTAssertTrue([dict getInt64:&value forKey:2U]); + XCTAssertEqual(value, 401); + XCTAssertTrue([dict getInt64:NULL forKey:3U]); + XCTAssertTrue([dict getInt64:&value forKey:3U]); + XCTAssertEqual(value, 402); + XCTAssertTrue([dict getInt64:NULL forKey:4U]); + XCTAssertTrue([dict getInt64:&value forKey:4U]); + XCTAssertEqual(value, 403); + + [dict setInt64:401 forKey:4U]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getInt64:NULL forKey:1U]); + XCTAssertTrue([dict getInt64:&value forKey:1U]); + XCTAssertEqual(value, 403); + XCTAssertTrue([dict getInt64:NULL forKey:2U]); + XCTAssertTrue([dict getInt64:&value forKey:2U]); + XCTAssertEqual(value, 401); + XCTAssertTrue([dict getInt64:NULL forKey:3U]); + XCTAssertTrue([dict getInt64:&value forKey:3U]); + XCTAssertEqual(value, 402); + XCTAssertTrue([dict getInt64:NULL forKey:4U]); + XCTAssertTrue([dict getInt64:&value forKey:4U]); + XCTAssertEqual(value, 401); + + const uint32_t kKeys2[] = { 2U, 3U }; + const int64_t kValues2[] = { 402, 400 }; + GPBUInt32Int64Dictionary *dict2 = + [[GPBUInt32Int64Dictionary alloc] initWithInt64s:kValues2 + forKeys:kKeys2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(dict2); + [dict addEntriesFromDictionary:dict2]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getInt64:NULL forKey:1U]); + XCTAssertTrue([dict getInt64:&value forKey:1U]); + XCTAssertEqual(value, 403); + XCTAssertTrue([dict getInt64:NULL forKey:2U]); + XCTAssertTrue([dict getInt64:&value forKey:2U]); + XCTAssertEqual(value, 402); + XCTAssertTrue([dict getInt64:NULL forKey:3U]); + XCTAssertTrue([dict getInt64:&value forKey:3U]); + XCTAssertEqual(value, 400); + XCTAssertTrue([dict getInt64:NULL forKey:4U]); + XCTAssertTrue([dict getInt64:&value forKey:4U]); + XCTAssertEqual(value, 401); + + [dict2 release]; + [dict release]; +} + +@end + +#pragma mark - UInt32 -> Bool + +@interface GPBUInt32BoolDictionaryTests : XCTestCase +@end + +@implementation GPBUInt32BoolDictionaryTests + +- (void)testEmpty { + GPBUInt32BoolDictionary *dict = [[GPBUInt32BoolDictionary alloc] init]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 0U); + XCTAssertFalse([dict getBool:NULL forKey:1U]); + [dict enumerateKeysAndBoolsUsingBlock:^(uint32_t aKey, BOOL aValue, BOOL *stop) { + #pragma unused(aKey, aValue, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [dict release]; +} + +- (void)testOne { + GPBUInt32BoolDictionary *dict = [[GPBUInt32BoolDictionary alloc] init]; + [dict setBool:YES forKey:1U]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 1U); + BOOL value; + XCTAssertTrue([dict getBool:NULL forKey:1U]); + XCTAssertTrue([dict getBool:&value forKey:1U]); + XCTAssertEqual(value, YES); + XCTAssertFalse([dict getBool:NULL forKey:2U]); + [dict enumerateKeysAndBoolsUsingBlock:^(uint32_t aKey, BOOL aValue, BOOL *stop) { + XCTAssertEqual(aKey, 1U); + XCTAssertEqual(aValue, YES); + XCTAssertNotEqual(stop, NULL); + }]; + [dict release]; +} + +- (void)testBasics { + const uint32_t kKeys[] = { 1U, 2U, 3U }; + const BOOL kValues[] = { YES, YES, NO }; + GPBUInt32BoolDictionary *dict = + [[GPBUInt32BoolDictionary alloc] initWithBools:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 3U); + BOOL value; + XCTAssertTrue([dict getBool:NULL forKey:1U]); + XCTAssertTrue([dict getBool:&value forKey:1U]); + XCTAssertEqual(value, YES); + XCTAssertTrue([dict getBool:NULL forKey:2U]); + XCTAssertTrue([dict getBool:&value forKey:2U]); + XCTAssertEqual(value, YES); + XCTAssertTrue([dict getBool:NULL forKey:3U]); + XCTAssertTrue([dict getBool:&value forKey:3U]); + XCTAssertEqual(value, NO); + XCTAssertFalse([dict getBool:NULL forKey:4U]); + + __block NSUInteger idx = 0; + uint32_t *seenKeys = malloc(3 * sizeof(uint32_t)); + BOOL *seenValues = malloc(3 * sizeof(BOOL)); + [dict enumerateKeysAndBoolsUsingBlock:^(uint32_t aKey, BOOL aValue, BOOL *stop) { + XCTAssertLessThan(idx, 3U); + seenKeys[idx] = aKey; + seenValues[idx] = aValue; + XCTAssertNotEqual(stop, NULL); + ++idx; + }]; + for (int i = 0; i < 3; ++i) { + BOOL foundKey = NO; + for (int j = 0; (j < 3) && !foundKey; ++j) { + if (kKeys[i] == seenKeys[j]) { + foundKey = YES; + XCTAssertEqual(kValues[i], seenValues[j], @"i = %d, j = %d", i, j); + } + } + XCTAssertTrue(foundKey, @"i = %d", i); + } + free(seenKeys); + free(seenValues); + + // Stopping the enumeration. + idx = 0; + [dict enumerateKeysAndBoolsUsingBlock:^(uint32_t aKey, BOOL aValue, BOOL *stop) { + #pragma unused(aKey, aValue) + if (idx == 1) *stop = YES; + XCTAssertNotEqual(idx, 2U); + ++idx; + }]; + [dict release]; +} + +- (void)testEquality { + const uint32_t kKeys1[] = { 1U, 2U, 3U, 4U }; + const uint32_t kKeys2[] = { 2U, 1U, 4U }; + const BOOL kValues1[] = { YES, YES, NO }; + const BOOL kValues2[] = { YES, NO, NO }; + const BOOL kValues3[] = { YES, YES, NO, NO }; + GPBUInt32BoolDictionary *dict1 = + [[GPBUInt32BoolDictionary alloc] initWithBools:kValues1 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict1); + GPBUInt32BoolDictionary *dict1prime = + [[GPBUInt32BoolDictionary alloc] initWithBools:kValues1 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict1prime); + GPBUInt32BoolDictionary *dict2 = + [[GPBUInt32BoolDictionary alloc] initWithBools:kValues2 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(dict2); + GPBUInt32BoolDictionary *dict3 = + [[GPBUInt32BoolDictionary alloc] initWithBools:kValues1 + forKeys:kKeys2 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict3); + GPBUInt32BoolDictionary *dict4 = + [[GPBUInt32BoolDictionary alloc] initWithBools:kValues3 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues3)]; + XCTAssertNotNil(dict4); + + // 1/1Prime should be different objects, but equal. + XCTAssertNotEqual(dict1, dict1prime); + XCTAssertEqualObjects(dict1, dict1prime); + // Equal, so they must have same hash. + XCTAssertEqual([dict1 hash], [dict1prime hash]); + + // 2 is same keys, different values; not equal. + XCTAssertNotEqualObjects(dict1, dict2); + + // 3 is different keys, same values; not equal. + XCTAssertNotEqualObjects(dict1, dict3); + + // 4 extra pair; not equal + XCTAssertNotEqualObjects(dict1, dict4); + + [dict1 release]; + [dict1prime release]; + [dict2 release]; + [dict3 release]; + [dict4 release]; +} + +- (void)testCopy { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const BOOL kValues[] = { YES, YES, NO, NO }; + GPBUInt32BoolDictionary *dict = + [[GPBUInt32BoolDictionary alloc] initWithBools:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + + GPBUInt32BoolDictionary *dict2 = [dict copy]; + XCTAssertNotNil(dict2); + + // Should be new object but equal. + XCTAssertNotEqual(dict, dict2); + XCTAssertEqualObjects(dict, dict2); + XCTAssertTrue([dict2 isKindOfClass:[GPBUInt32BoolDictionary class]]); + + [dict2 release]; + [dict release]; +} + +- (void)testDictionaryFromDictionary { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const BOOL kValues[] = { YES, YES, NO, NO }; + GPBUInt32BoolDictionary *dict = + [[GPBUInt32BoolDictionary alloc] initWithBools:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + + GPBUInt32BoolDictionary *dict2 = + [[GPBUInt32BoolDictionary alloc] initWithDictionary:dict]; + XCTAssertNotNil(dict2); + + // Should be new pointer, but equal objects. + XCTAssertNotEqual(dict, dict2); + XCTAssertEqualObjects(dict, dict2); + [dict2 release]; + [dict release]; +} + +- (void)testAdds { + GPBUInt32BoolDictionary *dict = [[GPBUInt32BoolDictionary alloc] init]; + XCTAssertNotNil(dict); + + XCTAssertEqual(dict.count, 0U); + [dict setBool:YES forKey:1U]; + XCTAssertEqual(dict.count, 1U); + + const uint32_t kKeys[] = { 2U, 3U, 4U }; + const BOOL kValues[] = { YES, NO, NO }; + GPBUInt32BoolDictionary *dict2 = + [[GPBUInt32BoolDictionary alloc] initWithBools:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict2); + [dict addEntriesFromDictionary:dict2]; + XCTAssertEqual(dict.count, 4U); + + BOOL value; + XCTAssertTrue([dict getBool:NULL forKey:1U]); + XCTAssertTrue([dict getBool:&value forKey:1U]); + XCTAssertEqual(value, YES); + XCTAssertTrue([dict getBool:NULL forKey:2U]); + XCTAssertTrue([dict getBool:&value forKey:2U]); + XCTAssertEqual(value, YES); + XCTAssertTrue([dict getBool:NULL forKey:3U]); + XCTAssertTrue([dict getBool:&value forKey:3U]); + XCTAssertEqual(value, NO); + XCTAssertTrue([dict getBool:NULL forKey:4U]); + XCTAssertTrue([dict getBool:&value forKey:4U]); + XCTAssertEqual(value, NO); + [dict2 release]; + [dict release]; +} + +- (void)testRemove { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const BOOL kValues[] = { YES, YES, NO, NO }; + GPBUInt32BoolDictionary *dict = + [[GPBUInt32BoolDictionary alloc] initWithBools:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 4U); + + [dict removeBoolForKey:2U]; + XCTAssertEqual(dict.count, 3U); + BOOL value; + XCTAssertTrue([dict getBool:NULL forKey:1U]); + XCTAssertTrue([dict getBool:&value forKey:1U]); + XCTAssertEqual(value, YES); + XCTAssertFalse([dict getBool:NULL forKey:2U]); + XCTAssertTrue([dict getBool:NULL forKey:3U]); + XCTAssertTrue([dict getBool:&value forKey:3U]); + XCTAssertEqual(value, NO); + XCTAssertTrue([dict getBool:NULL forKey:4U]); + XCTAssertTrue([dict getBool:&value forKey:4U]); + XCTAssertEqual(value, NO); + + // Remove again does nothing. + [dict removeBoolForKey:2U]; + XCTAssertEqual(dict.count, 3U); + XCTAssertTrue([dict getBool:NULL forKey:1U]); + XCTAssertTrue([dict getBool:&value forKey:1U]); + XCTAssertEqual(value, YES); + XCTAssertFalse([dict getBool:NULL forKey:2U]); + XCTAssertTrue([dict getBool:NULL forKey:3U]); + XCTAssertTrue([dict getBool:&value forKey:3U]); + XCTAssertEqual(value, NO); + XCTAssertTrue([dict getBool:NULL forKey:4U]); + XCTAssertTrue([dict getBool:&value forKey:4U]); + XCTAssertEqual(value, NO); + + [dict removeBoolForKey:4U]; + XCTAssertEqual(dict.count, 2U); + XCTAssertTrue([dict getBool:NULL forKey:1U]); + XCTAssertTrue([dict getBool:&value forKey:1U]); + XCTAssertEqual(value, YES); + XCTAssertFalse([dict getBool:NULL forKey:2U]); + XCTAssertTrue([dict getBool:NULL forKey:3U]); + XCTAssertTrue([dict getBool:&value forKey:3U]); + XCTAssertEqual(value, NO); + XCTAssertFalse([dict getBool:NULL forKey:4U]); + + [dict removeAll]; + XCTAssertEqual(dict.count, 0U); + XCTAssertFalse([dict getBool:NULL forKey:1U]); + XCTAssertFalse([dict getBool:NULL forKey:2U]); + XCTAssertFalse([dict getBool:NULL forKey:3U]); + XCTAssertFalse([dict getBool:NULL forKey:4U]); + [dict release]; +} + +- (void)testInplaceMutation { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const BOOL kValues[] = { YES, YES, NO, NO }; + GPBUInt32BoolDictionary *dict = + [[GPBUInt32BoolDictionary alloc] initWithBools:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 4U); + BOOL value; + XCTAssertTrue([dict getBool:NULL forKey:1U]); + XCTAssertTrue([dict getBool:&value forKey:1U]); + XCTAssertEqual(value, YES); + XCTAssertTrue([dict getBool:NULL forKey:2U]); + XCTAssertTrue([dict getBool:&value forKey:2U]); + XCTAssertEqual(value, YES); + XCTAssertTrue([dict getBool:NULL forKey:3U]); + XCTAssertTrue([dict getBool:&value forKey:3U]); + XCTAssertEqual(value, NO); + XCTAssertTrue([dict getBool:NULL forKey:4U]); + XCTAssertTrue([dict getBool:&value forKey:4U]); + XCTAssertEqual(value, NO); + + [dict setBool:NO forKey:1U]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getBool:NULL forKey:1U]); + XCTAssertTrue([dict getBool:&value forKey:1U]); + XCTAssertEqual(value, NO); + XCTAssertTrue([dict getBool:NULL forKey:2U]); + XCTAssertTrue([dict getBool:&value forKey:2U]); + XCTAssertEqual(value, YES); + XCTAssertTrue([dict getBool:NULL forKey:3U]); + XCTAssertTrue([dict getBool:&value forKey:3U]); + XCTAssertEqual(value, NO); + XCTAssertTrue([dict getBool:NULL forKey:4U]); + XCTAssertTrue([dict getBool:&value forKey:4U]); + XCTAssertEqual(value, NO); + + [dict setBool:YES forKey:4U]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getBool:NULL forKey:1U]); + XCTAssertTrue([dict getBool:&value forKey:1U]); + XCTAssertEqual(value, NO); + XCTAssertTrue([dict getBool:NULL forKey:2U]); + XCTAssertTrue([dict getBool:&value forKey:2U]); + XCTAssertEqual(value, YES); + XCTAssertTrue([dict getBool:NULL forKey:3U]); + XCTAssertTrue([dict getBool:&value forKey:3U]); + XCTAssertEqual(value, NO); + XCTAssertTrue([dict getBool:NULL forKey:4U]); + XCTAssertTrue([dict getBool:&value forKey:4U]); + XCTAssertEqual(value, YES); + + const uint32_t kKeys2[] = { 2U, 3U }; + const BOOL kValues2[] = { NO, YES }; + GPBUInt32BoolDictionary *dict2 = + [[GPBUInt32BoolDictionary alloc] initWithBools:kValues2 + forKeys:kKeys2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(dict2); + [dict addEntriesFromDictionary:dict2]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getBool:NULL forKey:1U]); + XCTAssertTrue([dict getBool:&value forKey:1U]); + XCTAssertEqual(value, NO); + XCTAssertTrue([dict getBool:NULL forKey:2U]); + XCTAssertTrue([dict getBool:&value forKey:2U]); + XCTAssertEqual(value, NO); + XCTAssertTrue([dict getBool:NULL forKey:3U]); + XCTAssertTrue([dict getBool:&value forKey:3U]); + XCTAssertEqual(value, YES); + XCTAssertTrue([dict getBool:NULL forKey:4U]); + XCTAssertTrue([dict getBool:&value forKey:4U]); + XCTAssertEqual(value, YES); + + [dict2 release]; + [dict release]; +} + +@end + +#pragma mark - UInt32 -> Float + +@interface GPBUInt32FloatDictionaryTests : XCTestCase +@end + +@implementation GPBUInt32FloatDictionaryTests + +- (void)testEmpty { + GPBUInt32FloatDictionary *dict = [[GPBUInt32FloatDictionary alloc] init]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 0U); + XCTAssertFalse([dict getFloat:NULL forKey:1U]); + [dict enumerateKeysAndFloatsUsingBlock:^(uint32_t aKey, float aValue, BOOL *stop) { + #pragma unused(aKey, aValue, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [dict release]; +} + +- (void)testOne { + GPBUInt32FloatDictionary *dict = [[GPBUInt32FloatDictionary alloc] init]; + [dict setFloat:500.f forKey:1U]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 1U); + float value; + XCTAssertTrue([dict getFloat:NULL forKey:1U]); + XCTAssertTrue([dict getFloat:&value forKey:1U]); + XCTAssertEqual(value, 500.f); + XCTAssertFalse([dict getFloat:NULL forKey:2U]); + [dict enumerateKeysAndFloatsUsingBlock:^(uint32_t aKey, float aValue, BOOL *stop) { + XCTAssertEqual(aKey, 1U); + XCTAssertEqual(aValue, 500.f); + XCTAssertNotEqual(stop, NULL); + }]; + [dict release]; +} + +- (void)testBasics { + const uint32_t kKeys[] = { 1U, 2U, 3U }; + const float kValues[] = { 500.f, 501.f, 502.f }; + GPBUInt32FloatDictionary *dict = + [[GPBUInt32FloatDictionary alloc] initWithFloats:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 3U); + float value; + XCTAssertTrue([dict getFloat:NULL forKey:1U]); + XCTAssertTrue([dict getFloat:&value forKey:1U]); + XCTAssertEqual(value, 500.f); + XCTAssertTrue([dict getFloat:NULL forKey:2U]); + XCTAssertTrue([dict getFloat:&value forKey:2U]); + XCTAssertEqual(value, 501.f); + XCTAssertTrue([dict getFloat:NULL forKey:3U]); + XCTAssertTrue([dict getFloat:&value forKey:3U]); + XCTAssertEqual(value, 502.f); + XCTAssertFalse([dict getFloat:NULL forKey:4U]); + + __block NSUInteger idx = 0; + uint32_t *seenKeys = malloc(3 * sizeof(uint32_t)); + float *seenValues = malloc(3 * sizeof(float)); + [dict enumerateKeysAndFloatsUsingBlock:^(uint32_t aKey, float aValue, BOOL *stop) { + XCTAssertLessThan(idx, 3U); + seenKeys[idx] = aKey; + seenValues[idx] = aValue; + XCTAssertNotEqual(stop, NULL); + ++idx; + }]; + for (int i = 0; i < 3; ++i) { + BOOL foundKey = NO; + for (int j = 0; (j < 3) && !foundKey; ++j) { + if (kKeys[i] == seenKeys[j]) { + foundKey = YES; + XCTAssertEqual(kValues[i], seenValues[j], @"i = %d, j = %d", i, j); + } + } + XCTAssertTrue(foundKey, @"i = %d", i); + } + free(seenKeys); + free(seenValues); + + // Stopping the enumeration. + idx = 0; + [dict enumerateKeysAndFloatsUsingBlock:^(uint32_t aKey, float aValue, BOOL *stop) { + #pragma unused(aKey, aValue) + if (idx == 1) *stop = YES; + XCTAssertNotEqual(idx, 2U); + ++idx; + }]; + [dict release]; +} + +- (void)testEquality { + const uint32_t kKeys1[] = { 1U, 2U, 3U, 4U }; + const uint32_t kKeys2[] = { 2U, 1U, 4U }; + const float kValues1[] = { 500.f, 501.f, 502.f }; + const float kValues2[] = { 500.f, 503.f, 502.f }; + const float kValues3[] = { 500.f, 501.f, 502.f, 503.f }; + GPBUInt32FloatDictionary *dict1 = + [[GPBUInt32FloatDictionary alloc] initWithFloats:kValues1 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict1); + GPBUInt32FloatDictionary *dict1prime = + [[GPBUInt32FloatDictionary alloc] initWithFloats:kValues1 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict1prime); + GPBUInt32FloatDictionary *dict2 = + [[GPBUInt32FloatDictionary alloc] initWithFloats:kValues2 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(dict2); + GPBUInt32FloatDictionary *dict3 = + [[GPBUInt32FloatDictionary alloc] initWithFloats:kValues1 + forKeys:kKeys2 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict3); + GPBUInt32FloatDictionary *dict4 = + [[GPBUInt32FloatDictionary alloc] initWithFloats:kValues3 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues3)]; + XCTAssertNotNil(dict4); + + // 1/1Prime should be different objects, but equal. + XCTAssertNotEqual(dict1, dict1prime); + XCTAssertEqualObjects(dict1, dict1prime); + // Equal, so they must have same hash. + XCTAssertEqual([dict1 hash], [dict1prime hash]); + + // 2 is same keys, different values; not equal. + XCTAssertNotEqualObjects(dict1, dict2); + + // 3 is different keys, same values; not equal. + XCTAssertNotEqualObjects(dict1, dict3); + + // 4 extra pair; not equal + XCTAssertNotEqualObjects(dict1, dict4); + + [dict1 release]; + [dict1prime release]; + [dict2 release]; + [dict3 release]; + [dict4 release]; +} + +- (void)testCopy { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const float kValues[] = { 500.f, 501.f, 502.f, 503.f }; + GPBUInt32FloatDictionary *dict = + [[GPBUInt32FloatDictionary alloc] initWithFloats:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + + GPBUInt32FloatDictionary *dict2 = [dict copy]; + XCTAssertNotNil(dict2); + + // Should be new object but equal. + XCTAssertNotEqual(dict, dict2); + XCTAssertEqualObjects(dict, dict2); + XCTAssertTrue([dict2 isKindOfClass:[GPBUInt32FloatDictionary class]]); + + [dict2 release]; + [dict release]; +} + +- (void)testDictionaryFromDictionary { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const float kValues[] = { 500.f, 501.f, 502.f, 503.f }; + GPBUInt32FloatDictionary *dict = + [[GPBUInt32FloatDictionary alloc] initWithFloats:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + + GPBUInt32FloatDictionary *dict2 = + [[GPBUInt32FloatDictionary alloc] initWithDictionary:dict]; + XCTAssertNotNil(dict2); + + // Should be new pointer, but equal objects. + XCTAssertNotEqual(dict, dict2); + XCTAssertEqualObjects(dict, dict2); + [dict2 release]; + [dict release]; +} + +- (void)testAdds { + GPBUInt32FloatDictionary *dict = [[GPBUInt32FloatDictionary alloc] init]; + XCTAssertNotNil(dict); + + XCTAssertEqual(dict.count, 0U); + [dict setFloat:500.f forKey:1U]; + XCTAssertEqual(dict.count, 1U); + + const uint32_t kKeys[] = { 2U, 3U, 4U }; + const float kValues[] = { 501.f, 502.f, 503.f }; + GPBUInt32FloatDictionary *dict2 = + [[GPBUInt32FloatDictionary alloc] initWithFloats:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict2); + [dict addEntriesFromDictionary:dict2]; + XCTAssertEqual(dict.count, 4U); + + float value; + XCTAssertTrue([dict getFloat:NULL forKey:1U]); + XCTAssertTrue([dict getFloat:&value forKey:1U]); + XCTAssertEqual(value, 500.f); + XCTAssertTrue([dict getFloat:NULL forKey:2U]); + XCTAssertTrue([dict getFloat:&value forKey:2U]); + XCTAssertEqual(value, 501.f); + XCTAssertTrue([dict getFloat:NULL forKey:3U]); + XCTAssertTrue([dict getFloat:&value forKey:3U]); + XCTAssertEqual(value, 502.f); + XCTAssertTrue([dict getFloat:NULL forKey:4U]); + XCTAssertTrue([dict getFloat:&value forKey:4U]); + XCTAssertEqual(value, 503.f); + [dict2 release]; + [dict release]; +} + +- (void)testRemove { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const float kValues[] = { 500.f, 501.f, 502.f, 503.f }; + GPBUInt32FloatDictionary *dict = + [[GPBUInt32FloatDictionary alloc] initWithFloats:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 4U); + + [dict removeFloatForKey:2U]; + XCTAssertEqual(dict.count, 3U); + float value; + XCTAssertTrue([dict getFloat:NULL forKey:1U]); + XCTAssertTrue([dict getFloat:&value forKey:1U]); + XCTAssertEqual(value, 500.f); + XCTAssertFalse([dict getFloat:NULL forKey:2U]); + XCTAssertTrue([dict getFloat:NULL forKey:3U]); + XCTAssertTrue([dict getFloat:&value forKey:3U]); + XCTAssertEqual(value, 502.f); + XCTAssertTrue([dict getFloat:NULL forKey:4U]); + XCTAssertTrue([dict getFloat:&value forKey:4U]); + XCTAssertEqual(value, 503.f); + + // Remove again does nothing. + [dict removeFloatForKey:2U]; + XCTAssertEqual(dict.count, 3U); + XCTAssertTrue([dict getFloat:NULL forKey:1U]); + XCTAssertTrue([dict getFloat:&value forKey:1U]); + XCTAssertEqual(value, 500.f); + XCTAssertFalse([dict getFloat:NULL forKey:2U]); + XCTAssertTrue([dict getFloat:NULL forKey:3U]); + XCTAssertTrue([dict getFloat:&value forKey:3U]); + XCTAssertEqual(value, 502.f); + XCTAssertTrue([dict getFloat:NULL forKey:4U]); + XCTAssertTrue([dict getFloat:&value forKey:4U]); + XCTAssertEqual(value, 503.f); + + [dict removeFloatForKey:4U]; + XCTAssertEqual(dict.count, 2U); + XCTAssertTrue([dict getFloat:NULL forKey:1U]); + XCTAssertTrue([dict getFloat:&value forKey:1U]); + XCTAssertEqual(value, 500.f); + XCTAssertFalse([dict getFloat:NULL forKey:2U]); + XCTAssertTrue([dict getFloat:NULL forKey:3U]); + XCTAssertTrue([dict getFloat:&value forKey:3U]); + XCTAssertEqual(value, 502.f); + XCTAssertFalse([dict getFloat:NULL forKey:4U]); + + [dict removeAll]; + XCTAssertEqual(dict.count, 0U); + XCTAssertFalse([dict getFloat:NULL forKey:1U]); + XCTAssertFalse([dict getFloat:NULL forKey:2U]); + XCTAssertFalse([dict getFloat:NULL forKey:3U]); + XCTAssertFalse([dict getFloat:NULL forKey:4U]); + [dict release]; +} + +- (void)testInplaceMutation { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const float kValues[] = { 500.f, 501.f, 502.f, 503.f }; + GPBUInt32FloatDictionary *dict = + [[GPBUInt32FloatDictionary alloc] initWithFloats:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 4U); + float value; + XCTAssertTrue([dict getFloat:NULL forKey:1U]); + XCTAssertTrue([dict getFloat:&value forKey:1U]); + XCTAssertEqual(value, 500.f); + XCTAssertTrue([dict getFloat:NULL forKey:2U]); + XCTAssertTrue([dict getFloat:&value forKey:2U]); + XCTAssertEqual(value, 501.f); + XCTAssertTrue([dict getFloat:NULL forKey:3U]); + XCTAssertTrue([dict getFloat:&value forKey:3U]); + XCTAssertEqual(value, 502.f); + XCTAssertTrue([dict getFloat:NULL forKey:4U]); + XCTAssertTrue([dict getFloat:&value forKey:4U]); + XCTAssertEqual(value, 503.f); + + [dict setFloat:503.f forKey:1U]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getFloat:NULL forKey:1U]); + XCTAssertTrue([dict getFloat:&value forKey:1U]); + XCTAssertEqual(value, 503.f); + XCTAssertTrue([dict getFloat:NULL forKey:2U]); + XCTAssertTrue([dict getFloat:&value forKey:2U]); + XCTAssertEqual(value, 501.f); + XCTAssertTrue([dict getFloat:NULL forKey:3U]); + XCTAssertTrue([dict getFloat:&value forKey:3U]); + XCTAssertEqual(value, 502.f); + XCTAssertTrue([dict getFloat:NULL forKey:4U]); + XCTAssertTrue([dict getFloat:&value forKey:4U]); + XCTAssertEqual(value, 503.f); + + [dict setFloat:501.f forKey:4U]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getFloat:NULL forKey:1U]); + XCTAssertTrue([dict getFloat:&value forKey:1U]); + XCTAssertEqual(value, 503.f); + XCTAssertTrue([dict getFloat:NULL forKey:2U]); + XCTAssertTrue([dict getFloat:&value forKey:2U]); + XCTAssertEqual(value, 501.f); + XCTAssertTrue([dict getFloat:NULL forKey:3U]); + XCTAssertTrue([dict getFloat:&value forKey:3U]); + XCTAssertEqual(value, 502.f); + XCTAssertTrue([dict getFloat:NULL forKey:4U]); + XCTAssertTrue([dict getFloat:&value forKey:4U]); + XCTAssertEqual(value, 501.f); + + const uint32_t kKeys2[] = { 2U, 3U }; + const float kValues2[] = { 502.f, 500.f }; + GPBUInt32FloatDictionary *dict2 = + [[GPBUInt32FloatDictionary alloc] initWithFloats:kValues2 + forKeys:kKeys2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(dict2); + [dict addEntriesFromDictionary:dict2]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getFloat:NULL forKey:1U]); + XCTAssertTrue([dict getFloat:&value forKey:1U]); + XCTAssertEqual(value, 503.f); + XCTAssertTrue([dict getFloat:NULL forKey:2U]); + XCTAssertTrue([dict getFloat:&value forKey:2U]); + XCTAssertEqual(value, 502.f); + XCTAssertTrue([dict getFloat:NULL forKey:3U]); + XCTAssertTrue([dict getFloat:&value forKey:3U]); + XCTAssertEqual(value, 500.f); + XCTAssertTrue([dict getFloat:NULL forKey:4U]); + XCTAssertTrue([dict getFloat:&value forKey:4U]); + XCTAssertEqual(value, 501.f); + + [dict2 release]; + [dict release]; +} + +@end + +#pragma mark - UInt32 -> Double + +@interface GPBUInt32DoubleDictionaryTests : XCTestCase +@end + +@implementation GPBUInt32DoubleDictionaryTests + +- (void)testEmpty { + GPBUInt32DoubleDictionary *dict = [[GPBUInt32DoubleDictionary alloc] init]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 0U); + XCTAssertFalse([dict getDouble:NULL forKey:1U]); + [dict enumerateKeysAndDoublesUsingBlock:^(uint32_t aKey, double aValue, BOOL *stop) { + #pragma unused(aKey, aValue, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [dict release]; +} + +- (void)testOne { + GPBUInt32DoubleDictionary *dict = [[GPBUInt32DoubleDictionary alloc] init]; + [dict setDouble:600. forKey:1U]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 1U); + double value; + XCTAssertTrue([dict getDouble:NULL forKey:1U]); + XCTAssertTrue([dict getDouble:&value forKey:1U]); + XCTAssertEqual(value, 600.); + XCTAssertFalse([dict getDouble:NULL forKey:2U]); + [dict enumerateKeysAndDoublesUsingBlock:^(uint32_t aKey, double aValue, BOOL *stop) { + XCTAssertEqual(aKey, 1U); + XCTAssertEqual(aValue, 600.); + XCTAssertNotEqual(stop, NULL); + }]; + [dict release]; +} + +- (void)testBasics { + const uint32_t kKeys[] = { 1U, 2U, 3U }; + const double kValues[] = { 600., 601., 602. }; + GPBUInt32DoubleDictionary *dict = + [[GPBUInt32DoubleDictionary alloc] initWithDoubles:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 3U); + double value; + XCTAssertTrue([dict getDouble:NULL forKey:1U]); + XCTAssertTrue([dict getDouble:&value forKey:1U]); + XCTAssertEqual(value, 600.); + XCTAssertTrue([dict getDouble:NULL forKey:2U]); + XCTAssertTrue([dict getDouble:&value forKey:2U]); + XCTAssertEqual(value, 601.); + XCTAssertTrue([dict getDouble:NULL forKey:3U]); + XCTAssertTrue([dict getDouble:&value forKey:3U]); + XCTAssertEqual(value, 602.); + XCTAssertFalse([dict getDouble:NULL forKey:4U]); + + __block NSUInteger idx = 0; + uint32_t *seenKeys = malloc(3 * sizeof(uint32_t)); + double *seenValues = malloc(3 * sizeof(double)); + [dict enumerateKeysAndDoublesUsingBlock:^(uint32_t aKey, double aValue, BOOL *stop) { + XCTAssertLessThan(idx, 3U); + seenKeys[idx] = aKey; + seenValues[idx] = aValue; + XCTAssertNotEqual(stop, NULL); + ++idx; + }]; + for (int i = 0; i < 3; ++i) { + BOOL foundKey = NO; + for (int j = 0; (j < 3) && !foundKey; ++j) { + if (kKeys[i] == seenKeys[j]) { + foundKey = YES; + XCTAssertEqual(kValues[i], seenValues[j], @"i = %d, j = %d", i, j); + } + } + XCTAssertTrue(foundKey, @"i = %d", i); + } + free(seenKeys); + free(seenValues); + + // Stopping the enumeration. + idx = 0; + [dict enumerateKeysAndDoublesUsingBlock:^(uint32_t aKey, double aValue, BOOL *stop) { + #pragma unused(aKey, aValue) + if (idx == 1) *stop = YES; + XCTAssertNotEqual(idx, 2U); + ++idx; + }]; + [dict release]; +} + +- (void)testEquality { + const uint32_t kKeys1[] = { 1U, 2U, 3U, 4U }; + const uint32_t kKeys2[] = { 2U, 1U, 4U }; + const double kValues1[] = { 600., 601., 602. }; + const double kValues2[] = { 600., 603., 602. }; + const double kValues3[] = { 600., 601., 602., 603. }; + GPBUInt32DoubleDictionary *dict1 = + [[GPBUInt32DoubleDictionary alloc] initWithDoubles:kValues1 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict1); + GPBUInt32DoubleDictionary *dict1prime = + [[GPBUInt32DoubleDictionary alloc] initWithDoubles:kValues1 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict1prime); + GPBUInt32DoubleDictionary *dict2 = + [[GPBUInt32DoubleDictionary alloc] initWithDoubles:kValues2 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(dict2); + GPBUInt32DoubleDictionary *dict3 = + [[GPBUInt32DoubleDictionary alloc] initWithDoubles:kValues1 + forKeys:kKeys2 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict3); + GPBUInt32DoubleDictionary *dict4 = + [[GPBUInt32DoubleDictionary alloc] initWithDoubles:kValues3 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues3)]; + XCTAssertNotNil(dict4); + + // 1/1Prime should be different objects, but equal. + XCTAssertNotEqual(dict1, dict1prime); + XCTAssertEqualObjects(dict1, dict1prime); + // Equal, so they must have same hash. + XCTAssertEqual([dict1 hash], [dict1prime hash]); + + // 2 is same keys, different values; not equal. + XCTAssertNotEqualObjects(dict1, dict2); + + // 3 is different keys, same values; not equal. + XCTAssertNotEqualObjects(dict1, dict3); + + // 4 extra pair; not equal + XCTAssertNotEqualObjects(dict1, dict4); + + [dict1 release]; + [dict1prime release]; + [dict2 release]; + [dict3 release]; + [dict4 release]; +} + +- (void)testCopy { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const double kValues[] = { 600., 601., 602., 603. }; + GPBUInt32DoubleDictionary *dict = + [[GPBUInt32DoubleDictionary alloc] initWithDoubles:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + + GPBUInt32DoubleDictionary *dict2 = [dict copy]; + XCTAssertNotNil(dict2); + + // Should be new object but equal. + XCTAssertNotEqual(dict, dict2); + XCTAssertEqualObjects(dict, dict2); + XCTAssertTrue([dict2 isKindOfClass:[GPBUInt32DoubleDictionary class]]); + + [dict2 release]; + [dict release]; +} + +- (void)testDictionaryFromDictionary { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const double kValues[] = { 600., 601., 602., 603. }; + GPBUInt32DoubleDictionary *dict = + [[GPBUInt32DoubleDictionary alloc] initWithDoubles:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + + GPBUInt32DoubleDictionary *dict2 = + [[GPBUInt32DoubleDictionary alloc] initWithDictionary:dict]; + XCTAssertNotNil(dict2); + + // Should be new pointer, but equal objects. + XCTAssertNotEqual(dict, dict2); + XCTAssertEqualObjects(dict, dict2); + [dict2 release]; + [dict release]; +} + +- (void)testAdds { + GPBUInt32DoubleDictionary *dict = [[GPBUInt32DoubleDictionary alloc] init]; + XCTAssertNotNil(dict); + + XCTAssertEqual(dict.count, 0U); + [dict setDouble:600. forKey:1U]; + XCTAssertEqual(dict.count, 1U); + + const uint32_t kKeys[] = { 2U, 3U, 4U }; + const double kValues[] = { 601., 602., 603. }; + GPBUInt32DoubleDictionary *dict2 = + [[GPBUInt32DoubleDictionary alloc] initWithDoubles:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict2); + [dict addEntriesFromDictionary:dict2]; + XCTAssertEqual(dict.count, 4U); + + double value; + XCTAssertTrue([dict getDouble:NULL forKey:1U]); + XCTAssertTrue([dict getDouble:&value forKey:1U]); + XCTAssertEqual(value, 600.); + XCTAssertTrue([dict getDouble:NULL forKey:2U]); + XCTAssertTrue([dict getDouble:&value forKey:2U]); + XCTAssertEqual(value, 601.); + XCTAssertTrue([dict getDouble:NULL forKey:3U]); + XCTAssertTrue([dict getDouble:&value forKey:3U]); + XCTAssertEqual(value, 602.); + XCTAssertTrue([dict getDouble:NULL forKey:4U]); + XCTAssertTrue([dict getDouble:&value forKey:4U]); + XCTAssertEqual(value, 603.); + [dict2 release]; + [dict release]; +} + +- (void)testRemove { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const double kValues[] = { 600., 601., 602., 603. }; + GPBUInt32DoubleDictionary *dict = + [[GPBUInt32DoubleDictionary alloc] initWithDoubles:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 4U); + + [dict removeDoubleForKey:2U]; + XCTAssertEqual(dict.count, 3U); + double value; + XCTAssertTrue([dict getDouble:NULL forKey:1U]); + XCTAssertTrue([dict getDouble:&value forKey:1U]); + XCTAssertEqual(value, 600.); + XCTAssertFalse([dict getDouble:NULL forKey:2U]); + XCTAssertTrue([dict getDouble:NULL forKey:3U]); + XCTAssertTrue([dict getDouble:&value forKey:3U]); + XCTAssertEqual(value, 602.); + XCTAssertTrue([dict getDouble:NULL forKey:4U]); + XCTAssertTrue([dict getDouble:&value forKey:4U]); + XCTAssertEqual(value, 603.); + + // Remove again does nothing. + [dict removeDoubleForKey:2U]; + XCTAssertEqual(dict.count, 3U); + XCTAssertTrue([dict getDouble:NULL forKey:1U]); + XCTAssertTrue([dict getDouble:&value forKey:1U]); + XCTAssertEqual(value, 600.); + XCTAssertFalse([dict getDouble:NULL forKey:2U]); + XCTAssertTrue([dict getDouble:NULL forKey:3U]); + XCTAssertTrue([dict getDouble:&value forKey:3U]); + XCTAssertEqual(value, 602.); + XCTAssertTrue([dict getDouble:NULL forKey:4U]); + XCTAssertTrue([dict getDouble:&value forKey:4U]); + XCTAssertEqual(value, 603.); + + [dict removeDoubleForKey:4U]; + XCTAssertEqual(dict.count, 2U); + XCTAssertTrue([dict getDouble:NULL forKey:1U]); + XCTAssertTrue([dict getDouble:&value forKey:1U]); + XCTAssertEqual(value, 600.); + XCTAssertFalse([dict getDouble:NULL forKey:2U]); + XCTAssertTrue([dict getDouble:NULL forKey:3U]); + XCTAssertTrue([dict getDouble:&value forKey:3U]); + XCTAssertEqual(value, 602.); + XCTAssertFalse([dict getDouble:NULL forKey:4U]); + + [dict removeAll]; + XCTAssertEqual(dict.count, 0U); + XCTAssertFalse([dict getDouble:NULL forKey:1U]); + XCTAssertFalse([dict getDouble:NULL forKey:2U]); + XCTAssertFalse([dict getDouble:NULL forKey:3U]); + XCTAssertFalse([dict getDouble:NULL forKey:4U]); + [dict release]; +} + +- (void)testInplaceMutation { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const double kValues[] = { 600., 601., 602., 603. }; + GPBUInt32DoubleDictionary *dict = + [[GPBUInt32DoubleDictionary alloc] initWithDoubles:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 4U); + double value; + XCTAssertTrue([dict getDouble:NULL forKey:1U]); + XCTAssertTrue([dict getDouble:&value forKey:1U]); + XCTAssertEqual(value, 600.); + XCTAssertTrue([dict getDouble:NULL forKey:2U]); + XCTAssertTrue([dict getDouble:&value forKey:2U]); + XCTAssertEqual(value, 601.); + XCTAssertTrue([dict getDouble:NULL forKey:3U]); + XCTAssertTrue([dict getDouble:&value forKey:3U]); + XCTAssertEqual(value, 602.); + XCTAssertTrue([dict getDouble:NULL forKey:4U]); + XCTAssertTrue([dict getDouble:&value forKey:4U]); + XCTAssertEqual(value, 603.); + + [dict setDouble:603. forKey:1U]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getDouble:NULL forKey:1U]); + XCTAssertTrue([dict getDouble:&value forKey:1U]); + XCTAssertEqual(value, 603.); + XCTAssertTrue([dict getDouble:NULL forKey:2U]); + XCTAssertTrue([dict getDouble:&value forKey:2U]); + XCTAssertEqual(value, 601.); + XCTAssertTrue([dict getDouble:NULL forKey:3U]); + XCTAssertTrue([dict getDouble:&value forKey:3U]); + XCTAssertEqual(value, 602.); + XCTAssertTrue([dict getDouble:NULL forKey:4U]); + XCTAssertTrue([dict getDouble:&value forKey:4U]); + XCTAssertEqual(value, 603.); + + [dict setDouble:601. forKey:4U]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getDouble:NULL forKey:1U]); + XCTAssertTrue([dict getDouble:&value forKey:1U]); + XCTAssertEqual(value, 603.); + XCTAssertTrue([dict getDouble:NULL forKey:2U]); + XCTAssertTrue([dict getDouble:&value forKey:2U]); + XCTAssertEqual(value, 601.); + XCTAssertTrue([dict getDouble:NULL forKey:3U]); + XCTAssertTrue([dict getDouble:&value forKey:3U]); + XCTAssertEqual(value, 602.); + XCTAssertTrue([dict getDouble:NULL forKey:4U]); + XCTAssertTrue([dict getDouble:&value forKey:4U]); + XCTAssertEqual(value, 601.); + + const uint32_t kKeys2[] = { 2U, 3U }; + const double kValues2[] = { 602., 600. }; + GPBUInt32DoubleDictionary *dict2 = + [[GPBUInt32DoubleDictionary alloc] initWithDoubles:kValues2 + forKeys:kKeys2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(dict2); + [dict addEntriesFromDictionary:dict2]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getDouble:NULL forKey:1U]); + XCTAssertTrue([dict getDouble:&value forKey:1U]); + XCTAssertEqual(value, 603.); + XCTAssertTrue([dict getDouble:NULL forKey:2U]); + XCTAssertTrue([dict getDouble:&value forKey:2U]); + XCTAssertEqual(value, 602.); + XCTAssertTrue([dict getDouble:NULL forKey:3U]); + XCTAssertTrue([dict getDouble:&value forKey:3U]); + XCTAssertEqual(value, 600.); + XCTAssertTrue([dict getDouble:NULL forKey:4U]); + XCTAssertTrue([dict getDouble:&value forKey:4U]); + XCTAssertEqual(value, 601.); + + [dict2 release]; + [dict release]; +} + +@end + +#pragma mark - UInt32 -> Enum + +@interface GPBUInt32EnumDictionaryTests : XCTestCase +@end + +@implementation GPBUInt32EnumDictionaryTests + +- (void)testEmpty { + GPBUInt32EnumDictionary *dict = [[GPBUInt32EnumDictionary alloc] init]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 0U); + XCTAssertFalse([dict getEnum:NULL forKey:1U]); + [dict enumerateKeysAndEnumsUsingBlock:^(uint32_t aKey, int32_t aValue, BOOL *stop) { + #pragma unused(aKey, aValue, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [dict release]; +} + +- (void)testOne { + GPBUInt32EnumDictionary *dict = [[GPBUInt32EnumDictionary alloc] init]; + [dict setEnum:700 forKey:1U]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 1U); + int32_t value; + XCTAssertTrue([dict getEnum:NULL forKey:1U]); + XCTAssertTrue([dict getEnum:&value forKey:1U]); + XCTAssertEqual(value, 700); + XCTAssertFalse([dict getEnum:NULL forKey:2U]); + [dict enumerateKeysAndEnumsUsingBlock:^(uint32_t aKey, int32_t aValue, BOOL *stop) { + XCTAssertEqual(aKey, 1U); + XCTAssertEqual(aValue, 700); + XCTAssertNotEqual(stop, NULL); + }]; + [dict release]; +} + +- (void)testBasics { + const uint32_t kKeys[] = { 1U, 2U, 3U }; + const int32_t kValues[] = { 700, 701, 702 }; + GPBUInt32EnumDictionary *dict = + [[GPBUInt32EnumDictionary alloc] initWithEnums:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 3U); + int32_t value; + XCTAssertTrue([dict getEnum:NULL forKey:1U]); + XCTAssertTrue([dict getEnum:&value forKey:1U]); + XCTAssertEqual(value, 700); + XCTAssertTrue([dict getEnum:NULL forKey:2U]); + XCTAssertTrue([dict getEnum:&value forKey:2U]); + XCTAssertEqual(value, 701); + XCTAssertTrue([dict getEnum:NULL forKey:3U]); + XCTAssertTrue([dict getEnum:&value forKey:3U]); + XCTAssertEqual(value, 702); + XCTAssertFalse([dict getEnum:NULL forKey:4U]); + + __block NSUInteger idx = 0; + uint32_t *seenKeys = malloc(3 * sizeof(uint32_t)); + int32_t *seenValues = malloc(3 * sizeof(int32_t)); + [dict enumerateKeysAndEnumsUsingBlock:^(uint32_t aKey, int32_t aValue, BOOL *stop) { + XCTAssertLessThan(idx, 3U); + seenKeys[idx] = aKey; + seenValues[idx] = aValue; + XCTAssertNotEqual(stop, NULL); + ++idx; + }]; + for (int i = 0; i < 3; ++i) { + BOOL foundKey = NO; + for (int j = 0; (j < 3) && !foundKey; ++j) { + if (kKeys[i] == seenKeys[j]) { + foundKey = YES; + XCTAssertEqual(kValues[i], seenValues[j], @"i = %d, j = %d", i, j); + } + } + XCTAssertTrue(foundKey, @"i = %d", i); + } + free(seenKeys); + free(seenValues); + + // Stopping the enumeration. + idx = 0; + [dict enumerateKeysAndEnumsUsingBlock:^(uint32_t aKey, int32_t aValue, BOOL *stop) { + #pragma unused(aKey, aValue) + if (idx == 1) *stop = YES; + XCTAssertNotEqual(idx, 2U); + ++idx; + }]; + [dict release]; +} + +- (void)testEquality { + const uint32_t kKeys1[] = { 1U, 2U, 3U, 4U }; + const uint32_t kKeys2[] = { 2U, 1U, 4U }; + const int32_t kValues1[] = { 700, 701, 702 }; + const int32_t kValues2[] = { 700, 703, 702 }; + const int32_t kValues3[] = { 700, 701, 702, 703 }; + GPBUInt32EnumDictionary *dict1 = + [[GPBUInt32EnumDictionary alloc] initWithEnums:kValues1 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict1); + GPBUInt32EnumDictionary *dict1prime = + [[GPBUInt32EnumDictionary alloc] initWithEnums:kValues1 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict1prime); + GPBUInt32EnumDictionary *dict2 = + [[GPBUInt32EnumDictionary alloc] initWithEnums:kValues2 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(dict2); + GPBUInt32EnumDictionary *dict3 = + [[GPBUInt32EnumDictionary alloc] initWithEnums:kValues1 + forKeys:kKeys2 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict3); + GPBUInt32EnumDictionary *dict4 = + [[GPBUInt32EnumDictionary alloc] initWithEnums:kValues3 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues3)]; + XCTAssertNotNil(dict4); + + // 1/1Prime should be different objects, but equal. + XCTAssertNotEqual(dict1, dict1prime); + XCTAssertEqualObjects(dict1, dict1prime); + // Equal, so they must have same hash. + XCTAssertEqual([dict1 hash], [dict1prime hash]); + + // 2 is same keys, different values; not equal. + XCTAssertNotEqualObjects(dict1, dict2); + + // 3 is different keys, same values; not equal. + XCTAssertNotEqualObjects(dict1, dict3); + + // 4 extra pair; not equal + XCTAssertNotEqualObjects(dict1, dict4); + + [dict1 release]; + [dict1prime release]; + [dict2 release]; + [dict3 release]; + [dict4 release]; +} + +- (void)testCopy { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const int32_t kValues[] = { 700, 701, 702, 703 }; + GPBUInt32EnumDictionary *dict = + [[GPBUInt32EnumDictionary alloc] initWithEnums:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + + GPBUInt32EnumDictionary *dict2 = [dict copy]; + XCTAssertNotNil(dict2); + + // Should be new object but equal. + XCTAssertNotEqual(dict, dict2); + XCTAssertEqualObjects(dict, dict2); + XCTAssertTrue([dict2 isKindOfClass:[GPBUInt32EnumDictionary class]]); + + [dict2 release]; + [dict release]; +} + +- (void)testDictionaryFromDictionary { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const int32_t kValues[] = { 700, 701, 702, 703 }; + GPBUInt32EnumDictionary *dict = + [[GPBUInt32EnumDictionary alloc] initWithEnums:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + + GPBUInt32EnumDictionary *dict2 = + [[GPBUInt32EnumDictionary alloc] initWithDictionary:dict]; + XCTAssertNotNil(dict2); + + // Should be new pointer, but equal objects. + XCTAssertNotEqual(dict, dict2); + XCTAssertEqualObjects(dict, dict2); + [dict2 release]; + [dict release]; +} + +- (void)testAdds { + GPBUInt32EnumDictionary *dict = [[GPBUInt32EnumDictionary alloc] init]; + XCTAssertNotNil(dict); + + XCTAssertEqual(dict.count, 0U); + [dict setEnum:700 forKey:1U]; + XCTAssertEqual(dict.count, 1U); + + const uint32_t kKeys[] = { 2U, 3U, 4U }; + const int32_t kValues[] = { 701, 702, 703 }; + GPBUInt32EnumDictionary *dict2 = + [[GPBUInt32EnumDictionary alloc] initWithEnums:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict2); + [dict addRawEntriesFromDictionary:dict2]; + XCTAssertEqual(dict.count, 4U); + + int32_t value; + XCTAssertTrue([dict getEnum:NULL forKey:1U]); + XCTAssertTrue([dict getEnum:&value forKey:1U]); + XCTAssertEqual(value, 700); + XCTAssertTrue([dict getEnum:NULL forKey:2U]); + XCTAssertTrue([dict getEnum:&value forKey:2U]); + XCTAssertEqual(value, 701); + XCTAssertTrue([dict getEnum:NULL forKey:3U]); + XCTAssertTrue([dict getEnum:&value forKey:3U]); + XCTAssertEqual(value, 702); + XCTAssertTrue([dict getEnum:NULL forKey:4U]); + XCTAssertTrue([dict getEnum:&value forKey:4U]); + XCTAssertEqual(value, 703); + [dict2 release]; + [dict release]; +} + +- (void)testRemove { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const int32_t kValues[] = { 700, 701, 702, 703 }; + GPBUInt32EnumDictionary *dict = + [[GPBUInt32EnumDictionary alloc] initWithEnums:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 4U); + + [dict removeEnumForKey:2U]; + XCTAssertEqual(dict.count, 3U); + int32_t value; + XCTAssertTrue([dict getEnum:NULL forKey:1U]); + XCTAssertTrue([dict getEnum:&value forKey:1U]); + XCTAssertEqual(value, 700); + XCTAssertFalse([dict getEnum:NULL forKey:2U]); + XCTAssertTrue([dict getEnum:NULL forKey:3U]); + XCTAssertTrue([dict getEnum:&value forKey:3U]); + XCTAssertEqual(value, 702); + XCTAssertTrue([dict getEnum:NULL forKey:4U]); + XCTAssertTrue([dict getEnum:&value forKey:4U]); + XCTAssertEqual(value, 703); + + // Remove again does nothing. + [dict removeEnumForKey:2U]; + XCTAssertEqual(dict.count, 3U); + XCTAssertTrue([dict getEnum:NULL forKey:1U]); + XCTAssertTrue([dict getEnum:&value forKey:1U]); + XCTAssertEqual(value, 700); + XCTAssertFalse([dict getEnum:NULL forKey:2U]); + XCTAssertTrue([dict getEnum:NULL forKey:3U]); + XCTAssertTrue([dict getEnum:&value forKey:3U]); + XCTAssertEqual(value, 702); + XCTAssertTrue([dict getEnum:NULL forKey:4U]); + XCTAssertTrue([dict getEnum:&value forKey:4U]); + XCTAssertEqual(value, 703); + + [dict removeEnumForKey:4U]; + XCTAssertEqual(dict.count, 2U); + XCTAssertTrue([dict getEnum:NULL forKey:1U]); + XCTAssertTrue([dict getEnum:&value forKey:1U]); + XCTAssertEqual(value, 700); + XCTAssertFalse([dict getEnum:NULL forKey:2U]); + XCTAssertTrue([dict getEnum:NULL forKey:3U]); + XCTAssertTrue([dict getEnum:&value forKey:3U]); + XCTAssertEqual(value, 702); + XCTAssertFalse([dict getEnum:NULL forKey:4U]); + + [dict removeAll]; + XCTAssertEqual(dict.count, 0U); + XCTAssertFalse([dict getEnum:NULL forKey:1U]); + XCTAssertFalse([dict getEnum:NULL forKey:2U]); + XCTAssertFalse([dict getEnum:NULL forKey:3U]); + XCTAssertFalse([dict getEnum:NULL forKey:4U]); + [dict release]; +} + +- (void)testInplaceMutation { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const int32_t kValues[] = { 700, 701, 702, 703 }; + GPBUInt32EnumDictionary *dict = + [[GPBUInt32EnumDictionary alloc] initWithEnums:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 4U); + int32_t value; + XCTAssertTrue([dict getEnum:NULL forKey:1U]); + XCTAssertTrue([dict getEnum:&value forKey:1U]); + XCTAssertEqual(value, 700); + XCTAssertTrue([dict getEnum:NULL forKey:2U]); + XCTAssertTrue([dict getEnum:&value forKey:2U]); + XCTAssertEqual(value, 701); + XCTAssertTrue([dict getEnum:NULL forKey:3U]); + XCTAssertTrue([dict getEnum:&value forKey:3U]); + XCTAssertEqual(value, 702); + XCTAssertTrue([dict getEnum:NULL forKey:4U]); + XCTAssertTrue([dict getEnum:&value forKey:4U]); + XCTAssertEqual(value, 703); + + [dict setEnum:703 forKey:1U]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getEnum:NULL forKey:1U]); + XCTAssertTrue([dict getEnum:&value forKey:1U]); + XCTAssertEqual(value, 703); + XCTAssertTrue([dict getEnum:NULL forKey:2U]); + XCTAssertTrue([dict getEnum:&value forKey:2U]); + XCTAssertEqual(value, 701); + XCTAssertTrue([dict getEnum:NULL forKey:3U]); + XCTAssertTrue([dict getEnum:&value forKey:3U]); + XCTAssertEqual(value, 702); + XCTAssertTrue([dict getEnum:NULL forKey:4U]); + XCTAssertTrue([dict getEnum:&value forKey:4U]); + XCTAssertEqual(value, 703); + + [dict setEnum:701 forKey:4U]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getEnum:NULL forKey:1U]); + XCTAssertTrue([dict getEnum:&value forKey:1U]); + XCTAssertEqual(value, 703); + XCTAssertTrue([dict getEnum:NULL forKey:2U]); + XCTAssertTrue([dict getEnum:&value forKey:2U]); + XCTAssertEqual(value, 701); + XCTAssertTrue([dict getEnum:NULL forKey:3U]); + XCTAssertTrue([dict getEnum:&value forKey:3U]); + XCTAssertEqual(value, 702); + XCTAssertTrue([dict getEnum:NULL forKey:4U]); + XCTAssertTrue([dict getEnum:&value forKey:4U]); + XCTAssertEqual(value, 701); + + const uint32_t kKeys2[] = { 2U, 3U }; + const int32_t kValues2[] = { 702, 700 }; + GPBUInt32EnumDictionary *dict2 = + [[GPBUInt32EnumDictionary alloc] initWithEnums:kValues2 + forKeys:kKeys2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(dict2); + [dict addRawEntriesFromDictionary:dict2]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getEnum:NULL forKey:1U]); + XCTAssertTrue([dict getEnum:&value forKey:1U]); + XCTAssertEqual(value, 703); + XCTAssertTrue([dict getEnum:NULL forKey:2U]); + XCTAssertTrue([dict getEnum:&value forKey:2U]); + XCTAssertEqual(value, 702); + XCTAssertTrue([dict getEnum:NULL forKey:3U]); + XCTAssertTrue([dict getEnum:&value forKey:3U]); + XCTAssertEqual(value, 700); + XCTAssertTrue([dict getEnum:NULL forKey:4U]); + XCTAssertTrue([dict getEnum:&value forKey:4U]); + XCTAssertEqual(value, 701); + + [dict2 release]; + [dict release]; +} + +@end + +#pragma mark - UInt32 -> Enum (Unknown Enums) + +@interface GPBUInt32EnumDictionaryUnknownEnumTests : XCTestCase +@end + +@implementation GPBUInt32EnumDictionaryUnknownEnumTests + +- (void)testRawBasics { + const uint32_t kKeys[] = { 1U, 2U, 3U }; + const int32_t kValues[] = { 700, 801, 702 }; + GPBUInt32EnumDictionary *dict = + [[GPBUInt32EnumDictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 3U); + XCTAssertTrue(dict.validationFunc == TestingEnum_IsValidValue); // Pointer comparison + int32_t value; + XCTAssertTrue([dict getRawValue:NULL forKey:1U]); + XCTAssertTrue([dict getRawValue:&value forKey:1U]); + XCTAssertEqual(value, 700); + XCTAssertTrue([dict getEnum:NULL forKey:2U]); + XCTAssertTrue([dict getEnum:&value forKey:2U]); + XCTAssertEqual(value, kGPBUnrecognizedEnumeratorValue); + XCTAssertTrue([dict getRawValue:NULL forKey:2U]); + XCTAssertTrue([dict getRawValue:&value forKey:2U]); + XCTAssertEqual(value, 801); + XCTAssertTrue([dict getRawValue:NULL forKey:3U]); + XCTAssertTrue([dict getRawValue:&value forKey:3U]); + XCTAssertEqual(value, 702); + XCTAssertFalse([dict getRawValue:NULL forKey:4U]); + + __block NSUInteger idx = 0; + uint32_t *seenKeys = malloc(3 * sizeof(uint32_t)); + int32_t *seenValues = malloc(3 * sizeof(int32_t)); + [dict enumerateKeysAndEnumsUsingBlock:^(uint32_t aKey, int32_t aValue, BOOL *stop) { + XCTAssertLessThan(idx, 3U); + seenKeys[idx] = aKey; + seenValues[idx] = aValue; + XCTAssertNotEqual(stop, NULL); + ++idx; + }]; + for (int i = 0; i < 3; ++i) { + BOOL foundKey = NO; + for (int j = 0; (j < 3) && !foundKey; ++j) { + if (kKeys[i] == seenKeys[j]) { + foundKey = YES; + if (i == 1) { + XCTAssertEqual(kGPBUnrecognizedEnumeratorValue, seenValues[j], @"i = %d, j = %d", i, j); + } else { + XCTAssertEqual(kValues[i], seenValues[j], @"i = %d, j = %d", i, j); + } + } + } + XCTAssertTrue(foundKey, @"i = %d", i); + } + idx = 0; + [dict enumerateKeysAndRawValuesUsingBlock:^(uint32_t aKey, int32_t aValue, BOOL *stop) { + XCTAssertLessThan(idx, 3U); + seenKeys[idx] = aKey; + seenValues[idx] = aValue; + XCTAssertNotEqual(stop, NULL); + ++idx; + }]; + for (int i = 0; i < 3; ++i) { + BOOL foundKey = NO; + for (int j = 0; (j < 3) && !foundKey; ++j) { + if (kKeys[i] == seenKeys[j]) { + foundKey = YES; + XCTAssertEqual(kValues[i], seenValues[j], @"i = %d, j = %d", i, j); + } + } + XCTAssertTrue(foundKey, @"i = %d", i); + } + free(seenKeys); + free(seenValues); + + // Stopping the enumeration. + idx = 0; + [dict enumerateKeysAndRawValuesUsingBlock:^(uint32_t aKey, int32_t aValue, BOOL *stop) { + #pragma unused(aKey, aValue) + if (idx == 1) *stop = YES; + XCTAssertNotEqual(idx, 2U); + ++idx; + }]; + [dict release]; +} + +- (void)testEqualityWithUnknowns { + const uint32_t kKeys1[] = { 1U, 2U, 3U, 4U }; + const uint32_t kKeys2[] = { 2U, 1U, 4U }; + const int32_t kValues1[] = { 700, 801, 702 }; // Unknown + const int32_t kValues2[] = { 700, 803, 702 }; // Unknown + const int32_t kValues3[] = { 700, 801, 702, 803 }; // Unknowns + GPBUInt32EnumDictionary *dict1 = + [[GPBUInt32EnumDictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues1 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict1); + GPBUInt32EnumDictionary *dict1prime = + [[GPBUInt32EnumDictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues1 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict1prime); + GPBUInt32EnumDictionary *dict2 = + [[GPBUInt32EnumDictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues2 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(dict2); + GPBUInt32EnumDictionary *dict3 = + [[GPBUInt32EnumDictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues1 + forKeys:kKeys2 + count:GPBARRAYSIZE(kValues1)]; + XCTAssertNotNil(dict3); + GPBUInt32EnumDictionary *dict4 = + [[GPBUInt32EnumDictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues3 + forKeys:kKeys1 + count:GPBARRAYSIZE(kValues3)]; + XCTAssertNotNil(dict4); + + // 1/1Prime should be different objects, but equal. + XCTAssertNotEqual(dict1, dict1prime); + XCTAssertEqualObjects(dict1, dict1prime); + // Equal, so they must have same hash. + XCTAssertEqual([dict1 hash], [dict1prime hash]); + + // 2 is same keys, different values; not equal. + XCTAssertNotEqualObjects(dict1, dict2); + + // 3 is different keys, same values; not equal. + XCTAssertNotEqualObjects(dict1, dict3); + + // 4 extra pair; not equal + XCTAssertNotEqualObjects(dict1, dict4); + + [dict1 release]; + [dict1prime release]; + [dict2 release]; + [dict3 release]; + [dict4 release]; +} + +- (void)testCopyWithUnknowns { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const int32_t kValues[] = { 700, 801, 702, 803 }; // Unknown + GPBUInt32EnumDictionary *dict = + [[GPBUInt32EnumDictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + + GPBUInt32EnumDictionary *dict2 = [dict copy]; + XCTAssertNotNil(dict2); + + // Should be new pointer, but equal objects. + XCTAssertNotEqual(dict, dict2); + XCTAssertEqual(dict.validationFunc, dict2.validationFunc); // Pointer comparison + XCTAssertEqualObjects(dict, dict2); + + [dict2 release]; + [dict release]; +} + +- (void)testDictionaryFromDictionary { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const int32_t kValues[] = { 700, 801, 702, 803 }; // Unknowns + GPBUInt32EnumDictionary *dict = + [[GPBUInt32EnumDictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + + GPBUInt32EnumDictionary *dict2 = + [[GPBUInt32EnumDictionary alloc] initWithDictionary:dict]; + XCTAssertNotNil(dict2); + + // Should be new pointer, but equal objects. + XCTAssertNotEqual(dict, dict2); + XCTAssertEqualObjects(dict, dict2); + XCTAssertEqual(dict.validationFunc, dict2.validationFunc); // Pointer comparison + [dict2 release]; + [dict release]; +} + +- (void)testUnknownAdds { + GPBUInt32EnumDictionary *dict = + [[GPBUInt32EnumDictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue]; + XCTAssertNotNil(dict); + + XCTAssertEqual(dict.count, 0U); + XCTAssertThrowsSpecificNamed([dict setEnum:801 forKey:2U], // Unknown + NSException, NSInvalidArgumentException); + XCTAssertEqual(dict.count, 0U); + [dict setRawValue:801 forKey:2U]; // Unknown + XCTAssertEqual(dict.count, 1U); + + const uint32_t kKeys[] = { 1U, 3U, 4U }; + const int32_t kValues[] = { 700, 702, 803 }; // Unknown + GPBUInt32EnumDictionary *dict2 = + [[GPBUInt32EnumDictionary alloc] initWithEnums:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict2); + [dict addRawEntriesFromDictionary:dict2]; + XCTAssertEqual(dict.count, 4U); + + int32_t value; + XCTAssertTrue([dict getEnum:NULL forKey:1U]); + XCTAssertTrue([dict getEnum:&value forKey:1U]); + XCTAssertEqual(value, 700); + XCTAssertTrue([dict getEnum:NULL forKey:2U]); + XCTAssertTrue([dict getEnum:&value forKey:2U]); + XCTAssertEqual(value, kGPBUnrecognizedEnumeratorValue); + XCTAssertTrue([dict getRawValue:NULL forKey:2U]); + XCTAssertTrue([dict getRawValue:&value forKey:2U]); + XCTAssertEqual(value, 801); + XCTAssertTrue([dict getEnum:NULL forKey:3U]); + XCTAssertTrue([dict getEnum:&value forKey:3U]); + XCTAssertEqual(value, 702); + XCTAssertTrue([dict getEnum:NULL forKey:4U]); + XCTAssertTrue([dict getEnum:&value forKey:4U]); + XCTAssertEqual(value, kGPBUnrecognizedEnumeratorValue); + XCTAssertTrue([dict getRawValue:NULL forKey:4U]); + XCTAssertTrue([dict getRawValue:&value forKey:4U]); + XCTAssertEqual(value, 803); + [dict2 release]; + [dict release]; +} + +- (void)testUnknownRemove { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const int32_t kValues[] = { 700, 801, 702, 803 }; // Unknowns + GPBUInt32EnumDictionary *dict = + [[GPBUInt32EnumDictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 4U); + + [dict removeEnumForKey:2U]; + XCTAssertEqual(dict.count, 3U); + int32_t value; + XCTAssertTrue([dict getEnum:NULL forKey:1U]); + XCTAssertTrue([dict getEnum:&value forKey:1U]); + XCTAssertEqual(value, 700); + XCTAssertFalse([dict getEnum:NULL forKey:2U]); + XCTAssertTrue([dict getEnum:NULL forKey:3U]); + XCTAssertTrue([dict getEnum:&value forKey:3U]); + XCTAssertEqual(value, 702); + XCTAssertTrue([dict getRawValue:NULL forKey:4U]); + XCTAssertTrue([dict getRawValue:&value forKey:4U]); + XCTAssertEqual(value, 803); + + // Remove again does nothing. + [dict removeEnumForKey:2U]; + XCTAssertEqual(dict.count, 3U); + XCTAssertTrue([dict getEnum:NULL forKey:1U]); + XCTAssertTrue([dict getEnum:&value forKey:1U]); + XCTAssertEqual(value, 700); + XCTAssertFalse([dict getEnum:NULL forKey:2U]); + XCTAssertTrue([dict getEnum:NULL forKey:3U]); + XCTAssertTrue([dict getEnum:&value forKey:3U]); + XCTAssertEqual(value, 702); + XCTAssertTrue([dict getRawValue:NULL forKey:4U]); + XCTAssertTrue([dict getRawValue:&value forKey:4U]); + XCTAssertEqual(value, 803); + + [dict removeEnumForKey:4U]; + XCTAssertEqual(dict.count, 2U); + XCTAssertTrue([dict getEnum:NULL forKey:1U]); + XCTAssertTrue([dict getEnum:&value forKey:1U]); + XCTAssertEqual(value, 700); + XCTAssertFalse([dict getEnum:NULL forKey:2U]); + XCTAssertTrue([dict getEnum:NULL forKey:3U]); + XCTAssertTrue([dict getEnum:&value forKey:3U]); + XCTAssertEqual(value, 702); + XCTAssertFalse([dict getEnum:NULL forKey:4U]); + + [dict removeAll]; + XCTAssertEqual(dict.count, 0U); + XCTAssertFalse([dict getEnum:NULL forKey:1U]); + XCTAssertFalse([dict getEnum:NULL forKey:2U]); + XCTAssertFalse([dict getEnum:NULL forKey:3U]); + XCTAssertFalse([dict getEnum:NULL forKey:4U]); + [dict release]; +} + +- (void)testInplaceMutationUnknowns { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const int32_t kValues[] = { 700, 801, 702, 803 }; // Unknowns + GPBUInt32EnumDictionary *dict = + [[GPBUInt32EnumDictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 4U); + int32_t value; + XCTAssertTrue([dict getEnum:NULL forKey:1U]); + XCTAssertTrue([dict getEnum:&value forKey:1U]); + XCTAssertEqual(value, 700); + XCTAssertTrue([dict getRawValue:NULL forKey:2U]); + XCTAssertTrue([dict getRawValue:&value forKey:2U]); + XCTAssertEqual(value, 801); + XCTAssertTrue([dict getEnum:NULL forKey:3U]); + XCTAssertTrue([dict getEnum:&value forKey:3U]); + XCTAssertEqual(value, 702); + XCTAssertTrue([dict getRawValue:NULL forKey:4U]); + XCTAssertTrue([dict getRawValue:&value forKey:4U]); + XCTAssertEqual(value, 803); + + XCTAssertThrowsSpecificNamed([dict setEnum:803 forKey:1U], // Unknown + NSException, NSInvalidArgumentException); + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getEnum:NULL forKey:1U]); + XCTAssertTrue([dict getEnum:&value forKey:1U]); + XCTAssertEqual(value, 700); + XCTAssertTrue([dict getRawValue:NULL forKey:2U]); + XCTAssertTrue([dict getRawValue:&value forKey:2U]); + XCTAssertEqual(value, 801); + XCTAssertTrue([dict getEnum:NULL forKey:3U]); + XCTAssertTrue([dict getEnum:&value forKey:3U]); + XCTAssertEqual(value, 702); + XCTAssertTrue([dict getRawValue:NULL forKey:4U]); + XCTAssertTrue([dict getRawValue:&value forKey:4U]); + XCTAssertEqual(value, 803); + + [dict setRawValue:803 forKey:1U]; // Unknown + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getRawValue:NULL forKey:1U]); + XCTAssertTrue([dict getRawValue:&value forKey:1U]); + XCTAssertEqual(value, 803); + XCTAssertTrue([dict getRawValue:NULL forKey:2U]); + XCTAssertTrue([dict getRawValue:&value forKey:2U]); + XCTAssertEqual(value, 801); + XCTAssertTrue([dict getEnum:NULL forKey:3U]); + XCTAssertTrue([dict getEnum:&value forKey:3U]); + XCTAssertEqual(value, 702); + XCTAssertTrue([dict getRawValue:NULL forKey:4U]); + XCTAssertTrue([dict getRawValue:&value forKey:4U]); + XCTAssertEqual(value, 803); + + [dict setRawValue:700 forKey:4U]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getRawValue:NULL forKey:1U]); + XCTAssertTrue([dict getRawValue:&value forKey:1U]); + XCTAssertEqual(value, 803); + XCTAssertTrue([dict getRawValue:NULL forKey:2U]); + XCTAssertTrue([dict getRawValue:&value forKey:2U]); + XCTAssertEqual(value, 801); + XCTAssertTrue([dict getEnum:NULL forKey:3U]); + XCTAssertTrue([dict getEnum:&value forKey:3U]); + XCTAssertEqual(value, 702); + XCTAssertTrue([dict getEnum:NULL forKey:4U]); + XCTAssertTrue([dict getEnum:&value forKey:4U]); + XCTAssertEqual(value, 700); + + const uint32_t kKeys2[] = { 2U, 3U }; + const int32_t kValues2[] = { 702, 801 }; // Unknown + GPBUInt32EnumDictionary *dict2 = + [[GPBUInt32EnumDictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues2 + forKeys:kKeys2 + count:GPBARRAYSIZE(kValues2)]; + XCTAssertNotNil(dict2); + [dict addRawEntriesFromDictionary:dict2]; + XCTAssertEqual(dict.count, 4U); + XCTAssertTrue([dict getRawValue:NULL forKey:1U]); + XCTAssertTrue([dict getRawValue:&value forKey:1U]); + XCTAssertEqual(value, 803); + XCTAssertTrue([dict getEnum:NULL forKey:2U]); + XCTAssertTrue([dict getEnum:&value forKey:2U]); + XCTAssertEqual(value, 702); + XCTAssertTrue([dict getRawValue:NULL forKey:3U]); + XCTAssertTrue([dict getRawValue:&value forKey:3U]); + XCTAssertEqual(value, 801); + XCTAssertTrue([dict getEnum:NULL forKey:4U]); + XCTAssertTrue([dict getEnum:&value forKey:4U]); + XCTAssertEqual(value, 700); + + [dict2 release]; + [dict release]; +} + +- (void)testCopyUnknowns { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const int32_t kValues[] = { 700, 801, 702, 803 }; + GPBUInt32EnumDictionary *dict = + [[GPBUInt32EnumDictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues + forKeys:kKeys + count:GPBARRAYSIZE(kValues)]; + XCTAssertNotNil(dict); + + GPBUInt32EnumDictionary *dict2 = [dict copy]; + XCTAssertNotNil(dict2); + + // Should be new pointer, but equal objects. + XCTAssertNotEqual(dict, dict2); + XCTAssertEqualObjects(dict, dict2); + XCTAssertEqual(dict.validationFunc, dict2.validationFunc); // Pointer comparison + XCTAssertTrue([dict2 isKindOfClass:[GPBUInt32EnumDictionary class]]); + + [dict2 release]; + [dict release]; +} + +@end + +#pragma mark - UInt32 -> Object + +@interface GPBUInt32ObjectDictionaryTests : XCTestCase +@end + +@implementation GPBUInt32ObjectDictionaryTests + +- (void)testEmpty { + GPBUInt32ObjectDictionary *dict = [[GPBUInt32ObjectDictionary alloc] init]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 0U); + XCTAssertNil([dict objectForKey:1U]); + [dict enumerateKeysAndObjectsUsingBlock:^(uint32_t aKey, NSString* aObject, BOOL *stop) { + #pragma unused(aKey, aObject, stop) + XCTFail(@"Shouldn't get here!"); + }]; + [dict release]; +} + +- (void)testOne { + GPBUInt32ObjectDictionary *dict = [[GPBUInt32ObjectDictionary alloc] init]; + [dict setObject:@"abc" forKey:1U]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 1U); + XCTAssertEqualObjects([dict objectForKey:1U], @"abc"); + XCTAssertNil([dict objectForKey:2U]); + [dict enumerateKeysAndObjectsUsingBlock:^(uint32_t aKey, NSString* aObject, BOOL *stop) { + XCTAssertEqual(aKey, 1U); + XCTAssertEqualObjects(aObject, @"abc"); + XCTAssertNotEqual(stop, NULL); + }]; + [dict release]; +} + +- (void)testBasics { + const uint32_t kKeys[] = { 1U, 2U, 3U }; + const NSString* kObjects[] = { @"abc", @"def", @"ghi" }; + GPBUInt32ObjectDictionary *dict = + [[GPBUInt32ObjectDictionary alloc] initWithObjects:kObjects + forKeys:kKeys + count:GPBARRAYSIZE(kObjects)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 3U); + XCTAssertEqualObjects([dict objectForKey:1U], @"abc"); + XCTAssertEqualObjects([dict objectForKey:2U], @"def"); + XCTAssertEqualObjects([dict objectForKey:3U], @"ghi"); + XCTAssertNil([dict objectForKey:4U]); + + __block NSUInteger idx = 0; + uint32_t *seenKeys = malloc(3 * sizeof(uint32_t)); + NSString* *seenObjects = malloc(3 * sizeof(NSString*)); + [dict enumerateKeysAndObjectsUsingBlock:^(uint32_t aKey, NSString* aObject, BOOL *stop) { + XCTAssertLessThan(idx, 3U); + seenKeys[idx] = aKey; + seenObjects[idx] = aObject; + XCTAssertNotEqual(stop, NULL); + ++idx; + }]; + for (int i = 0; i < 3; ++i) { + BOOL foundKey = NO; + for (int j = 0; (j < 3) && !foundKey; ++j) { + if (kKeys[i] == seenKeys[j]) { + foundKey = YES; + XCTAssertEqualObjects(kObjects[i], seenObjects[j], @"i = %d, j = %d", i, j); + } + } + XCTAssertTrue(foundKey, @"i = %d", i); + } + free(seenKeys); + free(seenObjects); + + // Stopping the enumeration. + idx = 0; + [dict enumerateKeysAndObjectsUsingBlock:^(uint32_t aKey, NSString* aObject, BOOL *stop) { + #pragma unused(aKey, aObject) + if (idx == 1) *stop = YES; + XCTAssertNotEqual(idx, 2U); + ++idx; + }]; + [dict release]; +} + +- (void)testEquality { + const uint32_t kKeys1[] = { 1U, 2U, 3U, 4U }; + const uint32_t kKeys2[] = { 2U, 1U, 4U }; + const NSString* kObjects1[] = { @"abc", @"def", @"ghi" }; + const NSString* kObjects2[] = { @"abc", @"jkl", @"ghi" }; + const NSString* kObjects3[] = { @"abc", @"def", @"ghi", @"jkl" }; + GPBUInt32ObjectDictionary *dict1 = + [[GPBUInt32ObjectDictionary alloc] initWithObjects:kObjects1 + forKeys:kKeys1 + count:GPBARRAYSIZE(kObjects1)]; + XCTAssertNotNil(dict1); + GPBUInt32ObjectDictionary *dict1prime = + [[GPBUInt32ObjectDictionary alloc] initWithObjects:kObjects1 + forKeys:kKeys1 + count:GPBARRAYSIZE(kObjects1)]; + XCTAssertNotNil(dict1prime); + GPBUInt32ObjectDictionary *dict2 = + [[GPBUInt32ObjectDictionary alloc] initWithObjects:kObjects2 + forKeys:kKeys1 + count:GPBARRAYSIZE(kObjects2)]; + XCTAssertNotNil(dict2); + GPBUInt32ObjectDictionary *dict3 = + [[GPBUInt32ObjectDictionary alloc] initWithObjects:kObjects1 + forKeys:kKeys2 + count:GPBARRAYSIZE(kObjects1)]; + XCTAssertNotNil(dict3); + GPBUInt32ObjectDictionary *dict4 = + [[GPBUInt32ObjectDictionary alloc] initWithObjects:kObjects3 + forKeys:kKeys1 + count:GPBARRAYSIZE(kObjects3)]; + XCTAssertNotNil(dict4); + + // 1/1Prime should be different objects, but equal. + XCTAssertNotEqual(dict1, dict1prime); + XCTAssertEqualObjects(dict1, dict1prime); + // Equal, so they must have same hash. + XCTAssertEqual([dict1 hash], [dict1prime hash]); + + // 2 is same keys, different objects; not equal. + XCTAssertNotEqualObjects(dict1, dict2); + + // 3 is different keys, same objects; not equal. + XCTAssertNotEqualObjects(dict1, dict3); + + // 4 extra pair; not equal + XCTAssertNotEqualObjects(dict1, dict4); + + [dict1 release]; + [dict1prime release]; + [dict2 release]; + [dict3 release]; + [dict4 release]; +} + +- (void)testCopy { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const NSString* kObjects[] = { @"abc", @"def", @"ghi", @"jkl" }; + GPBUInt32ObjectDictionary *dict = + [[GPBUInt32ObjectDictionary alloc] initWithObjects:kObjects + forKeys:kKeys + count:GPBARRAYSIZE(kObjects)]; + XCTAssertNotNil(dict); + + GPBUInt32ObjectDictionary *dict2 = [dict copy]; + XCTAssertNotNil(dict2); + + // Should be new object but equal. + XCTAssertNotEqual(dict, dict2); + XCTAssertEqualObjects(dict, dict2); + XCTAssertTrue([dict2 isKindOfClass:[GPBUInt32ObjectDictionary class]]); + + [dict2 release]; + [dict release]; +} + +- (void)testDictionaryFromDictionary { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const NSString* kObjects[] = { @"abc", @"def", @"ghi", @"jkl" }; + GPBUInt32ObjectDictionary *dict = + [[GPBUInt32ObjectDictionary alloc] initWithObjects:kObjects + forKeys:kKeys + count:GPBARRAYSIZE(kObjects)]; + XCTAssertNotNil(dict); + + GPBUInt32ObjectDictionary *dict2 = + [[GPBUInt32ObjectDictionary alloc] initWithDictionary:dict]; + XCTAssertNotNil(dict2); + + // Should be new pointer, but equal objects. + XCTAssertNotEqual(dict, dict2); + XCTAssertEqualObjects(dict, dict2); + [dict2 release]; + [dict release]; +} + +- (void)testAdds { + GPBUInt32ObjectDictionary *dict = [[GPBUInt32ObjectDictionary alloc] init]; + XCTAssertNotNil(dict); + + XCTAssertEqual(dict.count, 0U); + [dict setObject:@"abc" forKey:1U]; + XCTAssertEqual(dict.count, 1U); + + const uint32_t kKeys[] = { 2U, 3U, 4U }; + const NSString* kObjects[] = { @"def", @"ghi", @"jkl" }; + GPBUInt32ObjectDictionary *dict2 = + [[GPBUInt32ObjectDictionary alloc] initWithObjects:kObjects + forKeys:kKeys + count:GPBARRAYSIZE(kObjects)]; + XCTAssertNotNil(dict2); + [dict addEntriesFromDictionary:dict2]; + XCTAssertEqual(dict.count, 4U); + + XCTAssertEqualObjects([dict objectForKey:1U], @"abc"); + XCTAssertEqualObjects([dict objectForKey:2U], @"def"); + XCTAssertEqualObjects([dict objectForKey:3U], @"ghi"); + XCTAssertEqualObjects([dict objectForKey:4U], @"jkl"); + [dict2 release]; + [dict release]; +} + +- (void)testRemove { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const NSString* kObjects[] = { @"abc", @"def", @"ghi", @"jkl" }; + GPBUInt32ObjectDictionary *dict = + [[GPBUInt32ObjectDictionary alloc] initWithObjects:kObjects + forKeys:kKeys + count:GPBARRAYSIZE(kObjects)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 4U); + + [dict removeObjectForKey:2U]; + XCTAssertEqual(dict.count, 3U); + XCTAssertEqualObjects([dict objectForKey:1U], @"abc"); + XCTAssertNil([dict objectForKey:2U]); + XCTAssertEqualObjects([dict objectForKey:3U], @"ghi"); + XCTAssertEqualObjects([dict objectForKey:4U], @"jkl"); + + // Remove again does nothing. + [dict removeObjectForKey:2U]; + XCTAssertEqual(dict.count, 3U); + XCTAssertEqualObjects([dict objectForKey:1U], @"abc"); + XCTAssertNil([dict objectForKey:2U]); + XCTAssertEqualObjects([dict objectForKey:3U], @"ghi"); + XCTAssertEqualObjects([dict objectForKey:4U], @"jkl"); + + [dict removeObjectForKey:4U]; + XCTAssertEqual(dict.count, 2U); + XCTAssertEqualObjects([dict objectForKey:1U], @"abc"); + XCTAssertNil([dict objectForKey:2U]); + XCTAssertEqualObjects([dict objectForKey:3U], @"ghi"); + XCTAssertNil([dict objectForKey:4U]); + + [dict removeAll]; + XCTAssertEqual(dict.count, 0U); + XCTAssertNil([dict objectForKey:1U]); + XCTAssertNil([dict objectForKey:2U]); + XCTAssertNil([dict objectForKey:3U]); + XCTAssertNil([dict objectForKey:4U]); + [dict release]; +} + +- (void)testInplaceMutation { + const uint32_t kKeys[] = { 1U, 2U, 3U, 4U }; + const NSString* kObjects[] = { @"abc", @"def", @"ghi", @"jkl" }; + GPBUInt32ObjectDictionary *dict = + [[GPBUInt32ObjectDictionary alloc] initWithObjects:kObjects + forKeys:kKeys + count:GPBARRAYSIZE(kObjects)]; + XCTAssertNotNil(dict); + XCTAssertEqual(dict.count, 4U); + XCTAssertEqualObjects([dict objectForKey:1U], @"abc"); + XCTAssertEqualObjects([dict objectForKey:2U], @"def"); + XCTAssertEqualObjects([dict objectForKey:3U], @"ghi"); + XCTAssertEqualObjects([dict objectForKey:4U], @"jkl"); + + [dict setObject:@"jkl" forKey:1U]; + XCTAssertEqual(dict.count, 4U); + XCTAssertEqualObjects([dict objectForKey:1U], @"jkl"); + XCTAssertEqualObjects([dict objectForKey:2U], @"def"); + XCTAssertEqualObjects([dict objectForKey:3U], @"ghi"); + XCTAssertEqualObjects([dict objectForKey:4U], @"jkl"); + + [dict setObject:@"def" forKey:4U]; + XCTAssertEqual(dict.count, 4U); + XCTAssertEqualObjects([dict objectForKey:1U], @"jkl"); + XCTAssertEqualObjects([dict objectForKey:2U], @"def"); + XCTAssertEqualObjects([dict objectForKey:3U], @"ghi"); + XCTAssertEqualObjects([dict objectForKey:4U], @"def"); + + const uint32_t kKeys2[] = { 2U, 3U }; + const NSString* kObjects2[] = { @"ghi", @"abc" }; + GPBUInt32ObjectDictionary *dict2 = + [[GPBUInt32ObjectDictionary alloc] initWithObjects:kObjects2 + forKeys:kKeys2 + count:GPBARRAYSIZE(kObjects2)]; + XCTAssertNotNil(dict2); + [dict addEntriesFromDictionary:dict2]; + XCTAssertEqual(dict.count, 4U); + XCTAssertEqualObjects([dict objectForKey:1U], @"jkl"); + XCTAssertEqualObjects([dict objectForKey:2U], @"ghi"); + XCTAssertEqualObjects([dict objectForKey:3U], @"abc"); + XCTAssertEqualObjects([dict objectForKey:4U], @"def"); + + [dict2 release]; + [dict release]; +} + +@end + +// clang-format on +//%PDDM-EXPAND-END TEST_FOR_POD_KEY(UInt32, uint32_t, 1U, 2U, 3U, 4U) + diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/GPBDictionaryTests.pddm b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/GPBDictionaryTests.pddm new file mode 100644 index 0000000..17f12c2 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/GPBDictionaryTests.pddm @@ -0,0 +1,1048 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. + +//%PDDM-DEFINE TEST_FOR_POD_KEY(KEY_NAME, KEY_TYPE, KEY1, KEY2, KEY3, KEY4) +//%TESTS_FOR_POD_VALUES(KEY_NAME, KEY_TYPE, , , KEY1, KEY2, KEY3, KEY4) +//%TESTS_FOR_POD_KEY_OBJECT_VALUE(KEY_NAME, KEY_TYPE, KEY1, KEY2, KEY3, KEY4, Object, NSString*, @"abc", @"def", @"ghi", @"jkl") + +//%PDDM-DEFINE TESTS_FOR_POD_VALUES(KEY_NAME, KEY_TYPE, KisP, KSUFFIX, KEY1, KEY2, KEY3, KEY4) +//%TEST_HELPERS(KEY_NAME, KEY_TYPE, KisP) +//%TESTS_FOR_POD_VALUE(KEY_NAME, KEY_TYPE, KisP, KSUFFIX, KEY1, KEY2, KEY3, KEY4, UInt32, uint32_t, , 100U, 101U, 102U, 103U) +//%TESTS_FOR_POD_VALUE(KEY_NAME, KEY_TYPE, KisP, KSUFFIX, KEY1, KEY2, KEY3, KEY4, Int32, int32_t, , 200, 201, 202, 203) +//%TESTS_FOR_POD_VALUE(KEY_NAME, KEY_TYPE, KisP, KSUFFIX, KEY1, KEY2, KEY3, KEY4, UInt64, uint64_t, , 300U, 301U, 302U, 303U) +//%TESTS_FOR_POD_VALUE(KEY_NAME, KEY_TYPE, KisP, KSUFFIX, KEY1, KEY2, KEY3, KEY4, Int64, int64_t, , 400, 401, 402, 403) +//%TESTS_FOR_POD_VALUE(KEY_NAME, KEY_TYPE, KisP, KSUFFIX, KEY1, KEY2, KEY3, KEY4, Bool, BOOL, , YES, YES, NO, NO) +//%TESTS_FOR_POD_VALUE(KEY_NAME, KEY_TYPE, KisP, KSUFFIX, KEY1, KEY2, KEY3, KEY4, Float, float, , 500.f, 501.f, 502.f, 503.f) +//%TESTS_FOR_POD_VALUE(KEY_NAME, KEY_TYPE, KisP, KSUFFIX, KEY1, KEY2, KEY3, KEY4, Double, double, , 600., 601., 602., 603.) +//%TESTS_FOR_POD_VALUE(KEY_NAME, KEY_TYPE, KisP, KSUFFIX, KEY1, KEY2, KEY3, KEY4, Enum, int32_t, Raw, 700, 701, 702, 703) +//%TESTS_FOR_ENUM_VALUE_RAW_ADDITIONS(KEY_NAME, KEY_TYPE, KisP, KSUFFIX, KEY1, KEY2, KEY3, KEY4) + +//%PDDM-DEFINE TESTS_FOR_POD_VALUE(KEY_NAME, KEY_TYPE, KisP, KSUFFIX, KEY1, KEY2, KEY3, KEY4, VALUE_NAME, VALUE_TYPE, VACCESSOR, VAL1, VAL2, VAL3, VAL4) +//%TESTS_COMMON(KEY_NAME, KEY_TYPE, KisP, KSUFFIX, KEY1, KEY2, KEY3, KEY4, VALUE_NAME, VALUE_TYPE, , value, POD, VACCESSOR, VAL1, VAL2, VAL3, VAL4) + +//%PDDM-DEFINE TESTS_FOR_POD_KEY_OBJECT_VALUE(KEY_NAME, KEY_TYPE, KEY1, KEY2, KEY3, KEY4, VALUE_NAME, VALUE_TYPE, VAL1, VAL2, VAL3, VAL4) +//%TESTS_COMMON(KEY_NAME, KEY_TYPE, , , KEY1, KEY2, KEY3, KEY4, VALUE_NAME, VALUE_TYPE, Objects, object, OBJECT, , VAL1, VAL2, VAL3, VAL4) + +//%PDDM-DEFINE DICTIONARY_CLASS_DECLPOD(KEY_NAME, VALUE_NAME, VALUE_TYPE) +//%GPB##KEY_NAME##VALUE_NAME##Dictionary +//%PDDM-DEFINE DICTIONARY_CLASS_DECLEnum(KEY_NAME, VALUE_NAME, VALUE_TYPE) +//%GPB##KEY_NAME##VALUE_NAME##Dictionary +//%PDDM-DEFINE DICTIONARY_CLASS_DECLOBJECT(KEY_NAME, VALUE_NAME, VALUE_TYPE) +//%GPB##KEY_NAME##VALUE_NAME##Dictionary + +//%PDDM-DEFINE TESTS_COMMON(KEY_NAME, KEY_TYPE, KisP, KSUFFIX, KEY1, KEY2, KEY3, KEY4, VALUE_NAME, VALUE_TYPE, VSUFFIX, VNAME, VHELPER, VACCESSOR, VAL1, VAL2, VAL3, VAL4) +//%#pragma mark - KEY_NAME -> VALUE_NAME +//% +//%@interface GPB##KEY_NAME##VALUE_NAME##DictionaryTests : XCTestCase +//%@end +//% +//%@implementation GPB##KEY_NAME##VALUE_NAME##DictionaryTests +//% +//%- (void)testEmpty { +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] init]; +//% XCTAssertNotNil(dict); +//% XCTAssertEqual(dict.count, 0U); +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY1) +//% [dict enumerateKeysAnd##VALUE_NAME$u##sUsingBlock:^(KEY_TYPE KisP##aKey, VALUE_TYPE a##VNAME$u, BOOL *stop) { +//% #pragma unused(aKey, a##VNAME$u, stop) +//% XCTFail(@"Shouldn't get here!"); +//% }]; +//% [dict release]; +//%} +//% +//%- (void)testOne { +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] init]; +//% [dict set##VALUE_NAME$u##:VAL1 forKey:KEY1]; +//% XCTAssertNotNil(dict); +//% XCTAssertEqual(dict.count, 1U); +//%DECLARE_VALUE_STORAGE##VHELPER(VALUE_TYPE, VNAME)TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL1) +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY2) +//% [dict enumerateKeysAnd##VALUE_NAME$u##sUsingBlock:^(KEY_TYPE KisP##aKey, VALUE_TYPE a##VNAME$u, BOOL *stop) { +//% XCTAssertEqual##KSUFFIX(aKey, KEY1); +//% XCTAssertEqual##VSUFFIX(a##VNAME$u, VAL1); +//% XCTAssertNotEqual(stop, NULL); +//% }]; +//% [dict release]; +//%} +//% +//%- (void)testBasics { +//% const KEY_TYPE KisP##kKeys[] = { KEY1, KEY2, KEY3 }; +//% const VALUE_TYPE k##VNAME$u##s[] = { VAL1, VAL2, VAL3 }; +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME$u##s:k##VNAME$u##s +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s)]; +//% XCTAssertNotNil(dict); +//% XCTAssertEqual(dict.count, 3U); +//%DECLARE_VALUE_STORAGE##VHELPER(VALUE_TYPE, VNAME)TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL1) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY2, VAL2) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY3, VAL3) +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY4) +//% +//% __block NSUInteger idx = 0; +//% KEY_TYPE KisP##*seenKeys = malloc(3 * sizeof(KEY_TYPE##KisP)); +//% VALUE_TYPE *seen##VNAME$u##s = malloc(3 * sizeof(VALUE_TYPE)); +//% [dict enumerateKeysAnd##VALUE_NAME$u##sUsingBlock:^(KEY_TYPE KisP##aKey, VALUE_TYPE a##VNAME$u, BOOL *stop) { +//% XCTAssertLessThan(idx, 3U); +//% seenKeys[idx] = aKey; +//% seen##VNAME$u##s[idx] = a##VNAME$u##; +//% XCTAssertNotEqual(stop, NULL); +//% ++idx; +//% }]; +//% for (int i = 0; i < 3; ++i) { +//% BOOL foundKey = NO; +//% for (int j = 0; (j < 3) && !foundKey; ++j) { +//% if (COMPARE_KEYS##KSUFFIX(kKeys[i], seenKeys[j])) { +//% foundKey = YES; +//% XCTAssertEqual##VSUFFIX(k##VNAME$u##s[i], seen##VNAME$u##s[j], @"i = %d, j = %d", i, j); +//% } +//% } +//% XCTAssertTrue(foundKey, @"i = %d", i); +//% } +//% free(seenKeys); +//% free(seen##VNAME$u##s); +//% +//% // Stopping the enumeration. +//% idx = 0; +//% [dict enumerateKeysAnd##VALUE_NAME$u##sUsingBlock:^(KEY_TYPE KisP##aKey, VALUE_TYPE a##VNAME$u, BOOL *stop) { +//% #pragma unused(aKey, a##VNAME$u) +//% if (idx == 1) *stop = YES; +//% XCTAssertNotEqual(idx, 2U); +//% ++idx; +//% }]; +//% [dict release]; +//%} +//% +//%- (void)testEquality { +//% const KEY_TYPE KisP##kKeys1[] = { KEY1, KEY2, KEY3, KEY4 }; +//% const KEY_TYPE KisP##kKeys2[] = { KEY2, KEY1, KEY4 }; +//% const VALUE_TYPE k##VNAME$u##s1[] = { VAL1, VAL2, VAL3 }; +//% const VALUE_TYPE k##VNAME$u##s2[] = { VAL1, VAL4, VAL3 }; +//% const VALUE_TYPE k##VNAME$u##s3[] = { VAL1, VAL2, VAL3, VAL4 }; +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict1 = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME##s:k##VNAME$u##s1 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys1 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s1)]; +//% XCTAssertNotNil(dict1); +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict1prime = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME##s:k##VNAME$u##s1 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys1 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s1)]; +//% XCTAssertNotNil(dict1prime); +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict2 = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME##s:k##VNAME$u##s2 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys1 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s2)]; +//% XCTAssertNotNil(dict2); +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict3 = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME##s:k##VNAME$u##s1 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys2 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s1)]; +//% XCTAssertNotNil(dict3); +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict4 = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME##s:k##VNAME$u##s3 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys1 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s3)]; +//% XCTAssertNotNil(dict4); +//% +//% // 1/1Prime should be different objects, but equal. +//% XCTAssertNotEqual(dict1, dict1prime); +//% XCTAssertEqualObjects(dict1, dict1prime); +//% // Equal, so they must have same hash. +//% XCTAssertEqual([dict1 hash], [dict1prime hash]); +//% +//% // 2 is same keys, different ##VNAME##s; not equal. +//% XCTAssertNotEqualObjects(dict1, dict2); +//% +//% // 3 is different keys, same ##VNAME##s; not equal. +//% XCTAssertNotEqualObjects(dict1, dict3); +//% +//% // 4 extra pair; not equal +//% XCTAssertNotEqualObjects(dict1, dict4); +//% +//% [dict1 release]; +//% [dict1prime release]; +//% [dict2 release]; +//% [dict3 release]; +//% [dict4 release]; +//%} +//% +//%- (void)testCopy { +//% const KEY_TYPE KisP##kKeys[] = { KEY1, KEY2, KEY3, KEY4 }; +//% const VALUE_TYPE k##VNAME$u##s[] = { VAL1, VAL2, VAL3, VAL4 }; +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME##s:k##VNAME$u##s +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s)]; +//% XCTAssertNotNil(dict); +//% +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict2 = [dict copy]; +//% XCTAssertNotNil(dict2); +//% +//% // Should be new object but equal. +//% XCTAssertNotEqual(dict, dict2); +//% XCTAssertEqualObjects(dict, dict2); +//% XCTAssertTrue([dict2 isKindOfClass:[GPB##KEY_NAME##VALUE_NAME##Dictionary class]]); +//% +//% [dict2 release]; +//% [dict release]; +//%} +//% +//%- (void)testDictionaryFromDictionary { +//% const KEY_TYPE KisP##kKeys[] = { KEY1, KEY2, KEY3, KEY4 }; +//% const VALUE_TYPE k##VNAME$u##s[] = { VAL1, VAL2, VAL3, VAL4 }; +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME##s:k##VNAME$u##s +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s)]; +//% XCTAssertNotNil(dict); +//% +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict2 = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithDictionary:dict]; +//% XCTAssertNotNil(dict2); +//% +//% // Should be new pointer, but equal objects. +//% XCTAssertNotEqual(dict, dict2); +//% XCTAssertEqualObjects(dict, dict2); +//% [dict2 release]; +//% [dict release]; +//%} +//% +//%- (void)testAdds { +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] init]; +//% XCTAssertNotNil(dict); +//% +//% XCTAssertEqual(dict.count, 0U); +//% [dict set##VALUE_NAME##:VAL1 forKey:KEY1]; +//% XCTAssertEqual(dict.count, 1U); +//% +//% const KEY_TYPE KisP##kKeys[] = { KEY2, KEY3, KEY4 }; +//% const VALUE_TYPE k##VNAME$u##s[] = { VAL2, VAL3, VAL4 }; +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict2 = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME##s:k##VNAME$u##s +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s)]; +//% XCTAssertNotNil(dict2); +//% [dict add##VACCESSOR##EntriesFromDictionary:dict2]; +//% XCTAssertEqual(dict.count, 4U); +//% +//%DECLARE_VALUE_STORAGE##VHELPER(VALUE_TYPE, VNAME)TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL1) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY2, VAL2) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY3, VAL3) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY4, VAL4) +//% [dict2 release]; +//% [dict release]; +//%} +//% +//%- (void)testRemove { +//% const KEY_TYPE KisP##kKeys[] = { KEY1, KEY2, KEY3, KEY4 }; +//% const VALUE_TYPE k##VNAME$u##s[] = { VAL1, VAL2, VAL3, VAL4 }; +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME##s:k##VNAME$u##s +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s)]; +//% XCTAssertNotNil(dict); +//% XCTAssertEqual(dict.count, 4U); +//% +//% [dict remove##VALUE_NAME##ForKey:KEY2]; +//% XCTAssertEqual(dict.count, 3U); +//%DECLARE_VALUE_STORAGE##VHELPER(VALUE_TYPE, VNAME)TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL1) +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY2) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY3, VAL3) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY4, VAL4) +//% +//% // Remove again does nothing. +//% [dict remove##VALUE_NAME##ForKey:KEY2]; +//% XCTAssertEqual(dict.count, 3U); +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL1) +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY2) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY3, VAL3) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY4, VAL4) +//% +//% [dict remove##VALUE_NAME##ForKey:KEY4]; +//% XCTAssertEqual(dict.count, 2U); +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL1) +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY2) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY3, VAL3) +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY4) +//% +//% [dict removeAll]; +//% XCTAssertEqual(dict.count, 0U); +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY1) +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY2) +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY3) +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY4) +//% [dict release]; +//%} +//% +//%- (void)testInplaceMutation { +//% const KEY_TYPE KisP##kKeys[] = { KEY1, KEY2, KEY3, KEY4 }; +//% const VALUE_TYPE k##VNAME$u##s[] = { VAL1, VAL2, VAL3, VAL4 }; +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME##s:k##VNAME$u##s +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s)]; +//% XCTAssertNotNil(dict); +//% XCTAssertEqual(dict.count, 4U); +//%DECLARE_VALUE_STORAGE##VHELPER(VALUE_TYPE, VNAME)TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL1) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY2, VAL2) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY3, VAL3) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY4, VAL4) +//% +//% [dict set##VALUE_NAME##:VAL4 forKey:KEY1]; +//% XCTAssertEqual(dict.count, 4U); +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL4) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY2, VAL2) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY3, VAL3) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY4, VAL4) +//% +//% [dict set##VALUE_NAME##:VAL2 forKey:KEY4]; +//% XCTAssertEqual(dict.count, 4U); +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL4) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY2, VAL2) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY3, VAL3) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY4, VAL2) +//% +//% const KEY_TYPE KisP##kKeys2[] = { KEY2, KEY3 }; +//% const VALUE_TYPE k##VNAME$u##s2[] = { VAL3, VAL1 }; +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict2 = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME##s:k##VNAME$u##s2 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys2 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s2)]; +//% XCTAssertNotNil(dict2); +//% [dict add##VACCESSOR##EntriesFromDictionary:dict2]; +//% XCTAssertEqual(dict.count, 4U); +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL4) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY2, VAL3) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY3, VAL1) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY4, VAL2) +//% +//% [dict2 release]; +//% [dict release]; +//%} +//% +//%@end +//% + +//%PDDM-DEFINE TESTS_FOR_ENUM_VALUE_RAW_ADDITIONS(KEY_NAME, KEY_TYPE, KisP, KSUFFIX, KEY1, KEY2, KEY3, KEY4) +//%TESTS_FOR_ENUM_VALUE_RAW_ADDITIONS2(KEY_NAME, KEY_TYPE, KisP, KSUFFIX, KEY1, KEY2, KEY3, KEY4, Enum, int32_t, , POD, 700, 801, 702, 803) +//%PDDM-DEFINE TESTS_FOR_ENUM_VALUE_RAW_ADDITIONS2(KEY_NAME, KEY_TYPE, KisP, KSUFFIX, KEY1, KEY2, KEY3, KEY4, VALUE_NAME, VALUE_TYPE, VSUFFIX, VHELPER, VAL1, VAL2, VAL3, VAL4) +//%#pragma mark - KEY_NAME -> VALUE_NAME (Unknown Enums) +//% +//%@interface GPB##KEY_NAME##VALUE_NAME##DictionaryUnknownEnumTests : XCTestCase +//%@end +//% +//%@implementation GPB##KEY_NAME##VALUE_NAME##DictionaryUnknownEnumTests +//% +//%- (void)testRawBasics { +//% const KEY_TYPE KisP##kKeys[] = { KEY1, KEY2, KEY3 }; +//% const VALUE_TYPE kValues[] = { VAL1, VAL2, VAL3 }; +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue +//% KEY_NAME$S VALUE_NAME$S rawValues:kValues +//% KEY_NAME$S VALUE_NAME$S forKeys:kKeys +//% KEY_NAME$S VALUE_NAME$S count:GPBARRAYSIZE(kValues)]; +//% XCTAssertNotNil(dict); +//% XCTAssertEqual(dict.count, 3U); +//% XCTAssertTrue(dict.validationFunc == TestingEnum_IsValidValue); // Pointer comparison +//%DECLARE_VALUE_STORAGE##VHELPER(VALUE_TYPE, value)TEST_RAW_VALUE##VHELPER(dict, value, KEY1, VAL1) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, value, KEY2, kGPBUnrecognizedEnumeratorValue) +//%TEST_RAW_VALUE##VHELPER(dict, value, KEY2, VAL2) +//%TEST_RAW_VALUE##VHELPER(dict, value, KEY3, VAL3) +//%RAW_VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY4) +//% +//% __block NSUInteger idx = 0; +//% KEY_TYPE KisP##*seenKeys = malloc(3 * sizeof(KEY_TYPE##KisP)); +//% VALUE_TYPE *seenValues = malloc(3 * sizeof(VALUE_TYPE)); +//% [dict enumerateKeysAndEnumsUsingBlock:^(KEY_TYPE KisP##aKey, VALUE_TYPE aValue, BOOL *stop) { +//% XCTAssertLessThan(idx, 3U); +//% seenKeys[idx] = aKey; +//% seenValues[idx] = aValue; +//% XCTAssertNotEqual(stop, NULL); +//% ++idx; +//% }]; +//% for (int i = 0; i < 3; ++i) { +//% BOOL foundKey = NO; +//% for (int j = 0; (j < 3) && !foundKey; ++j) { +//% if (COMPARE_KEYS##KSUFFIX(kKeys[i], seenKeys[j])) { +//% foundKey = YES; +//% if (i == 1) { +//% XCTAssertEqual##VSUFFIX(kGPBUnrecognizedEnumeratorValue, seenValues[j], @"i = %d, j = %d", i, j); +//% } else { +//% XCTAssertEqual##VSUFFIX(kValues[i], seenValues[j], @"i = %d, j = %d", i, j); +//% } +//% } +//% } +//% XCTAssertTrue(foundKey, @"i = %d", i); +//% } +//% idx = 0; +//% [dict enumerateKeysAndRawValuesUsingBlock:^(KEY_TYPE KisP##aKey, VALUE_TYPE aValue, BOOL *stop) { +//% XCTAssertLessThan(idx, 3U); +//% seenKeys[idx] = aKey; +//% seenValues[idx] = aValue; +//% XCTAssertNotEqual(stop, NULL); +//% ++idx; +//% }]; +//% for (int i = 0; i < 3; ++i) { +//% BOOL foundKey = NO; +//% for (int j = 0; (j < 3) && !foundKey; ++j) { +//% if (COMPARE_KEYS##KSUFFIX(kKeys[i], seenKeys[j])) { +//% foundKey = YES; +//% XCTAssertEqual##VSUFFIX(kValues[i], seenValues[j], @"i = %d, j = %d", i, j); +//% } +//% } +//% XCTAssertTrue(foundKey, @"i = %d", i); +//% } +//% free(seenKeys); +//% free(seenValues); +//% +//% // Stopping the enumeration. +//% idx = 0; +//% [dict enumerateKeysAndRawValuesUsingBlock:^(KEY_TYPE KisP##aKey, VALUE_TYPE aValue, BOOL *stop) { +//% #pragma unused(aKey, aValue) +//% if (idx == 1) *stop = YES; +//% XCTAssertNotEqual(idx, 2U); +//% ++idx; +//% }]; +//% [dict release]; +//%} +//% +//%- (void)testEqualityWithUnknowns { +//% const KEY_TYPE KisP##kKeys1[] = { KEY1, KEY2, KEY3, KEY4 }; +//% const KEY_TYPE KisP##kKeys2[] = { KEY2, KEY1, KEY4 }; +//% const VALUE_TYPE kValues1[] = { VAL1, VAL2, VAL3 }; // Unknown +//% const VALUE_TYPE kValues2[] = { VAL1, VAL4, VAL3 }; // Unknown +//% const VALUE_TYPE kValues3[] = { VAL1, VAL2, VAL3, VAL4 }; // Unknowns +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict1 = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue +//% KEY_NAME$S VALUE_NAME$S rawValues:kValues1 +//% KEY_NAME$S VALUE_NAME$S forKeys:kKeys1 +//% KEY_NAME$S VALUE_NAME$S count:GPBARRAYSIZE(kValues1)]; +//% XCTAssertNotNil(dict1); +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict1prime = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue +//% KEY_NAME$S VALUE_NAME$S rawValues:kValues1 +//% KEY_NAME$S VALUE_NAME$S forKeys:kKeys1 +//% KEY_NAME$S VALUE_NAME$S count:GPBARRAYSIZE(kValues1)]; +//% XCTAssertNotNil(dict1prime); +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict2 = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue +//% KEY_NAME$S VALUE_NAME$S rawValues:kValues2 +//% KEY_NAME$S VALUE_NAME$S forKeys:kKeys1 +//% KEY_NAME$S VALUE_NAME$S count:GPBARRAYSIZE(kValues2)]; +//% XCTAssertNotNil(dict2); +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict3 = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue +//% KEY_NAME$S VALUE_NAME$S rawValues:kValues1 +//% KEY_NAME$S VALUE_NAME$S forKeys:kKeys2 +//% KEY_NAME$S VALUE_NAME$S count:GPBARRAYSIZE(kValues1)]; +//% XCTAssertNotNil(dict3); +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict4 = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue +//% KEY_NAME$S VALUE_NAME$S rawValues:kValues3 +//% KEY_NAME$S VALUE_NAME$S forKeys:kKeys1 +//% KEY_NAME$S VALUE_NAME$S count:GPBARRAYSIZE(kValues3)]; +//% XCTAssertNotNil(dict4); +//% +//% // 1/1Prime should be different objects, but equal. +//% XCTAssertNotEqual(dict1, dict1prime); +//% XCTAssertEqualObjects(dict1, dict1prime); +//% // Equal, so they must have same hash. +//% XCTAssertEqual([dict1 hash], [dict1prime hash]); +//% +//% // 2 is same keys, different values; not equal. +//% XCTAssertNotEqualObjects(dict1, dict2); +//% +//% // 3 is different keys, same values; not equal. +//% XCTAssertNotEqualObjects(dict1, dict3); +//% +//% // 4 extra pair; not equal +//% XCTAssertNotEqualObjects(dict1, dict4); +//% +//% [dict1 release]; +//% [dict1prime release]; +//% [dict2 release]; +//% [dict3 release]; +//% [dict4 release]; +//%} +//% +//%- (void)testCopyWithUnknowns { +//% const KEY_TYPE KisP##kKeys[] = { KEY1, KEY2, KEY3, KEY4 }; +//% const VALUE_TYPE kValues[] = { VAL1, VAL2, VAL3, VAL4 }; // Unknown +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue +//% KEY_NAME$S VALUE_NAME$S rawValues:kValues +//% KEY_NAME$S VALUE_NAME$S forKeys:kKeys +//% KEY_NAME$S VALUE_NAME$S count:GPBARRAYSIZE(kValues)]; +//% XCTAssertNotNil(dict); +//% +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict2 = [dict copy]; +//% XCTAssertNotNil(dict2); +//% +//% // Should be new pointer, but equal objects. +//% XCTAssertNotEqual(dict, dict2); +//% XCTAssertEqual(dict.validationFunc, dict2.validationFunc); // Pointer comparison +//% XCTAssertEqualObjects(dict, dict2); +//% +//% [dict2 release]; +//% [dict release]; +//%} +//% +//%- (void)testDictionaryFromDictionary { +//% const KEY_TYPE KisP##kKeys[] = { KEY1, KEY2, KEY3, KEY4 }; +//% const VALUE_TYPE kValues[] = { VAL1, VAL2, VAL3, VAL4 }; // Unknowns +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue +//% KEY_NAME$S VALUE_NAME$S rawValues:kValues +//% KEY_NAME$S VALUE_NAME$S forKeys:kKeys +//% KEY_NAME$S VALUE_NAME$S count:GPBARRAYSIZE(kValues)]; +//% XCTAssertNotNil(dict); +//% +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict2 = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithDictionary:dict]; +//% XCTAssertNotNil(dict2); +//% +//% // Should be new pointer, but equal objects. +//% XCTAssertNotEqual(dict, dict2); +//% XCTAssertEqualObjects(dict, dict2); +//% XCTAssertEqual(dict.validationFunc, dict2.validationFunc); // Pointer comparison +//% [dict2 release]; +//% [dict release]; +//%} +//% +//%- (void)testUnknownAdds { +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue]; +//% XCTAssertNotNil(dict); +//% +//% XCTAssertEqual(dict.count, 0U); +//% XCTAssertThrowsSpecificNamed([dict setEnum:VAL2 forKey:KEY2], // Unknown +//% NSException, NSInvalidArgumentException); +//% XCTAssertEqual(dict.count, 0U); +//% [dict setRawValue:VAL2 forKey:KEY2]; // Unknown +//% XCTAssertEqual(dict.count, 1U); +//% +//% const KEY_TYPE KisP##kKeys[] = { KEY1, KEY3, KEY4 }; +//% const VALUE_TYPE kValues[] = { VAL1, VAL3, VAL4 }; // Unknown +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict2 = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithEnums:kValues +//% KEY_NAME$S VALUE_NAME$S forKeys:kKeys +//% KEY_NAME$S VALUE_NAME$S count:GPBARRAYSIZE(kValues)]; +//% XCTAssertNotNil(dict2); +//% [dict addRawEntriesFromDictionary:dict2]; +//% XCTAssertEqual(dict.count, 4U); +//% +//%DECLARE_VALUE_STORAGE##VHELPER(VALUE_TYPE, value)TEST_VALUE##VHELPER(VALUE_NAME, dict, value, KEY1, VAL1) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, value, KEY2, kGPBUnrecognizedEnumeratorValue) +//%TEST_RAW_VALUE##VHELPER(dict, value, KEY2, VAL2) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, value, KEY3, VAL3) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, value, KEY4, kGPBUnrecognizedEnumeratorValue) +//%TEST_RAW_VALUE##VHELPER(dict, value, KEY4, VAL4) +//% [dict2 release]; +//% [dict release]; +//%} +//% +//%- (void)testUnknownRemove { +//% const KEY_TYPE KisP##kKeys[] = { KEY1, KEY2, KEY3, KEY4 }; +//% const VALUE_TYPE kValues[] = { VAL1, VAL2, VAL3, VAL4 }; // Unknowns +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue +//% KEY_NAME$S VALUE_NAME$S rawValues:kValues +//% KEY_NAME$S VALUE_NAME$S forKeys:kKeys +//% KEY_NAME$S VALUE_NAME$S count:GPBARRAYSIZE(kValues)]; +//% XCTAssertNotNil(dict); +//% XCTAssertEqual(dict.count, 4U); +//% +//% [dict removeEnumForKey:KEY2]; +//% XCTAssertEqual(dict.count, 3U); +//%DECLARE_VALUE_STORAGE##VHELPER(VALUE_TYPE, value)TEST_VALUE##VHELPER(VALUE_NAME, dict, value, KEY1, VAL1) +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY2) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, value, KEY3, VAL3) +//%TEST_RAW_VALUE##VHELPER(dict, value, KEY4, VAL4) +//% +//% // Remove again does nothing. +//% [dict removeEnumForKey:KEY2]; +//% XCTAssertEqual(dict.count, 3U); +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, value, KEY1, VAL1) +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY2) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, value, KEY3, VAL3) +//%TEST_RAW_VALUE##VHELPER(dict, value, KEY4, VAL4) +//% +//% [dict removeEnumForKey:KEY4]; +//% XCTAssertEqual(dict.count, 2U); +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, value, KEY1, VAL1) +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY2) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, value, KEY3, VAL3) +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY4) +//% +//% [dict removeAll]; +//% XCTAssertEqual(dict.count, 0U); +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY1) +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY2) +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY3) +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY4) +//% [dict release]; +//%} +//% +//%- (void)testInplaceMutationUnknowns { +//% const KEY_TYPE KisP##kKeys[] = { KEY1, KEY2, KEY3, KEY4 }; +//% const VALUE_TYPE kValues[] = { VAL1, VAL2, VAL3, VAL4 }; // Unknowns +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue +//% KEY_NAME$S VALUE_NAME$S rawValues:kValues +//% KEY_NAME$S VALUE_NAME$S forKeys:kKeys +//% KEY_NAME$S VALUE_NAME$S count:GPBARRAYSIZE(kValues)]; +//% XCTAssertNotNil(dict); +//% XCTAssertEqual(dict.count, 4U); +//%DECLARE_VALUE_STORAGE##VHELPER(VALUE_TYPE, value)TEST_VALUE##VHELPER(VALUE_NAME, dict, value, KEY1, VAL1) +//%TEST_RAW_VALUE##VHELPER(dict, value, KEY2, VAL2) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, value, KEY3, VAL3) +//%TEST_RAW_VALUE##VHELPER(dict, value, KEY4, VAL4) +//% +//% XCTAssertThrowsSpecificNamed([dict setEnum:VAL4 forKey:KEY1], // Unknown +//% NSException, NSInvalidArgumentException); +//% XCTAssertEqual(dict.count, 4U); +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, value, KEY1, VAL1) +//%TEST_RAW_VALUE##VHELPER(dict, value, KEY2, VAL2) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, value, KEY3, VAL3) +//%TEST_RAW_VALUE##VHELPER(dict, value, KEY4, VAL4) +//% +//% [dict setRawValue:VAL4 forKey:KEY1]; // Unknown +//% XCTAssertEqual(dict.count, 4U); +//%TEST_RAW_VALUE##VHELPER(dict, value, KEY1, VAL4) +//%TEST_RAW_VALUE##VHELPER(dict, value, KEY2, VAL2) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, value, KEY3, VAL3) +//%TEST_RAW_VALUE##VHELPER(dict, value, KEY4, VAL4) +//% +//% [dict setRawValue:VAL1 forKey:KEY4]; +//% XCTAssertEqual(dict.count, 4U); +//%TEST_RAW_VALUE##VHELPER(dict, value, KEY1, VAL4) +//%TEST_RAW_VALUE##VHELPER(dict, value, KEY2, VAL2) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, value, KEY3, VAL3) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, value, KEY4, VAL1) +//% +//% const KEY_TYPE KisP##kKeys2[] = { KEY2, KEY3 }; +//% const VALUE_TYPE kValues2[] = { VAL3, VAL2 }; // Unknown +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict2 = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue +//% KEY_NAME$S VALUE_NAME$S rawValues:kValues2 +//% KEY_NAME$S VALUE_NAME$S forKeys:kKeys2 +//% KEY_NAME$S VALUE_NAME$S count:GPBARRAYSIZE(kValues2)]; +//% XCTAssertNotNil(dict2); +//% [dict addRawEntriesFromDictionary:dict2]; +//% XCTAssertEqual(dict.count, 4U); +//%TEST_RAW_VALUE##VHELPER(dict, value, KEY1, VAL4) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, value, KEY2, VAL3) +//%TEST_RAW_VALUE##VHELPER(dict, value, KEY3, VAL2) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, value, KEY4, VAL1) +//% +//% [dict2 release]; +//% [dict release]; +//%} +//% +//%- (void)testCopyUnknowns { +//% const KEY_TYPE KisP##kKeys[] = { KEY1, KEY2, KEY3, KEY4 }; +//% const VALUE_TYPE kValues[] = { VAL1, VAL2, VAL3, VAL4 }; +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithValidationFunction:TestingEnum_IsValidValue +//% KEY_NAME$S VALUE_NAME$S rawValues:kValues +//% KEY_NAME$S VALUE_NAME$S forKeys:kKeys +//% KEY_NAME$S VALUE_NAME$S count:GPBARRAYSIZE(kValues)]; +//% XCTAssertNotNil(dict); +//% +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict2 = [dict copy]; +//% XCTAssertNotNil(dict2); +//% +//% // Should be new pointer, but equal objects. +//% XCTAssertNotEqual(dict, dict2); +//% XCTAssertEqualObjects(dict, dict2); +//% XCTAssertEqual(dict.validationFunc, dict2.validationFunc); // Pointer comparison +//% XCTAssertTrue([dict2 isKindOfClass:[GPB##KEY_NAME##VALUE_NAME##Dictionary class]]); +//% +//% [dict2 release]; +//% [dict release]; +//%} +//% +//%@end +//% + +// +// Helpers for PODs +// + +//%PDDM-DEFINE DECLARE_VALUE_STORAGEPOD(VALUE_TYPE, NAME) +//% VALUE_TYPE NAME; +//% +//%PDDM-DEFINE VALUE_NOT_FOUNDPOD(VALUE_NAME, DICT, KEY) +//% XCTAssertFalse([DICT get##VALUE_NAME##:NULL forKey:KEY]); +//%PDDM-DEFINE TEST_VALUEPOD(VALUE_NAME, DICT, STORAGE, KEY, VALUE) +//% XCTAssertTrue([DICT get##VALUE_NAME##:NULL forKey:KEY]); +//% XCTAssertTrue([DICT get##VALUE_NAME##:&STORAGE forKey:KEY]); +//% XCTAssertEqual(STORAGE, VALUE); +//%PDDM-DEFINE COMPARE_KEYS(KEY1, KEY2) +//%KEY1 == KEY2 +//%PDDM-DEFINE RAW_VALUE_NOT_FOUNDPOD(VALUE_NAME, DICT, KEY) +//% XCTAssertFalse([DICT getRawValue:NULL forKey:KEY]); +//%PDDM-DEFINE TEST_RAW_VALUEPOD(DICT, STORAGE, KEY, VALUE) +//% XCTAssertTrue([DICT getRawValue:NULL forKey:KEY]); +//% XCTAssertTrue([DICT getRawValue:&STORAGE forKey:KEY]); +//% XCTAssertEqual(STORAGE, VALUE); + +// +// Helpers for Objects +// + +//%PDDM-DEFINE DECLARE_VALUE_STORAGEOBJECT(VALUE_TYPE, NAME) +// Empty +//%PDDM-DEFINE VALUE_NOT_FOUNDOBJECT(VALUE_NAME, DICT, KEY) +//% XCTAssertNil([DICT objectForKey:KEY]); +//%PDDM-DEFINE TEST_VALUEOBJECT(VALUE_NAME, DICT, STORAGE, KEY, VALUE) +//% XCTAssertEqualObjects([DICT objectForKey:KEY], VALUE); +//%PDDM-DEFINE COMPARE_KEYSObjects(KEY1, KEY2) +//%[KEY1 isEqual:KEY2] + +// +// Helpers for tests. +// + +//%PDDM-DEFINE TEST_HELPERS(KEY_NAME, KEY_TYPE, KisP) +//%// To let the testing macros work, add some extra methods to simplify things. +//%@interface GPB##KEY_NAME##EnumDictionary (TestingTweak) +//%- (instancetype)initWithEnums:(const int32_t [])values +//% forKeys:(const KEY_TYPE##KisP$S##KisP [])keys +//% count:(NSUInteger)count; +//%@end +//% +//%static BOOL TestingEnum_IsValidValue(int32_t value) { +//% switch (value) { +//% case 700: +//% case 701: +//% case 702: +//% case 703: +//% return YES; +//% default: +//% return NO; +//% } +//%} +//% +//%@implementation GPB##KEY_NAME##EnumDictionary (TestingTweak) +//%- (instancetype)initWithEnums:(const int32_t [])values +//% forKeys:(const KEY_TYPE##KisP$S##KisP [])keys +//% count:(NSUInteger)count { +//% return [self initWithValidationFunction:TestingEnum_IsValidValue +//% rawValues:values +//% forKeys:keys +//% count:count]; +//%} +//%@end +//% +//% + + +// +// BOOL test macros +// +//TODO(thomasvl): enum tests + +//%PDDM-DEFINE BOOL_TESTS_FOR_POD_VALUE(VALUE_NAME, VALUE_TYPE, VAL1, VAL2) +//%BOOL_TESTS_COMMON(Bool, BOOL, , , YES, NO, VALUE_NAME, VALUE_TYPE, , value, POD, VAL1, VAL2) + +//%PDDM-DEFINE TESTS_FOR_BOOL_KEY_OBJECT_VALUE(VALUE_NAME, VALUE_TYPE, VAL1, VAL2) +//%BOOL_TESTS_COMMON(Bool, BOOL, , , YES, NO, VALUE_NAME, VALUE_TYPE, Objects, object, OBJECT, VAL1, VAL2) + +//%PDDM-DEFINE BOOL_TESTS_COMMON(KEY_NAME, KEY_TYPE, KisP, KSUFFIX, KEY1, KEY2, VALUE_NAME, VALUE_TYPE, VSUFFIX, VNAME, VHELPER, VAL1, VAL2) +//%#pragma mark - KEY_NAME -> VALUE_NAME +//% +//%@interface GPB##KEY_NAME##VALUE_NAME##DictionaryTests : XCTestCase +//%@end +//% +//%@implementation GPB##KEY_NAME##VALUE_NAME##DictionaryTests +//% +//%- (void)testEmpty { +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] init]; +//% XCTAssertNotNil(dict); +//% XCTAssertEqual(dict.count, 0U); +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY1) +//% [dict enumerateKeysAnd##VALUE_NAME##sUsingBlock:^(KEY_TYPE KisP##aKey, VALUE_TYPE a##VNAME$u##, BOOL *stop) { +//% #pragma unused(aKey, a##VNAME$u##, stop) +//% XCTFail(@"Shouldn't get here!"); +//% }]; +//% [dict release]; +//%} +//% +//%- (void)testOne { +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] init]; +//% [dict set##VALUE_NAME$u##:VAL1 forKey:KEY1]; +//% XCTAssertNotNil(dict); +//% XCTAssertEqual(dict.count, 1U); +//%DECLARE_VALUE_STORAGE##VHELPER(VALUE_TYPE, VNAME)TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL1) +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY2) +//% [dict enumerateKeysAnd##VALUE_NAME$u##sUsingBlock:^(KEY_TYPE KisP##aKey, VALUE_TYPE a##VNAME$u, BOOL *stop) { +//% XCTAssertEqual##KSUFFIX(aKey, KEY1); +//% XCTAssertEqual##VSUFFIX(a##VNAME$u, VAL1); +//% XCTAssertNotEqual(stop, NULL); +//% }]; +//% [dict release]; +//%} +//% +//%- (void)testBasics { +//% const KEY_TYPE KisP##kKeys[] = { KEY1, KEY2 }; +//% const VALUE_TYPE k##VNAME$u##s[] = { VAL1, VAL2 }; +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME##s:k##VNAME$u##s +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s)]; +//% XCTAssertNotNil(dict); +//% XCTAssertEqual(dict.count, 2U); +//%DECLARE_VALUE_STORAGE##VHELPER(VALUE_TYPE, VNAME)TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL1) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY2, VAL2) +//% +//% __block NSUInteger idx = 0; +//% KEY_TYPE KisP##*seenKeys = malloc(2 * sizeof(KEY_TYPE##KisP)); +//% VALUE_TYPE *seen##VNAME$u##s = malloc(2 * sizeof(VALUE_TYPE)); +//% [dict enumerateKeysAnd##VALUE_NAME$u##sUsingBlock:^(KEY_TYPE KisP##aKey, VALUE_TYPE a##VNAME$u##, BOOL *stop) { +//% XCTAssertLessThan(idx, 2U); +//% seenKeys[idx] = aKey; +//% seen##VNAME$u##s[idx] = a##VNAME$u; +//% XCTAssertNotEqual(stop, NULL); +//% ++idx; +//% }]; +//% for (int i = 0; i < 2; ++i) { +//% BOOL foundKey = NO; +//% for (int j = 0; (j < 2) && !foundKey; ++j) { +//% if (COMPARE_KEYS##KSUFFIX(kKeys[i], seenKeys[j])) { +//% foundKey = YES; +//% XCTAssertEqual##VSUFFIX(k##VNAME$u##s[i], seen##VNAME$u##s[j], @"i = %d, j = %d", i, j); +//% } +//% } +//% XCTAssertTrue(foundKey, @"i = %d", i); +//% } +//% free(seenKeys); +//% free(seen##VNAME$u##s); +//% +//% // Stopping the enumeration. +//% idx = 0; +//% [dict enumerateKeysAnd##VALUE_NAME$u##sUsingBlock:^(KEY_TYPE KisP##aKey, VALUE_TYPE a##VNAME$u##, BOOL *stop) { +//% #pragma unused(aKey, a##VNAME$u) +//% if (idx == 0) *stop = YES; +//% XCTAssertNotEqual(idx, 2U); +//% ++idx; +//% }]; +//% [dict release]; +//%} +//% +//%- (void)testEquality { +//% const KEY_TYPE KisP##kKeys1[] = { KEY1, KEY2 }; +//% const KEY_TYPE KisP##kKeys2[] = { KEY2, KEY1 }; +//% const VALUE_TYPE k##VNAME$u##s1[] = { VAL1, VAL2 }; +//% const VALUE_TYPE k##VNAME$u##s2[] = { VAL2, VAL1 }; +//% const VALUE_TYPE k##VNAME$u##s3[] = { VAL2 }; +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict1 = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME##s:k##VNAME$u##s1 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys1 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s1)]; +//% XCTAssertNotNil(dict1); +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict1prime = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME##s:k##VNAME$u##s1 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys1 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s1)]; +//% XCTAssertNotNil(dict1prime); +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict2 = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME##s:k##VNAME$u##s2 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys1 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s2)]; +//% XCTAssertNotNil(dict2); +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict3 = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME##s:k##VNAME$u##s1 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys2 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s1)]; +//% XCTAssertNotNil(dict3); +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict4 = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME##s:k##VNAME$u##s3 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys1 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s3)]; +//% XCTAssertNotNil(dict4); +//% +//% // 1/1Prime should be different objects, but equal. +//% XCTAssertNotEqual(dict1, dict1prime); +//% XCTAssertEqualObjects(dict1, dict1prime); +//% // Equal, so they must have same hash. +//% XCTAssertEqual([dict1 hash], [dict1prime hash]); +//% +//% // 2 is same keys, different ##VNAME##s; not equal. +//% XCTAssertNotEqualObjects(dict1, dict2); +//% +//% // 3 is different keys, same ##VNAME##s; not equal. +//% XCTAssertNotEqualObjects(dict1, dict3); +//% +//% // 4 Fewer pairs; not equal +//% XCTAssertNotEqualObjects(dict1, dict4); +//% +//% [dict1 release]; +//% [dict1prime release]; +//% [dict2 release]; +//% [dict3 release]; +//% [dict4 release]; +//%} +//% +//%- (void)testCopy { +//% const KEY_TYPE KisP##kKeys[] = { KEY1, KEY2 }; +//% const VALUE_TYPE k##VNAME$u##s[] = { VAL1, VAL2 }; +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME##s:k##VNAME$u##s +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s)]; +//% XCTAssertNotNil(dict); +//% +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict2 = [dict copy]; +//% XCTAssertNotNil(dict2); +//% +//% // Should be new object but equal. +//% XCTAssertNotEqual(dict, dict2); +//% XCTAssertEqualObjects(dict, dict2); +//% XCTAssertTrue([dict2 isKindOfClass:[GPB##KEY_NAME##VALUE_NAME##Dictionary class]]); +//% +//% [dict2 release]; +//% [dict release]; +//%} +//% +//%- (void)testDictionaryFromDictionary { +//% const KEY_TYPE KisP##kKeys[] = { KEY1, KEY2 }; +//% const VALUE_TYPE k##VNAME$u##s[] = { VAL1, VAL2 }; +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME##s:k##VNAME$u##s +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s)]; +//% XCTAssertNotNil(dict); +//% +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict2 = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWithDictionary:dict]; +//% XCTAssertNotNil(dict2); +//% +//% // Should be new pointer, but equal objects. +//% XCTAssertNotEqual(dict, dict2); +//% XCTAssertEqualObjects(dict, dict2); +//% [dict2 release]; +//% [dict release]; +//%} +//% +//%- (void)testAdds { +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] init]; +//% XCTAssertNotNil(dict); +//% +//% XCTAssertEqual(dict.count, 0U); +//% [dict set##VALUE_NAME:VAL1 forKey:KEY1]; +//% XCTAssertEqual(dict.count, 1U); +//% +//% const KEY_TYPE KisP##kKeys[] = { KEY2 }; +//% const VALUE_TYPE k##VNAME$u##s[] = { VAL2 }; +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict2 = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME##s:k##VNAME$u##s +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s)]; +//% XCTAssertNotNil(dict2); +//% [dict addEntriesFromDictionary:dict2]; +//% XCTAssertEqual(dict.count, 2U); +//% +//%DECLARE_VALUE_STORAGE##VHELPER(VALUE_TYPE, VNAME)TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL1) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY2, VAL2) +//% [dict2 release]; +//% [dict release]; +//%} +//% +//%- (void)testRemove { +//% const KEY_TYPE KisP##kKeys[] = { KEY1, KEY2}; +//% const VALUE_TYPE k##VNAME$u##s[] = { VAL1, VAL2 }; +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME##s:k##VNAME$u##s +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s)]; +//% XCTAssertNotNil(dict); +//% XCTAssertEqual(dict.count, 2U); +//% +//% [dict remove##VALUE_NAME##ForKey:KEY2]; +//% XCTAssertEqual(dict.count, 1U); +//%DECLARE_VALUE_STORAGE##VHELPER(VALUE_TYPE, VNAME)TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL1) +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY2) +//% +//% // Remove again does nothing. +//% [dict remove##VALUE_NAME##ForKey:KEY2]; +//% XCTAssertEqual(dict.count, 1U); +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL1) +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY2) +//% +//% [dict removeAll]; +//% XCTAssertEqual(dict.count, 0U); +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY1) +//%VALUE_NOT_FOUND##VHELPER(VALUE_NAME, dict, KEY2) +//% [dict release]; +//%} +//% +//%- (void)testInplaceMutation { +//% const KEY_TYPE KisP##kKeys[] = { KEY1, KEY2 }; +//% const VALUE_TYPE k##VNAME$u##s[] = { VAL1, VAL2 }; +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME##s:k##VNAME$u##s +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s)]; +//% XCTAssertNotNil(dict); +//% XCTAssertEqual(dict.count, 2U); +//%DECLARE_VALUE_STORAGE##VHELPER(VALUE_TYPE, VNAME)TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL1) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY2, VAL2) +//% +//% [dict set##VALUE_NAME##:VAL2 forKey:KEY1]; +//% XCTAssertEqual(dict.count, 2U); +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL2) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY2, VAL2) +//% +//% [dict set##VALUE_NAME##:VAL1 forKey:KEY2]; +//% XCTAssertEqual(dict.count, 2U); +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL2) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY2, VAL1) +//% +//% const KEY_TYPE KisP##kKeys2[] = { KEY2, KEY1 }; +//% const VALUE_TYPE k##VNAME$u##s2[] = { VAL2, VAL1 }; +//% DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) *dict2 = +//% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] initWith##VALUE_NAME##s:k##VNAME$u##s2 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## forKeys:kKeys2 +//% KEY_NAME$S VALUE_NAME$S ##VALUE_NAME$S## count:GPBARRAYSIZE(k##VNAME$u##s2)]; +//% XCTAssertNotNil(dict2); +//% [dict addEntriesFromDictionary:dict2]; +//% XCTAssertEqual(dict.count, 2U); +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY1, VAL1) +//%TEST_VALUE##VHELPER(VALUE_NAME, dict, VNAME, KEY2, VAL2) +//% +//% [dict2 release]; +//% [dict release]; +//%} +//% +//%@end +//% + diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/UnitTests-Bridging-Header.h b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/UnitTests-Bridging-Header.h new file mode 100644 index 0000000..46292fc --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/UnitTests-Bridging-Header.h @@ -0,0 +1,6 @@ +// +// Use this file to import your target's public headers that you would like to expose to Swift. +// + +#import "google/protobuf/UnittestRuntimeProto2.pbobjc.h" +#import "google/protobuf/UnittestRuntimeProto3.pbobjc.h" diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/text_format_extensions_unittest_data.txt b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/text_format_extensions_unittest_data.txt new file mode 100644 index 0000000..d520545 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/text_format_extensions_unittest_data.txt @@ -0,0 +1,140 @@ +1: 101 # [UnittestRoot_optionalInt32Extension] +2: 102 # [UnittestRoot_optionalInt64Extension] +3: 103 # [UnittestRoot_optionalUint32Extension] +4: 104 # [UnittestRoot_optionalUint64Extension] +5: 105 # [UnittestRoot_optionalSint32Extension] +6: 106 # [UnittestRoot_optionalSint64Extension] +7: 107 # [UnittestRoot_optionalFixed32Extension] +8: 108 # [UnittestRoot_optionalFixed64Extension] +9: 109 # [UnittestRoot_optionalSfixed32Extension] +10: 110 # [UnittestRoot_optionalSfixed64Extension] +11: 111 # [UnittestRoot_optionalFloatExtension] +12: 112 # [UnittestRoot_optionalDoubleExtension] +13: true # [UnittestRoot_optionalBoolExtension] +14: "115" # [UnittestRoot_optionalStringExtension] +15: "\001\000\002\003\000\005" # [UnittestRoot_optionalBytesExtension] +16 { # [UnittestRoot_optionalGroupExtension] + a: 117 +} +18 { # [UnittestRoot_optionalNestedMessageExtension] + bb: 118 +} +19 { # [UnittestRoot_optionalForeignMessageExtension] + c: 119 +} +20 { # [UnittestRoot_optionalImportMessageExtension] + d: 120 +} +21: 3 # [UnittestRoot_optionalNestedEnumExtension] +22: 6 # [UnittestRoot_optionalForeignEnumExtension] +23: 9 # [UnittestRoot_optionalImportEnumExtension] +24: "124" # [UnittestRoot_optionalStringPieceExtension] +25: "125" # [UnittestRoot_optionalCordExtension] +# [UnittestRoot_repeatedInt32Extension] +31: 201 +31: 301 +# [UnittestRoot_repeatedInt64Extension] +32: 202 +32: 302 +# [UnittestRoot_repeatedUint32Extension] +33: 203 +33: 303 +# [UnittestRoot_repeatedUint64Extension] +34: 204 +34: 304 +# [UnittestRoot_repeatedSint32Extension] +35: 205 +35: 305 +# [UnittestRoot_repeatedSint64Extension] +36: 206 +36: 306 +# [UnittestRoot_repeatedFixed32Extension] +37: 207 +37: 307 +# [UnittestRoot_repeatedFixed64Extension] +38: 208 +38: 308 +# [UnittestRoot_repeatedSfixed32Extension] +39: 209 +39: 309 +# [UnittestRoot_repeatedSfixed64Extension] +40: 210 +40: 310 +# [UnittestRoot_repeatedFloatExtension] +41: 211 +41: 311 +# [UnittestRoot_repeatedDoubleExtension] +42: 212 +42: 312 +# [UnittestRoot_repeatedBoolExtension] +43: false +43: true +# [UnittestRoot_repeatedStringExtension] +44: "215" +44: "315" +# [UnittestRoot_repeatedBytesExtension] +45: "\330\000\000\000" +45: "<\001\000\000" +# [UnittestRoot_repeatedGroupExtension] +46 { + a: 217 +} +46 { + a: 317 +} +# [UnittestRoot_repeatedNestedMessageExtension] +48 { + bb: 218 +} +48 { + bb: 318 +} +# [UnittestRoot_repeatedForeignMessageExtension] +49 { + c: 219 +} +49 { + c: 319 +} +# [UnittestRoot_repeatedImportMessageExtension] +50 { + d: 220 +} +50 { + d: 320 +} +# [UnittestRoot_repeatedNestedEnumExtension] +51: 3 +51: 2 +# [UnittestRoot_repeatedForeignEnumExtension] +52: 6 +52: 5 +# [UnittestRoot_repeatedImportEnumExtension] +53: 9 +53: 8 +# [UnittestRoot_repeatedStringPieceExtension] +54: "224" +54: "324" +# [UnittestRoot_repeatedCordExtension] +55: "225" +55: "325" +61: 401 # [UnittestRoot_defaultInt32Extension] +62: 402 # [UnittestRoot_defaultInt64Extension] +63: 403 # [UnittestRoot_defaultUint32Extension] +64: 404 # [UnittestRoot_defaultUint64Extension] +65: 405 # [UnittestRoot_defaultSint32Extension] +66: 406 # [UnittestRoot_defaultSint64Extension] +67: 407 # [UnittestRoot_defaultFixed32Extension] +68: 408 # [UnittestRoot_defaultFixed64Extension] +69: 409 # [UnittestRoot_defaultSfixed32Extension] +70: 410 # [UnittestRoot_defaultSfixed64Extension] +71: 411 # [UnittestRoot_defaultFloatExtension] +72: 412 # [UnittestRoot_defaultDoubleExtension] +73: false # [UnittestRoot_defaultBoolExtension] +74: "415" # [UnittestRoot_defaultStringExtension] +75: "\240\001\000\000" # [UnittestRoot_defaultBytesExtension] +81: 1 # [UnittestRoot_defaultNestedEnumExtension] +82: 4 # [UnittestRoot_defaultForeignEnumExtension] +83: 7 # [UnittestRoot_defaultImportEnumExtension] +84: "424" # [UnittestRoot_defaultStringPieceExtension] +85: "425" # [UnittestRoot_defaultCordExtension] diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/text_format_unittest_data.txt b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/text_format_unittest_data.txt new file mode 100644 index 0000000..d10f100 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/text_format_unittest_data.txt @@ -0,0 +1,116 @@ +optional_int32: 101 +optional_int64: 102 +optional_uint32: 103 +optional_uint64: 104 +optional_sint32: 105 +optional_sint64: 106 +optional_fixed32: 107 +optional_fixed64: 108 +optional_sfixed32: 109 +optional_sfixed64: 110 +optional_float: 111 +optional_double: 112 +optional_bool: true +optional_string: "115" +optional_bytes: "\001\000\002\003\000\005" +OptionalGroup { + a: 117 +} +optional_nested_message { + bb: 118 +} +optional_foreign_message { + c: 119 +} +optional_import_message { + d: 120 +} +optional_nested_enum: BAZ +optional_foreign_enum: FOREIGN_BAZ +optional_import_enum: IMPORT_BAZ +optional_string_piece: "124" +optional_cord: "125" +repeated_int32: 201 +repeated_int32: 301 +repeated_int64: 202 +repeated_int64: 302 +repeated_uint32: 203 +repeated_uint32: 303 +repeated_uint64: 204 +repeated_uint64: 304 +repeated_sint32: 205 +repeated_sint32: 305 +repeated_sint64: 206 +repeated_sint64: 306 +repeated_fixed32: 207 +repeated_fixed32: 307 +repeated_fixed64: 208 +repeated_fixed64: 308 +repeated_sfixed32: 209 +repeated_sfixed32: 309 +repeated_sfixed64: 210 +repeated_sfixed64: 310 +repeated_float: 211 +repeated_float: 311 +repeated_double: 212 +repeated_double: 312 +repeated_bool: false +repeated_bool: true +repeated_string: "215" +repeated_string: "315" +repeated_bytes: "\330\000\000\000" +repeated_bytes: "<\001\000\000" +RepeatedGroup { + a: 217 +} +RepeatedGroup { + a: 317 +} +repeated_nested_message { + bb: 218 +} +repeated_nested_message { + bb: 318 +} +repeated_foreign_message { + c: 219 +} +repeated_foreign_message { + c: 319 +} +repeated_import_message { + d: 220 +} +repeated_import_message { + d: 320 +} +repeated_nested_enum: BAZ +repeated_nested_enum: BAR +repeated_foreign_enum: FOREIGN_BAZ +repeated_foreign_enum: FOREIGN_BAR +repeated_import_enum: IMPORT_BAZ +repeated_import_enum: IMPORT_BAR +repeated_string_piece: "224" +repeated_string_piece: "324" +repeated_cord: "225" +repeated_cord: "325" +default_int32: 401 +default_int64: 402 +default_uint32: 403 +default_uint64: 404 +default_sint32: 405 +default_sint64: 406 +default_fixed32: 407 +default_fixed64: 408 +default_sfixed32: 409 +default_sfixed64: 410 +default_float: 411 +default_double: 412 +default_bool: false +default_string: "415" +default_bytes: "\240\001\000\000" +default_nested_enum: FOO +default_foreign_enum: FOREIGN_FOO +default_import_enum: IMPORT_FOO +default_string_piece: "424" +default_cord: "425" diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/unittest_extension_chain_d.proto b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/unittest_extension_chain_d.proto new file mode 100644 index 0000000..f9abe3b --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/Tests/unittest_extension_chain_d.proto @@ -0,0 +1,49 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2016 Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto2"; + +package protobuf_unittest; + +import "google/protobuf/unittest.proto"; + +import "unittest_extension_chain_b.proto"; +import "unittest_extension_chain_c.proto"; + +// The root should end up needing to merge B (C will be merged into B, so it +// doesn't need to be directly merged). + +message ChainDMessage { + optional ChainBMessage b = 1; + optional ChainCMessage c = 2; +} + +extend TestAllExtensions { + optional int32 chain_d_extension = 10004; +} diff --git a/tools/go-generator/cmd/generator/_protobuf/objectivec/google/protobuf/Timestamp.pbobjc.h b/tools/go-generator/cmd/generator/_protobuf/objectivec/google/protobuf/Timestamp.pbobjc.h new file mode 100644 index 0000000..6a7cef8 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/objectivec/google/protobuf/Timestamp.pbobjc.h @@ -0,0 +1,2 @@ +// Moved to root of objectivec directory, shim to keep anyone's imports working. +#import "GPBTimestamp.pbobjc.h" diff --git a/tools/go-generator/cmd/generator/_protobuf/php/ext/google/protobuf/array.h b/tools/go-generator/cmd/generator/_protobuf/php/ext/google/protobuf/array.h new file mode 100644 index 0000000..031effa --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/ext/google/protobuf/array.h @@ -0,0 +1,67 @@ +// 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 PHP_PROTOBUF_ARRAY_H_ +#define PHP_PROTOBUF_ARRAY_H_ + +#include + +#include "def.h" +#include "php-upb.h" + +// Registers PHP classes for RepeatedField. +void Array_ModuleInit(); + +// Gets a upb_array* for the PHP object |val|: +// * If |val| is a RepeatedField object, we first check its type and verify +// that that the elements have the correct type for |type|. If so, we return +// the wrapped upb_array*. We also make sure that this array's arena is fused +// to |arena|, so the returned upb_array is guaranteed to live as long as +// |arena|. +// * If |val| is a PHP Array, we attempt to create a new upb_array using +// |arena| and add all of the PHP elements to it. +// +// If an error occurs, we raise a PHP error and return NULL. +upb_array *RepeatedField_GetUpbArray(zval *val, TypeInfo type, + upb_arena *arena); + +// Creates a PHP RepeatedField object for the given upb_array* and |type| and +// returns it in |val|. The PHP object will keep a reference to this |arena| to +// ensure the underlying array data stays alive. +// +// If |arr| is NULL, this will return a PHP null object. +void RepeatedField_GetPhpWrapper(zval *val, upb_array *arr, TypeInfo type, + zval *arena); + +// Returns true if the given arrays are equal. Both arrays must be of this +// |type| and, if the type is |UPB_TYPE_MESSAGE|, must have the same |m|. +bool ArrayEq(const upb_array *a1, const upb_array *a2, TypeInfo type); + +#endif // PHP_PROTOBUF_ARRAY_H_ diff --git a/tools/go-generator/cmd/generator/_protobuf/php/ext/google/protobuf/config.m4 b/tools/go-generator/cmd/generator/_protobuf/php/ext/google/protobuf/config.m4 new file mode 100644 index 0000000..c09c03a --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/ext/google/protobuf/config.m4 @@ -0,0 +1,10 @@ +PHP_ARG_ENABLE(protobuf, whether to enable Protobuf extension, [ --enable-protobuf Enable Protobuf extension]) + +if test "$PHP_PROTOBUF" != "no"; then + + PHP_NEW_EXTENSION( + protobuf, + arena.c array.c convert.c def.c map.c message.c names.c php-upb.c protobuf.c, + $ext_shared, , -std=gnu99) + +fi diff --git a/tools/go-generator/cmd/generator/_protobuf/php/ext/google/protobuf/names.c b/tools/go-generator/cmd/generator/_protobuf/php/ext/google/protobuf/names.c new file mode 100644 index 0000000..a991888 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/ext/google/protobuf/names.c @@ -0,0 +1,227 @@ +// 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. + +#include "names.h" + +#include + +#include "protobuf.h" + +/* stringsink *****************************************************************/ + +typedef struct { + char *ptr; + size_t len, size; +} stringsink; + +static size_t stringsink_string(stringsink *sink, const char *ptr, size_t len) { + size_t new_size = sink->size; + + while (sink->len + len > new_size) { + new_size *= 2; + } + + if (new_size != sink->size) { + sink->ptr = realloc(sink->ptr, new_size); + sink->size = new_size; + } + + memcpy(sink->ptr + sink->len, ptr, len); + sink->len += len; + + return len; +} + +static void stringsink_init(stringsink *sink) { + sink->size = 32; + sink->ptr = malloc(sink->size); + PBPHP_ASSERT(sink->ptr != NULL); + sink->len = 0; +} + +static void stringsink_uninit(stringsink *sink) { free(sink->ptr); } + +/* def name -> classname ******************************************************/ + +const char *const kReservedNames[] = { + "abstract", "and", "array", "as", "break", + "callable", "case", "catch", "class", "clone", + "const", "continue", "declare", "default", "die", + "do", "echo", "else", "elseif", "empty", + "enddeclare", "endfor", "endforeach", "endif", "endswitch", + "endwhile", "eval", "exit", "extends", "final", + "finally", "fn", "for", "foreach", "function", + "if", "implements", "include", "include_once", "instanceof", + "global", "goto", "insteadof", "interface", "isset", + "list", "match", "namespace", "new", "object", + "or", "print", "private", "protected", "public", + "require", "require_once", "return", "static", "switch", + "throw", "trait", "try", "unset", "use", + "var", "while", "xor", "yield", "int", + "float", "bool", "string", "true", "false", + "null", "void", "iterable", NULL}; + +bool is_reserved_name(const char* name) { + int i; + for (i = 0; kReservedNames[i]; i++) { + if (strcmp(kReservedNames[i], name) == 0) { + return true; + } + } + return false; +} + +static char nolocale_tolower(char ch) { + if (ch >= 'A' && ch <= 'Z') { + return ch - ('A' - 'a'); + } else { + return ch; + } +} + +static char nolocale_toupper(char ch) { + if (ch >= 'a' && ch <= 'z') { + return ch - ('a' - 'A'); + } else { + return ch; + } +} + +static bool is_reserved(const char *segment, int length) { + bool result; + char* lower = calloc(1, length + 1); + memcpy(lower, segment, length); + int i = 0; + while(lower[i]) { + lower[i] = nolocale_tolower(lower[i]); + i++; + } + lower[length] = 0; + result = is_reserved_name(lower); + free(lower); + return result; +} + +static void fill_prefix(const char *segment, int length, + const char *prefix_given, + const char *package_name, + stringsink *classname) { + if (prefix_given != NULL && strcmp(prefix_given, "") != 0) { + stringsink_string(classname, prefix_given, strlen(prefix_given)); + } else { + if (is_reserved(segment, length)) { + if (package_name != NULL && + strcmp("google.protobuf", package_name) == 0) { + stringsink_string(classname, "GPB", 3); + } else { + stringsink_string(classname, "PB", 2); + } + } + } +} + +static void fill_segment(const char *segment, int length, + stringsink *classname, bool use_camel) { + if (use_camel && (segment[0] < 'A' || segment[0] > 'Z')) { + char first = nolocale_toupper(segment[0]); + stringsink_string(classname, &first, 1); + stringsink_string(classname, segment + 1, length - 1); + } else { + stringsink_string(classname, segment, length); + } +} + +static void fill_namespace(const char *package, const char *php_namespace, + stringsink *classname) { + if (php_namespace != NULL) { + if (strlen(php_namespace) != 0) { + stringsink_string(classname, php_namespace, strlen(php_namespace)); + stringsink_string(classname, "\\", 1); + } + } else if (package != NULL) { + int i = 0, j = 0; + size_t package_len = strlen(package); + while (i < package_len) { + j = i; + while (j < package_len && package[j] != '.') { + j++; + } + fill_prefix(package + i, j - i, "", package, classname); + fill_segment(package + i, j - i, classname, true); + stringsink_string(classname, "\\", 1); + i = j + 1; + } + } +} + +static void fill_classname(const char *fullname, + const char *package, + const char *prefix, + stringsink *classname) { + int classname_start = 0; + if (package != NULL) { + size_t package_len = strlen(package); + classname_start = package_len == 0 ? 0 : package_len + 1; + } + size_t fullname_len = strlen(fullname); + + int i = classname_start, j; + while (i < fullname_len) { + j = i; + while (j < fullname_len && fullname[j] != '.') { + j++; + } + fill_prefix(fullname + i, j - i, prefix, package, classname); + fill_segment(fullname + i, j - i, classname, false); + if (j != fullname_len) { + stringsink_string(classname, "\\", 1); + } + i = j + 1; + } +} + +char *GetPhpClassname(const upb_filedef *file, const char *fullname) { + // Prepend '.' to package name to make it absolute. In the 5 additional + // bytes allocated, one for '.', one for trailing 0, and 3 for 'GPB' if + // given message is google.protobuf.Empty. + const char *package = upb_filedef_package(file); + const char *php_namespace = upb_filedef_phpnamespace(file); + const char *prefix = upb_filedef_phpprefix(file); + char *ret; + stringsink namesink; + stringsink_init(&namesink); + + fill_namespace(package, php_namespace, &namesink); + fill_classname(fullname, package, prefix, &namesink); + stringsink_string(&namesink, "\0", 1); + ret = strdup(namesink.ptr); + stringsink_uninit(&namesink); + return ret; +} diff --git a/tools/go-generator/cmd/generator/_protobuf/php/ext/google/protobuf/wkt.inc b/tools/go-generator/cmd/generator/_protobuf/php/ext/google/protobuf/wkt.inc new file mode 100644 index 0000000..df3cce9 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/ext/google/protobuf/wkt.inc @@ -0,0 +1,3245 @@ +// This file is generated from the .proto files for the well-known +// types. Do not edit! + +ZEND_BEGIN_ARG_INFO_EX(arginfo_lookup, 0, 0, 1) + ZEND_ARG_INFO(0, key) +ZEND_END_ARG_INFO() + +static void google_protobuf_any_proto_AddDescriptor(); +static void google_protobuf_api_proto_AddDescriptor(); +static void google_protobuf_duration_proto_AddDescriptor(); +static void google_protobuf_empty_proto_AddDescriptor(); +static void google_protobuf_field_mask_proto_AddDescriptor(); +static void google_protobuf_source_context_proto_AddDescriptor(); +static void google_protobuf_struct_proto_AddDescriptor(); +static void google_protobuf_type_proto_AddDescriptor(); +static void google_protobuf_timestamp_proto_AddDescriptor(); +static void google_protobuf_wrappers_proto_AddDescriptor(); +/* google/protobuf/any.proto */ + +zend_class_entry* GPBMetadata_Google_Protobuf_Any_ce; + +const char google_protobuf_any_proto_descriptor [212] = { +'\n', '\031', 'g', 'o', 'o', 'g', 'l', 'e', '/', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '/', 'a', 'n', 'y', '.', 'p', 'r', 'o', +'t', 'o', '\022', '\017', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '\"', '&', '\n', '\003', 'A', 'n', +'y', '\022', '\020', '\n', '\010', 't', 'y', 'p', 'e', '_', 'u', 'r', 'l', '\030', '\001', ' ', '\001', '(', '\t', '\022', '\r', '\n', '\005', 'v', 'a', +'l', 'u', 'e', '\030', '\002', ' ', '\001', '(', '\014', 'B', 'v', '\n', '\023', 'c', 'o', 'm', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', +'r', 'o', 't', 'o', 'b', 'u', 'f', 'B', '\010', 'A', 'n', 'y', 'P', 'r', 'o', 't', 'o', 'P', '\001', 'Z', ',', 'g', 'o', 'o', 'g', +'l', 'e', '.', 'g', 'o', 'l', 'a', 'n', 'g', '.', 'o', 'r', 'g', '/', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '/', 't', 'y', +'p', 'e', 's', '/', 'k', 'n', 'o', 'w', 'n', '/', 'a', 'n', 'y', 'p', 'b', '\242', '\002', '\003', 'G', 'P', 'B', '\252', '\002', '\036', 'G', +'o', 'o', 'g', 'l', 'e', '.', 'P', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'W', 'e', 'l', 'l', 'K', 'n', 'o', 'w', 'n', 'T', +'y', 'p', 'e', 's', 'b', '\006', 'p', 'r', 'o', 't', 'o', '3', +}; + +static void google_protobuf_any_proto_AddDescriptor() { + if (DescriptorPool_HasFile("google/protobuf/any.proto")) return; + DescriptorPool_AddDescriptor("google/protobuf/any.proto", google_protobuf_any_proto_descriptor, + sizeof(google_protobuf_any_proto_descriptor)); +} + +static PHP_METHOD(GPBMetadata_Google_Protobuf_Any, initOnce) { + google_protobuf_any_proto_AddDescriptor(); +} + +static zend_function_entry GPBMetadata_Google_Protobuf_Any_methods[] = { + PHP_ME(GPBMetadata_Google_Protobuf_Any, initOnce, arginfo_void, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + ZEND_FE_END +}; + +static void GPBMetadata_Google_Protobuf_Any_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "GPBMetadata\\Google\\Protobuf\\Any", + GPBMetadata_Google_Protobuf_Any_methods); + + GPBMetadata_Google_Protobuf_Any_ce = zend_register_internal_class(&tmp_ce); +} + +/* google_protobuf_Any */ + +zend_class_entry* google_protobuf_Any_ce; + +static PHP_METHOD(google_protobuf_Any, __construct) { + google_protobuf_any_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_Any, getTypeUrl) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "type_url"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Any, setTypeUrl) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "type_url"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Any, getValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Any, setValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +ZEND_BEGIN_ARG_INFO_EX(arginfo_is, 0, 0, 1) + ZEND_ARG_INFO(0, proto) +ZEND_END_ARG_INFO() + +static zend_function_entry google_protobuf_Any_phpmethods[] = { + PHP_ME(google_protobuf_Any, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Any, getTypeUrl, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Any, setTypeUrl, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Any, getValue, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Any, setValue, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Any, is, arginfo_is, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Any, pack, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Any, unpack, arginfo_void, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_Any_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\Any", + google_protobuf_Any_phpmethods); + + google_protobuf_Any_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_Any_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_Any_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_Any_ce, message_ce); +} + +/* google/protobuf/api.proto */ + +zend_class_entry* GPBMetadata_Google_Protobuf_Api_ce; + +const char google_protobuf_api_proto_descriptor [751] = { +'\n', '\031', 'g', 'o', 'o', 'g', 'l', 'e', '/', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '/', 'a', 'p', 'i', '.', 'p', 'r', 'o', +'t', 'o', '\022', '\017', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '\032', '$', 'g', 'o', 'o', 'g', +'l', 'e', '/', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '/', 's', 'o', 'u', 'r', 'c', 'e', '_', 'c', 'o', 'n', 't', 'e', 'x', +'t', '.', 'p', 'r', 'o', 't', 'o', '\032', '\032', 'g', 'o', 'o', 'g', 'l', 'e', '/', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '/', +'t', 'y', 'p', 'e', '.', 'p', 'r', 'o', 't', 'o', '\"', '\201', '\002', '\n', '\003', 'A', 'p', 'i', '\022', '\014', '\n', '\004', 'n', 'a', 'm', +'e', '\030', '\001', ' ', '\001', '(', '\t', '\022', '(', '\n', '\007', 'm', 'e', 't', 'h', 'o', 'd', 's', '\030', '\002', ' ', '\003', '(', '\013', '2', +'\027', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'M', 'e', 't', 'h', 'o', 'd', '\022', +'(', '\n', '\007', 'o', 'p', 't', 'i', 'o', 'n', 's', '\030', '\003', ' ', '\003', '(', '\013', '2', '\027', '.', 'g', 'o', 'o', 'g', 'l', 'e', +'.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'O', 'p', 't', 'i', 'o', 'n', '\022', '\017', '\n', '\007', 'v', 'e', 'r', 's', 'i', +'o', 'n', '\030', '\004', ' ', '\001', '(', '\t', '\022', '6', '\n', '\016', 's', 'o', 'u', 'r', 'c', 'e', '_', 'c', 'o', 'n', 't', 'e', 'x', +'t', '\030', '\005', ' ', '\001', '(', '\013', '2', '\036', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', +'.', 'S', 'o', 'u', 'r', 'c', 'e', 'C', 'o', 'n', 't', 'e', 'x', 't', '\022', '&', '\n', '\006', 'm', 'i', 'x', 'i', 'n', 's', '\030', +'\006', ' ', '\003', '(', '\013', '2', '\026', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'M', +'i', 'x', 'i', 'n', '\022', '\'', '\n', '\006', 's', 'y', 'n', 't', 'a', 'x', '\030', '\007', ' ', '\001', '(', '\016', '2', '\027', '.', 'g', 'o', +'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'S', 'y', 'n', 't', 'a', 'x', '\"', '\325', '\001', '\n', '\006', +'M', 'e', 't', 'h', 'o', 'd', '\022', '\014', '\n', '\004', 'n', 'a', 'm', 'e', '\030', '\001', ' ', '\001', '(', '\t', '\022', '\030', '\n', '\020', 'r', +'e', 'q', 'u', 'e', 's', 't', '_', 't', 'y', 'p', 'e', '_', 'u', 'r', 'l', '\030', '\002', ' ', '\001', '(', '\t', '\022', '\031', '\n', '\021', +'r', 'e', 'q', 'u', 'e', 's', 't', '_', 's', 't', 'r', 'e', 'a', 'm', 'i', 'n', 'g', '\030', '\003', ' ', '\001', '(', '\010', '\022', '\031', +'\n', '\021', 'r', 'e', 's', 'p', 'o', 'n', 's', 'e', '_', 't', 'y', 'p', 'e', '_', 'u', 'r', 'l', '\030', '\004', ' ', '\001', '(', '\t', +'\022', '\032', '\n', '\022', 'r', 'e', 's', 'p', 'o', 'n', 's', 'e', '_', 's', 't', 'r', 'e', 'a', 'm', 'i', 'n', 'g', '\030', '\005', ' ', +'\001', '(', '\010', '\022', '(', '\n', '\007', 'o', 'p', 't', 'i', 'o', 'n', 's', '\030', '\006', ' ', '\003', '(', '\013', '2', '\027', '.', 'g', 'o', +'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'O', 'p', 't', 'i', 'o', 'n', '\022', '\'', '\n', '\006', 's', +'y', 'n', 't', 'a', 'x', '\030', '\007', ' ', '\001', '(', '\016', '2', '\027', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', +'o', 'b', 'u', 'f', '.', 'S', 'y', 'n', 't', 'a', 'x', '\"', '#', '\n', '\005', 'M', 'i', 'x', 'i', 'n', '\022', '\014', '\n', '\004', 'n', +'a', 'm', 'e', '\030', '\001', ' ', '\001', '(', '\t', '\022', '\014', '\n', '\004', 'r', 'o', 'o', 't', '\030', '\002', ' ', '\001', '(', '\t', 'B', 'v', +'\n', '\023', 'c', 'o', 'm', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', 'B', '\010', 'A', 'p', +'i', 'P', 'r', 'o', 't', 'o', 'P', '\001', 'Z', ',', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'g', 'o', 'l', 'a', 'n', 'g', '.', 'o', +'r', 'g', '/', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '/', 't', 'y', 'p', 'e', 's', '/', 'k', 'n', 'o', 'w', 'n', '/', 'a', +'p', 'i', 'p', 'b', '\242', '\002', '\003', 'G', 'P', 'B', '\252', '\002', '\036', 'G', 'o', 'o', 'g', 'l', 'e', '.', 'P', 'r', 'o', 't', 'o', +'b', 'u', 'f', '.', 'W', 'e', 'l', 'l', 'K', 'n', 'o', 'w', 'n', 'T', 'y', 'p', 'e', 's', 'b', '\006', 'p', 'r', 'o', 't', 'o', +'3', +}; + +static void google_protobuf_api_proto_AddDescriptor() { + if (DescriptorPool_HasFile("google/protobuf/api.proto")) return; + google_protobuf_source_context_proto_AddDescriptor(); + google_protobuf_type_proto_AddDescriptor(); + DescriptorPool_AddDescriptor("google/protobuf/api.proto", google_protobuf_api_proto_descriptor, + sizeof(google_protobuf_api_proto_descriptor)); +} + +static PHP_METHOD(GPBMetadata_Google_Protobuf_Api, initOnce) { + google_protobuf_api_proto_AddDescriptor(); +} + +static zend_function_entry GPBMetadata_Google_Protobuf_Api_methods[] = { + PHP_ME(GPBMetadata_Google_Protobuf_Api, initOnce, arginfo_void, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + ZEND_FE_END +}; + +static void GPBMetadata_Google_Protobuf_Api_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "GPBMetadata\\Google\\Protobuf\\Api", + GPBMetadata_Google_Protobuf_Api_methods); + + GPBMetadata_Google_Protobuf_Api_ce = zend_register_internal_class(&tmp_ce); +} + +/* google_protobuf_Api */ + +zend_class_entry* google_protobuf_Api_ce; + +static PHP_METHOD(google_protobuf_Api, __construct) { + google_protobuf_api_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_Api, getName) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "name"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Api, setName) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "name"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Api, getMethods) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "methods"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Api, setMethods) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "methods"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Api, getOptions) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "options"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Api, setOptions) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "options"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Api, getVersion) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "version"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Api, setVersion) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "version"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Api, getSourceContext) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "source_context"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Api, setSourceContext) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "source_context"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Api, getMixins) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "mixins"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Api, setMixins) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "mixins"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Api, getSyntax) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "syntax"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Api, setSyntax) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "syntax"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static zend_function_entry google_protobuf_Api_phpmethods[] = { + PHP_ME(google_protobuf_Api, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Api, getName, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Api, setName, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Api, getMethods, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Api, setMethods, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Api, getOptions, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Api, setOptions, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Api, getVersion, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Api, setVersion, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Api, getSourceContext, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Api, setSourceContext, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Api, getMixins, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Api, setMixins, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Api, getSyntax, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Api, setSyntax, arginfo_setter, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_Api_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\Api", + google_protobuf_Api_phpmethods); + + google_protobuf_Api_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_Api_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_Api_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_Api_ce, message_ce); +} + +/* google_protobuf_Method */ + +zend_class_entry* google_protobuf_Method_ce; + +static PHP_METHOD(google_protobuf_Method, __construct) { + google_protobuf_api_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_Method, getName) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "name"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Method, setName) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "name"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Method, getRequestTypeUrl) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "request_type_url"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Method, setRequestTypeUrl) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "request_type_url"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Method, getRequestStreaming) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "request_streaming"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Method, setRequestStreaming) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "request_streaming"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Method, getResponseTypeUrl) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "response_type_url"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Method, setResponseTypeUrl) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "response_type_url"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Method, getResponseStreaming) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "response_streaming"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Method, setResponseStreaming) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "response_streaming"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Method, getOptions) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "options"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Method, setOptions) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "options"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Method, getSyntax) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "syntax"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Method, setSyntax) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "syntax"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static zend_function_entry google_protobuf_Method_phpmethods[] = { + PHP_ME(google_protobuf_Method, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Method, getName, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Method, setName, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Method, getRequestTypeUrl, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Method, setRequestTypeUrl, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Method, getRequestStreaming, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Method, setRequestStreaming, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Method, getResponseTypeUrl, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Method, setResponseTypeUrl, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Method, getResponseStreaming, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Method, setResponseStreaming, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Method, getOptions, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Method, setOptions, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Method, getSyntax, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Method, setSyntax, arginfo_setter, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_Method_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\Method", + google_protobuf_Method_phpmethods); + + google_protobuf_Method_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_Method_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_Method_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_Method_ce, message_ce); +} + +/* google_protobuf_Mixin */ + +zend_class_entry* google_protobuf_Mixin_ce; + +static PHP_METHOD(google_protobuf_Mixin, __construct) { + google_protobuf_api_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_Mixin, getName) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "name"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Mixin, setName) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "name"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Mixin, getRoot) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "root"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Mixin, setRoot) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "root"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static zend_function_entry google_protobuf_Mixin_phpmethods[] = { + PHP_ME(google_protobuf_Mixin, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Mixin, getName, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Mixin, setName, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Mixin, getRoot, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Mixin, setRoot, arginfo_setter, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_Mixin_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\Mixin", + google_protobuf_Mixin_phpmethods); + + google_protobuf_Mixin_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_Mixin_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_Mixin_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_Mixin_ce, message_ce); +} + +/* google/protobuf/duration.proto */ + +zend_class_entry* GPBMetadata_Google_Protobuf_Duration_ce; + +const char google_protobuf_duration_proto_descriptor [235] = { +'\n', '\036', 'g', 'o', 'o', 'g', 'l', 'e', '/', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '/', 'd', 'u', 'r', 'a', 't', 'i', 'o', +'n', '.', 'p', 'r', 'o', 't', 'o', '\022', '\017', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '\"', +'*', '\n', '\010', 'D', 'u', 'r', 'a', 't', 'i', 'o', 'n', '\022', '\017', '\n', '\007', 's', 'e', 'c', 'o', 'n', 'd', 's', '\030', '\001', ' ', +'\001', '(', '\003', '\022', '\r', '\n', '\005', 'n', 'a', 'n', 'o', 's', '\030', '\002', ' ', '\001', '(', '\005', 'B', '\203', '\001', '\n', '\023', 'c', 'o', +'m', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', 'B', '\r', 'D', 'u', 'r', 'a', 't', 'i', +'o', 'n', 'P', 'r', 'o', 't', 'o', 'P', '\001', 'Z', '1', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'g', 'o', 'l', 'a', 'n', 'g', '.', +'o', 'r', 'g', '/', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '/', 't', 'y', 'p', 'e', 's', '/', 'k', 'n', 'o', 'w', 'n', '/', +'d', 'u', 'r', 'a', 't', 'i', 'o', 'n', 'p', 'b', '\370', '\001', '\001', '\242', '\002', '\003', 'G', 'P', 'B', '\252', '\002', '\036', 'G', 'o', 'o', +'g', 'l', 'e', '.', 'P', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'W', 'e', 'l', 'l', 'K', 'n', 'o', 'w', 'n', 'T', 'y', 'p', +'e', 's', 'b', '\006', 'p', 'r', 'o', 't', 'o', '3', +}; + +static void google_protobuf_duration_proto_AddDescriptor() { + if (DescriptorPool_HasFile("google/protobuf/duration.proto")) return; + DescriptorPool_AddDescriptor("google/protobuf/duration.proto", google_protobuf_duration_proto_descriptor, + sizeof(google_protobuf_duration_proto_descriptor)); +} + +static PHP_METHOD(GPBMetadata_Google_Protobuf_Duration, initOnce) { + google_protobuf_duration_proto_AddDescriptor(); +} + +static zend_function_entry GPBMetadata_Google_Protobuf_Duration_methods[] = { + PHP_ME(GPBMetadata_Google_Protobuf_Duration, initOnce, arginfo_void, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + ZEND_FE_END +}; + +static void GPBMetadata_Google_Protobuf_Duration_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "GPBMetadata\\Google\\Protobuf\\Duration", + GPBMetadata_Google_Protobuf_Duration_methods); + + GPBMetadata_Google_Protobuf_Duration_ce = zend_register_internal_class(&tmp_ce); +} + +/* google_protobuf_Duration */ + +zend_class_entry* google_protobuf_Duration_ce; + +static PHP_METHOD(google_protobuf_Duration, __construct) { + google_protobuf_duration_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_Duration, getSeconds) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "seconds"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Duration, setSeconds) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "seconds"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Duration, getNanos) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "nanos"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Duration, setNanos) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "nanos"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static zend_function_entry google_protobuf_Duration_phpmethods[] = { + PHP_ME(google_protobuf_Duration, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Duration, getSeconds, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Duration, setSeconds, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Duration, getNanos, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Duration, setNanos, arginfo_setter, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_Duration_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\Duration", + google_protobuf_Duration_phpmethods); + + google_protobuf_Duration_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_Duration_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_Duration_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_Duration_ce, message_ce); +} + +/* google/protobuf/empty.proto */ + +zend_class_entry* GPBMetadata_Google_Protobuf_GPBEmpty_ce; + +const char google_protobuf_empty_proto_descriptor [190] = { +'\n', '\033', 'g', 'o', 'o', 'g', 'l', 'e', '/', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '/', 'e', 'm', 'p', 't', 'y', '.', 'p', +'r', 'o', 't', 'o', '\022', '\017', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '\"', '\007', '\n', '\005', +'E', 'm', 'p', 't', 'y', 'B', '}', '\n', '\023', 'c', 'o', 'm', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', +'b', 'u', 'f', 'B', '\n', 'E', 'm', 'p', 't', 'y', 'P', 'r', 'o', 't', 'o', 'P', '\001', 'Z', '.', 'g', 'o', 'o', 'g', 'l', 'e', +'.', 'g', 'o', 'l', 'a', 'n', 'g', '.', 'o', 'r', 'g', '/', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '/', 't', 'y', 'p', 'e', +'s', '/', 'k', 'n', 'o', 'w', 'n', '/', 'e', 'm', 'p', 't', 'y', 'p', 'b', '\370', '\001', '\001', '\242', '\002', '\003', 'G', 'P', 'B', '\252', +'\002', '\036', 'G', 'o', 'o', 'g', 'l', 'e', '.', 'P', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'W', 'e', 'l', 'l', 'K', 'n', 'o', +'w', 'n', 'T', 'y', 'p', 'e', 's', 'b', '\006', 'p', 'r', 'o', 't', 'o', '3', +}; + +static void google_protobuf_empty_proto_AddDescriptor() { + if (DescriptorPool_HasFile("google/protobuf/empty.proto")) return; + DescriptorPool_AddDescriptor("google/protobuf/empty.proto", google_protobuf_empty_proto_descriptor, + sizeof(google_protobuf_empty_proto_descriptor)); +} + +static PHP_METHOD(GPBMetadata_Google_Protobuf_GPBEmpty, initOnce) { + google_protobuf_empty_proto_AddDescriptor(); +} + +static zend_function_entry GPBMetadata_Google_Protobuf_GPBEmpty_methods[] = { + PHP_ME(GPBMetadata_Google_Protobuf_GPBEmpty, initOnce, arginfo_void, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + ZEND_FE_END +}; + +static void GPBMetadata_Google_Protobuf_GPBEmpty_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "GPBMetadata\\Google\\Protobuf\\GPBEmpty", + GPBMetadata_Google_Protobuf_GPBEmpty_methods); + + GPBMetadata_Google_Protobuf_GPBEmpty_ce = zend_register_internal_class(&tmp_ce); +} + +/* google_protobuf_Empty */ + +zend_class_entry* google_protobuf_Empty_ce; + +static PHP_METHOD(google_protobuf_Empty, __construct) { + google_protobuf_empty_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static zend_function_entry google_protobuf_Empty_phpmethods[] = { + PHP_ME(google_protobuf_Empty, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_Empty_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\GPBEmpty", + google_protobuf_Empty_phpmethods); + + google_protobuf_Empty_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_Empty_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_Empty_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_Empty_ce, message_ce); +} + +/* google/protobuf/field_mask.proto */ + +zend_class_entry* GPBMetadata_Google_Protobuf_FieldMask_ce; + +const char google_protobuf_field_mask_proto_descriptor [223] = { +'\n', ' ', 'g', 'o', 'o', 'g', 'l', 'e', '/', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '/', 'f', 'i', 'e', 'l', 'd', '_', 'm', +'a', 's', 'k', '.', 'p', 'r', 'o', 't', 'o', '\022', '\017', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', +'f', '\"', '\032', '\n', '\t', 'F', 'i', 'e', 'l', 'd', 'M', 'a', 's', 'k', '\022', '\r', '\n', '\005', 'p', 'a', 't', 'h', 's', '\030', '\001', +' ', '\003', '(', '\t', 'B', '\205', '\001', '\n', '\023', 'c', 'o', 'm', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', +'b', 'u', 'f', 'B', '\016', 'F', 'i', 'e', 'l', 'd', 'M', 'a', 's', 'k', 'P', 'r', 'o', 't', 'o', 'P', '\001', 'Z', '2', 'g', 'o', +'o', 'g', 'l', 'e', '.', 'g', 'o', 'l', 'a', 'n', 'g', '.', 'o', 'r', 'g', '/', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '/', +'t', 'y', 'p', 'e', 's', '/', 'k', 'n', 'o', 'w', 'n', '/', 'f', 'i', 'e', 'l', 'd', 'm', 'a', 's', 'k', 'p', 'b', '\370', '\001', +'\001', '\242', '\002', '\003', 'G', 'P', 'B', '\252', '\002', '\036', 'G', 'o', 'o', 'g', 'l', 'e', '.', 'P', 'r', 'o', 't', 'o', 'b', 'u', 'f', +'.', 'W', 'e', 'l', 'l', 'K', 'n', 'o', 'w', 'n', 'T', 'y', 'p', 'e', 's', 'b', '\006', 'p', 'r', 'o', 't', 'o', '3', +}; + +static void google_protobuf_field_mask_proto_AddDescriptor() { + if (DescriptorPool_HasFile("google/protobuf/field_mask.proto")) return; + DescriptorPool_AddDescriptor("google/protobuf/field_mask.proto", google_protobuf_field_mask_proto_descriptor, + sizeof(google_protobuf_field_mask_proto_descriptor)); +} + +static PHP_METHOD(GPBMetadata_Google_Protobuf_FieldMask, initOnce) { + google_protobuf_field_mask_proto_AddDescriptor(); +} + +static zend_function_entry GPBMetadata_Google_Protobuf_FieldMask_methods[] = { + PHP_ME(GPBMetadata_Google_Protobuf_FieldMask, initOnce, arginfo_void, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + ZEND_FE_END +}; + +static void GPBMetadata_Google_Protobuf_FieldMask_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "GPBMetadata\\Google\\Protobuf\\FieldMask", + GPBMetadata_Google_Protobuf_FieldMask_methods); + + GPBMetadata_Google_Protobuf_FieldMask_ce = zend_register_internal_class(&tmp_ce); +} + +/* google_protobuf_FieldMask */ + +zend_class_entry* google_protobuf_FieldMask_ce; + +static PHP_METHOD(google_protobuf_FieldMask, __construct) { + google_protobuf_field_mask_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_FieldMask, getPaths) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "paths"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_FieldMask, setPaths) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "paths"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static zend_function_entry google_protobuf_FieldMask_phpmethods[] = { + PHP_ME(google_protobuf_FieldMask, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_FieldMask, getPaths, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_FieldMask, setPaths, arginfo_setter, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_FieldMask_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\FieldMask", + google_protobuf_FieldMask_phpmethods); + + google_protobuf_FieldMask_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_FieldMask_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_FieldMask_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_FieldMask_ce, message_ce); +} + +/* google/protobuf/source_context.proto */ + +zend_class_entry* GPBMetadata_Google_Protobuf_SourceContext_ce; + +const char google_protobuf_source_context_proto_descriptor [240] = { +'\n', '$', 'g', 'o', 'o', 'g', 'l', 'e', '/', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '/', 's', 'o', 'u', 'r', 'c', 'e', '_', +'c', 'o', 'n', 't', 'e', 'x', 't', '.', 'p', 'r', 'o', 't', 'o', '\022', '\017', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', +'t', 'o', 'b', 'u', 'f', '\"', '\"', '\n', '\r', 'S', 'o', 'u', 'r', 'c', 'e', 'C', 'o', 'n', 't', 'e', 'x', 't', '\022', '\021', '\n', +'\t', 'f', 'i', 'l', 'e', '_', 'n', 'a', 'm', 'e', '\030', '\001', ' ', '\001', '(', '\t', 'B', '\212', '\001', '\n', '\023', 'c', 'o', 'm', '.', +'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', 'B', '\022', 'S', 'o', 'u', 'r', 'c', 'e', 'C', 'o', +'n', 't', 'e', 'x', 't', 'P', 'r', 'o', 't', 'o', 'P', '\001', 'Z', '6', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'g', 'o', 'l', 'a', +'n', 'g', '.', 'o', 'r', 'g', '/', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '/', 't', 'y', 'p', 'e', 's', '/', 'k', 'n', 'o', +'w', 'n', '/', 's', 'o', 'u', 'r', 'c', 'e', 'c', 'o', 'n', 't', 'e', 'x', 't', 'p', 'b', '\242', '\002', '\003', 'G', 'P', 'B', '\252', +'\002', '\036', 'G', 'o', 'o', 'g', 'l', 'e', '.', 'P', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'W', 'e', 'l', 'l', 'K', 'n', 'o', +'w', 'n', 'T', 'y', 'p', 'e', 's', 'b', '\006', 'p', 'r', 'o', 't', 'o', '3', +}; + +static void google_protobuf_source_context_proto_AddDescriptor() { + if (DescriptorPool_HasFile("google/protobuf/source_context.proto")) return; + DescriptorPool_AddDescriptor("google/protobuf/source_context.proto", google_protobuf_source_context_proto_descriptor, + sizeof(google_protobuf_source_context_proto_descriptor)); +} + +static PHP_METHOD(GPBMetadata_Google_Protobuf_SourceContext, initOnce) { + google_protobuf_source_context_proto_AddDescriptor(); +} + +static zend_function_entry GPBMetadata_Google_Protobuf_SourceContext_methods[] = { + PHP_ME(GPBMetadata_Google_Protobuf_SourceContext, initOnce, arginfo_void, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + ZEND_FE_END +}; + +static void GPBMetadata_Google_Protobuf_SourceContext_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "GPBMetadata\\Google\\Protobuf\\SourceContext", + GPBMetadata_Google_Protobuf_SourceContext_methods); + + GPBMetadata_Google_Protobuf_SourceContext_ce = zend_register_internal_class(&tmp_ce); +} + +/* google_protobuf_SourceContext */ + +zend_class_entry* google_protobuf_SourceContext_ce; + +static PHP_METHOD(google_protobuf_SourceContext, __construct) { + google_protobuf_source_context_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_SourceContext, getFileName) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "file_name"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_SourceContext, setFileName) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "file_name"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static zend_function_entry google_protobuf_SourceContext_phpmethods[] = { + PHP_ME(google_protobuf_SourceContext, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_SourceContext, getFileName, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_SourceContext, setFileName, arginfo_setter, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_SourceContext_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\SourceContext", + google_protobuf_SourceContext_phpmethods); + + google_protobuf_SourceContext_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_SourceContext_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_SourceContext_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_SourceContext_ce, message_ce); +} + +/* google/protobuf/struct.proto */ + +zend_class_entry* GPBMetadata_Google_Protobuf_Struct_ce; + +const char google_protobuf_struct_proto_descriptor [638] = { +'\n', '\034', 'g', 'o', 'o', 'g', 'l', 'e', '/', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '/', 's', 't', 'r', 'u', 'c', 't', '.', +'p', 'r', 'o', 't', 'o', '\022', '\017', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '\"', '\204', '\001', +'\n', '\006', 'S', 't', 'r', 'u', 'c', 't', '\022', '3', '\n', '\006', 'f', 'i', 'e', 'l', 'd', 's', '\030', '\001', ' ', '\003', '(', '\013', '2', +'#', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'S', 't', 'r', 'u', 'c', 't', '.', +'F', 'i', 'e', 'l', 'd', 's', 'E', 'n', 't', 'r', 'y', '\032', 'E', '\n', '\013', 'F', 'i', 'e', 'l', 'd', 's', 'E', 'n', 't', 'r', +'y', '\022', '\013', '\n', '\003', 'k', 'e', 'y', '\030', '\001', ' ', '\001', '(', '\t', '\022', '%', '\n', '\005', 'v', 'a', 'l', 'u', 'e', '\030', '\002', +' ', '\001', '(', '\013', '2', '\026', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'V', 'a', +'l', 'u', 'e', ':', '\002', '8', '\001', '\"', '\352', '\001', '\n', '\005', 'V', 'a', 'l', 'u', 'e', '\022', '0', '\n', '\n', 'n', 'u', 'l', 'l', +'_', 'v', 'a', 'l', 'u', 'e', '\030', '\001', ' ', '\001', '(', '\016', '2', '\032', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', +'t', 'o', 'b', 'u', 'f', '.', 'N', 'u', 'l', 'l', 'V', 'a', 'l', 'u', 'e', 'H', '\000', '\022', '\026', '\n', '\014', 'n', 'u', 'm', 'b', +'e', 'r', '_', 'v', 'a', 'l', 'u', 'e', '\030', '\002', ' ', '\001', '(', '\001', 'H', '\000', '\022', '\026', '\n', '\014', 's', 't', 'r', 'i', 'n', +'g', '_', 'v', 'a', 'l', 'u', 'e', '\030', '\003', ' ', '\001', '(', '\t', 'H', '\000', '\022', '\024', '\n', '\n', 'b', 'o', 'o', 'l', '_', 'v', +'a', 'l', 'u', 'e', '\030', '\004', ' ', '\001', '(', '\010', 'H', '\000', '\022', '/', '\n', '\014', 's', 't', 'r', 'u', 'c', 't', '_', 'v', 'a', +'l', 'u', 'e', '\030', '\005', ' ', '\001', '(', '\013', '2', '\027', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', +'u', 'f', '.', 'S', 't', 'r', 'u', 'c', 't', 'H', '\000', '\022', '0', '\n', '\n', 'l', 'i', 's', 't', '_', 'v', 'a', 'l', 'u', 'e', +'\030', '\006', ' ', '\001', '(', '\013', '2', '\032', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', +'L', 'i', 's', 't', 'V', 'a', 'l', 'u', 'e', 'H', '\000', 'B', '\006', '\n', '\004', 'k', 'i', 'n', 'd', '\"', '3', '\n', '\t', 'L', 'i', +'s', 't', 'V', 'a', 'l', 'u', 'e', '\022', '&', '\n', '\006', 'v', 'a', 'l', 'u', 'e', 's', '\030', '\001', ' ', '\003', '(', '\013', '2', '\026', +'.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'V', 'a', 'l', 'u', 'e', '*', '\033', '\n', +'\t', 'N', 'u', 'l', 'l', 'V', 'a', 'l', 'u', 'e', '\022', '\016', '\n', '\n', 'N', 'U', 'L', 'L', '_', 'V', 'A', 'L', 'U', 'E', '\020', +'\000', 'B', '\177', '\n', '\023', 'c', 'o', 'm', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', 'B', +'\013', 'S', 't', 'r', 'u', 'c', 't', 'P', 'r', 'o', 't', 'o', 'P', '\001', 'Z', '/', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'g', 'o', +'l', 'a', 'n', 'g', '.', 'o', 'r', 'g', '/', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '/', 't', 'y', 'p', 'e', 's', '/', 'k', +'n', 'o', 'w', 'n', '/', 's', 't', 'r', 'u', 'c', 't', 'p', 'b', '\370', '\001', '\001', '\242', '\002', '\003', 'G', 'P', 'B', '\252', '\002', '\036', +'G', 'o', 'o', 'g', 'l', 'e', '.', 'P', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'W', 'e', 'l', 'l', 'K', 'n', 'o', 'w', 'n', +'T', 'y', 'p', 'e', 's', 'b', '\006', 'p', 'r', 'o', 't', 'o', '3', +}; + +static void google_protobuf_struct_proto_AddDescriptor() { + if (DescriptorPool_HasFile("google/protobuf/struct.proto")) return; + DescriptorPool_AddDescriptor("google/protobuf/struct.proto", google_protobuf_struct_proto_descriptor, + sizeof(google_protobuf_struct_proto_descriptor)); +} + +static PHP_METHOD(GPBMetadata_Google_Protobuf_Struct, initOnce) { + google_protobuf_struct_proto_AddDescriptor(); +} + +static zend_function_entry GPBMetadata_Google_Protobuf_Struct_methods[] = { + PHP_ME(GPBMetadata_Google_Protobuf_Struct, initOnce, arginfo_void, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + ZEND_FE_END +}; + +static void GPBMetadata_Google_Protobuf_Struct_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "GPBMetadata\\Google\\Protobuf\\Struct", + GPBMetadata_Google_Protobuf_Struct_methods); + + GPBMetadata_Google_Protobuf_Struct_ce = zend_register_internal_class(&tmp_ce); +} + +/* google_protobuf_Struct */ + +zend_class_entry* google_protobuf_Struct_ce; + +static PHP_METHOD(google_protobuf_Struct, __construct) { + google_protobuf_struct_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_Struct, getFields) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "fields"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Struct, setFields) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "fields"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static zend_function_entry google_protobuf_Struct_phpmethods[] = { + PHP_ME(google_protobuf_Struct, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Struct, getFields, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Struct, setFields, arginfo_setter, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_Struct_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\Struct", + google_protobuf_Struct_phpmethods); + + google_protobuf_Struct_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_Struct_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_Struct_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_Struct_ce, message_ce); +} + +/* google_protobuf_Struct_FieldsEntry */ + +zend_class_entry* google_protobuf_Struct_FieldsEntry_ce; + +static PHP_METHOD(google_protobuf_Struct_FieldsEntry, __construct) { + google_protobuf_struct_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_Struct_FieldsEntry, getKey) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "key"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Struct_FieldsEntry, setKey) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "key"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Struct_FieldsEntry, getValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Struct_FieldsEntry, setValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static zend_function_entry google_protobuf_Struct_FieldsEntry_phpmethods[] = { + PHP_ME(google_protobuf_Struct_FieldsEntry, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Struct_FieldsEntry, getKey, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Struct_FieldsEntry, setKey, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Struct_FieldsEntry, getValue, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Struct_FieldsEntry, setValue, arginfo_setter, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_Struct_FieldsEntry_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\Struct\\FieldsEntry", + google_protobuf_Struct_FieldsEntry_phpmethods); + + google_protobuf_Struct_FieldsEntry_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_Struct_FieldsEntry_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_Struct_FieldsEntry_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_Struct_FieldsEntry_ce, message_ce); +} + +/* google_protobuf_Value */ + +zend_class_entry* google_protobuf_Value_ce; + +static PHP_METHOD(google_protobuf_Value, __construct) { + google_protobuf_struct_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_Value, getNullValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "null_value"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Value, setNullValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "null_value"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Value, getNumberValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "number_value"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Value, setNumberValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "number_value"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Value, getStringValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "string_value"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Value, setStringValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "string_value"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Value, getBoolValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "bool_value"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Value, setBoolValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "bool_value"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Value, getStructValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "struct_value"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Value, setStructValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "struct_value"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Value, getListValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "list_value"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Value, setListValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "list_value"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Value, getKind) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_oneofdef *oneof = upb_msgdef_ntooz(intern->desc->msgdef, + "kind"); + const upb_fielddef *field = upb_msg_whichoneof(intern->msg, oneof); + RETURN_STRING(field ? upb_fielddef_name(field) : ""); +} +static zend_function_entry google_protobuf_Value_phpmethods[] = { + PHP_ME(google_protobuf_Value, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Value, getNullValue, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Value, setNullValue, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Value, getNumberValue, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Value, setNumberValue, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Value, getStringValue, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Value, setStringValue, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Value, getBoolValue, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Value, setBoolValue, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Value, getStructValue, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Value, setStructValue, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Value, getListValue, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Value, setListValue, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Value, getKind, arginfo_void, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_Value_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\Value", + google_protobuf_Value_phpmethods); + + google_protobuf_Value_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_Value_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_Value_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_Value_ce, message_ce); +} + +/* google_protobuf_ListValue */ + +zend_class_entry* google_protobuf_ListValue_ce; + +static PHP_METHOD(google_protobuf_ListValue, __construct) { + google_protobuf_struct_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_ListValue, getValues) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "values"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_ListValue, setValues) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "values"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static zend_function_entry google_protobuf_ListValue_phpmethods[] = { + PHP_ME(google_protobuf_ListValue, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_ListValue, getValues, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_ListValue, setValues, arginfo_setter, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_ListValue_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\ListValue", + google_protobuf_ListValue_phpmethods); + + google_protobuf_ListValue_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_ListValue_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_ListValue_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_ListValue_ce, message_ce); +} + +/* google_protobuf_NullValue */ + +zend_class_entry* google_protobuf_NullValue_ce; + +PHP_METHOD(google_protobuf_NullValue, name) { + google_protobuf_struct_proto_AddDescriptor(); + const upb_symtab *symtab = DescriptorPool_GetSymbolTable(); + const upb_enumdef *e = upb_symtab_lookupenum(symtab, "google.protobuf.NullValue"); + const char *name; + zend_long value; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &value) == + FAILURE) { + return; + } + name = upb_enumdef_iton(e, value); + if (!name) { + zend_throw_exception_ex(NULL, 0, + "Google\\Protobuf\\NullValue has no name " + "defined for value " ZEND_LONG_FMT ".", + value); + return; + } + RETURN_STRING(name); +} + +PHP_METHOD(google_protobuf_NullValue, value) { + google_protobuf_struct_proto_AddDescriptor(); + const upb_symtab *symtab = DescriptorPool_GetSymbolTable(); + const upb_enumdef *e = upb_symtab_lookupenum(symtab, "google.protobuf.NullValue"); + char *name = NULL; + size_t name_len; + int32_t num; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &name, + &name_len) == FAILURE) { + return; + } + if (!upb_enumdef_ntoi(e, name, name_len, &num)) { + zend_throw_exception_ex(NULL, 0, + "Google\\Protobuf\\NullValue has no value " + "defined for name %s.", + name); + return; + } + RETURN_LONG(num); +} + +static zend_function_entry google_protobuf_NullValue_phpmethods[] = { + PHP_ME(google_protobuf_NullValue, name, arginfo_lookup, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + PHP_ME(google_protobuf_NullValue, value, arginfo_lookup, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + ZEND_FE_END +}; + +static void google_protobuf_NullValue_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\NullValue", + google_protobuf_NullValue_phpmethods); + + google_protobuf_NullValue_ce = zend_register_internal_class(&tmp_ce); + zend_declare_class_constant_long(google_protobuf_NullValue_ce, "NULL_VALUE", + strlen("NULL_VALUE"), 0); +} + +/* google/protobuf/type.proto */ + +zend_class_entry* GPBMetadata_Google_Protobuf_Type_ce; + +const char google_protobuf_type_proto_descriptor [1592] = { +'\n', '\032', 'g', 'o', 'o', 'g', 'l', 'e', '/', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '/', 't', 'y', 'p', 'e', '.', 'p', 'r', +'o', 't', 'o', '\022', '\017', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '\032', '\031', 'g', 'o', 'o', +'g', 'l', 'e', '/', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '/', 'a', 'n', 'y', '.', 'p', 'r', 'o', 't', 'o', '\032', '$', 'g', +'o', 'o', 'g', 'l', 'e', '/', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '/', 's', 'o', 'u', 'r', 'c', 'e', '_', 'c', 'o', 'n', +'t', 'e', 'x', 't', '.', 'p', 'r', 'o', 't', 'o', '\"', '\327', '\001', '\n', '\004', 'T', 'y', 'p', 'e', '\022', '\014', '\n', '\004', 'n', 'a', +'m', 'e', '\030', '\001', ' ', '\001', '(', '\t', '\022', '&', '\n', '\006', 'f', 'i', 'e', 'l', 'd', 's', '\030', '\002', ' ', '\003', '(', '\013', '2', +'\026', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'F', 'i', 'e', 'l', 'd', '\022', '\016', +'\n', '\006', 'o', 'n', 'e', 'o', 'f', 's', '\030', '\003', ' ', '\003', '(', '\t', '\022', '(', '\n', '\007', 'o', 'p', 't', 'i', 'o', 'n', 's', +'\030', '\004', ' ', '\003', '(', '\013', '2', '\027', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', +'O', 'p', 't', 'i', 'o', 'n', '\022', '6', '\n', '\016', 's', 'o', 'u', 'r', 'c', 'e', '_', 'c', 'o', 'n', 't', 'e', 'x', 't', '\030', +'\005', ' ', '\001', '(', '\013', '2', '\036', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'S', +'o', 'u', 'r', 'c', 'e', 'C', 'o', 'n', 't', 'e', 'x', 't', '\022', '\'', '\n', '\006', 's', 'y', 'n', 't', 'a', 'x', '\030', '\006', ' ', +'\001', '(', '\016', '2', '\027', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'S', 'y', 'n', +'t', 'a', 'x', '\"', '\325', '\005', '\n', '\005', 'F', 'i', 'e', 'l', 'd', '\022', ')', '\n', '\004', 'k', 'i', 'n', 'd', '\030', '\001', ' ', '\001', +'(', '\016', '2', '\033', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'F', 'i', 'e', 'l', +'d', '.', 'K', 'i', 'n', 'd', '\022', '7', '\n', '\013', 'c', 'a', 'r', 'd', 'i', 'n', 'a', 'l', 'i', 't', 'y', '\030', '\002', ' ', '\001', +'(', '\016', '2', '\"', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'F', 'i', 'e', 'l', +'d', '.', 'C', 'a', 'r', 'd', 'i', 'n', 'a', 'l', 'i', 't', 'y', '\022', '\016', '\n', '\006', 'n', 'u', 'm', 'b', 'e', 'r', '\030', '\003', +' ', '\001', '(', '\005', '\022', '\014', '\n', '\004', 'n', 'a', 'm', 'e', '\030', '\004', ' ', '\001', '(', '\t', '\022', '\020', '\n', '\010', 't', 'y', 'p', +'e', '_', 'u', 'r', 'l', '\030', '\006', ' ', '\001', '(', '\t', '\022', '\023', '\n', '\013', 'o', 'n', 'e', 'o', 'f', '_', 'i', 'n', 'd', 'e', +'x', '\030', '\007', ' ', '\001', '(', '\005', '\022', '\016', '\n', '\006', 'p', 'a', 'c', 'k', 'e', 'd', '\030', '\010', ' ', '\001', '(', '\010', '\022', '(', +'\n', '\007', 'o', 'p', 't', 'i', 'o', 'n', 's', '\030', '\t', ' ', '\003', '(', '\013', '2', '\027', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', +'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'O', 'p', 't', 'i', 'o', 'n', '\022', '\021', '\n', '\t', 'j', 's', 'o', 'n', '_', 'n', +'a', 'm', 'e', '\030', '\n', ' ', '\001', '(', '\t', '\022', '\025', '\n', '\r', 'd', 'e', 'f', 'a', 'u', 'l', 't', '_', 'v', 'a', 'l', 'u', +'e', '\030', '\013', ' ', '\001', '(', '\t', '\"', '\310', '\002', '\n', '\004', 'K', 'i', 'n', 'd', '\022', '\020', '\n', '\014', 'T', 'Y', 'P', 'E', '_', +'U', 'N', 'K', 'N', 'O', 'W', 'N', '\020', '\000', '\022', '\017', '\n', '\013', 'T', 'Y', 'P', 'E', '_', 'D', 'O', 'U', 'B', 'L', 'E', '\020', +'\001', '\022', '\016', '\n', '\n', 'T', 'Y', 'P', 'E', '_', 'F', 'L', 'O', 'A', 'T', '\020', '\002', '\022', '\016', '\n', '\n', 'T', 'Y', 'P', 'E', +'_', 'I', 'N', 'T', '6', '4', '\020', '\003', '\022', '\017', '\n', '\013', 'T', 'Y', 'P', 'E', '_', 'U', 'I', 'N', 'T', '6', '4', '\020', '\004', +'\022', '\016', '\n', '\n', 'T', 'Y', 'P', 'E', '_', 'I', 'N', 'T', '3', '2', '\020', '\005', '\022', '\020', '\n', '\014', 'T', 'Y', 'P', 'E', '_', +'F', 'I', 'X', 'E', 'D', '6', '4', '\020', '\006', '\022', '\020', '\n', '\014', 'T', 'Y', 'P', 'E', '_', 'F', 'I', 'X', 'E', 'D', '3', '2', +'\020', '\007', '\022', '\r', '\n', '\t', 'T', 'Y', 'P', 'E', '_', 'B', 'O', 'O', 'L', '\020', '\010', '\022', '\017', '\n', '\013', 'T', 'Y', 'P', 'E', +'_', 'S', 'T', 'R', 'I', 'N', 'G', '\020', '\t', '\022', '\016', '\n', '\n', 'T', 'Y', 'P', 'E', '_', 'G', 'R', 'O', 'U', 'P', '\020', '\n', +'\022', '\020', '\n', '\014', 'T', 'Y', 'P', 'E', '_', 'M', 'E', 'S', 'S', 'A', 'G', 'E', '\020', '\013', '\022', '\016', '\n', '\n', 'T', 'Y', 'P', +'E', '_', 'B', 'Y', 'T', 'E', 'S', '\020', '\014', '\022', '\017', '\n', '\013', 'T', 'Y', 'P', 'E', '_', 'U', 'I', 'N', 'T', '3', '2', '\020', +'\r', '\022', '\r', '\n', '\t', 'T', 'Y', 'P', 'E', '_', 'E', 'N', 'U', 'M', '\020', '\016', '\022', '\021', '\n', '\r', 'T', 'Y', 'P', 'E', '_', +'S', 'F', 'I', 'X', 'E', 'D', '3', '2', '\020', '\017', '\022', '\021', '\n', '\r', 'T', 'Y', 'P', 'E', '_', 'S', 'F', 'I', 'X', 'E', 'D', +'6', '4', '\020', '\020', '\022', '\017', '\n', '\013', 'T', 'Y', 'P', 'E', '_', 'S', 'I', 'N', 'T', '3', '2', '\020', '\021', '\022', '\017', '\n', '\013', +'T', 'Y', 'P', 'E', '_', 'S', 'I', 'N', 'T', '6', '4', '\020', '\022', '\"', 't', '\n', '\013', 'C', 'a', 'r', 'd', 'i', 'n', 'a', 'l', +'i', 't', 'y', '\022', '\027', '\n', '\023', 'C', 'A', 'R', 'D', 'I', 'N', 'A', 'L', 'I', 'T', 'Y', '_', 'U', 'N', 'K', 'N', 'O', 'W', +'N', '\020', '\000', '\022', '\030', '\n', '\024', 'C', 'A', 'R', 'D', 'I', 'N', 'A', 'L', 'I', 'T', 'Y', '_', 'O', 'P', 'T', 'I', 'O', 'N', +'A', 'L', '\020', '\001', '\022', '\030', '\n', '\024', 'C', 'A', 'R', 'D', 'I', 'N', 'A', 'L', 'I', 'T', 'Y', '_', 'R', 'E', 'Q', 'U', 'I', +'R', 'E', 'D', '\020', '\002', '\022', '\030', '\n', '\024', 'C', 'A', 'R', 'D', 'I', 'N', 'A', 'L', 'I', 'T', 'Y', '_', 'R', 'E', 'P', 'E', +'A', 'T', 'E', 'D', '\020', '\003', '\"', '\316', '\001', '\n', '\004', 'E', 'n', 'u', 'm', '\022', '\014', '\n', '\004', 'n', 'a', 'm', 'e', '\030', '\001', +' ', '\001', '(', '\t', '\022', '-', '\n', '\t', 'e', 'n', 'u', 'm', 'v', 'a', 'l', 'u', 'e', '\030', '\002', ' ', '\003', '(', '\013', '2', '\032', +'.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'E', 'n', 'u', 'm', 'V', 'a', 'l', 'u', +'e', '\022', '(', '\n', '\007', 'o', 'p', 't', 'i', 'o', 'n', 's', '\030', '\003', ' ', '\003', '(', '\013', '2', '\027', '.', 'g', 'o', 'o', 'g', +'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'O', 'p', 't', 'i', 'o', 'n', '\022', '6', '\n', '\016', 's', 'o', 'u', +'r', 'c', 'e', '_', 'c', 'o', 'n', 't', 'e', 'x', 't', '\030', '\004', ' ', '\001', '(', '\013', '2', '\036', '.', 'g', 'o', 'o', 'g', 'l', +'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'S', 'o', 'u', 'r', 'c', 'e', 'C', 'o', 'n', 't', 'e', 'x', 't', '\022', +'\'', '\n', '\006', 's', 'y', 'n', 't', 'a', 'x', '\030', '\005', ' ', '\001', '(', '\016', '2', '\027', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', +'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'S', 'y', 'n', 't', 'a', 'x', '\"', 'S', '\n', '\t', 'E', 'n', 'u', 'm', 'V', 'a', +'l', 'u', 'e', '\022', '\014', '\n', '\004', 'n', 'a', 'm', 'e', '\030', '\001', ' ', '\001', '(', '\t', '\022', '\016', '\n', '\006', 'n', 'u', 'm', 'b', +'e', 'r', '\030', '\002', ' ', '\001', '(', '\005', '\022', '(', '\n', '\007', 'o', 'p', 't', 'i', 'o', 'n', 's', '\030', '\003', ' ', '\003', '(', '\013', +'2', '\027', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'O', 'p', 't', 'i', 'o', 'n', +'\"', ';', '\n', '\006', 'O', 'p', 't', 'i', 'o', 'n', '\022', '\014', '\n', '\004', 'n', 'a', 'm', 'e', '\030', '\001', ' ', '\001', '(', '\t', '\022', +'#', '\n', '\005', 'v', 'a', 'l', 'u', 'e', '\030', '\002', ' ', '\001', '(', '\013', '2', '\024', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', +'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'A', 'n', 'y', '*', '.', '\n', '\006', 'S', 'y', 'n', 't', 'a', 'x', '\022', '\021', '\n', '\r', +'S', 'Y', 'N', 'T', 'A', 'X', '_', 'P', 'R', 'O', 'T', 'O', '2', '\020', '\000', '\022', '\021', '\n', '\r', 'S', 'Y', 'N', 'T', 'A', 'X', +'_', 'P', 'R', 'O', 'T', 'O', '3', '\020', '\001', 'B', '{', '\n', '\023', 'c', 'o', 'm', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', +'r', 'o', 't', 'o', 'b', 'u', 'f', 'B', '\t', 'T', 'y', 'p', 'e', 'P', 'r', 'o', 't', 'o', 'P', '\001', 'Z', '-', 'g', 'o', 'o', +'g', 'l', 'e', '.', 'g', 'o', 'l', 'a', 'n', 'g', '.', 'o', 'r', 'g', '/', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '/', 't', +'y', 'p', 'e', 's', '/', 'k', 'n', 'o', 'w', 'n', '/', 't', 'y', 'p', 'e', 'p', 'b', '\370', '\001', '\001', '\242', '\002', '\003', 'G', 'P', +'B', '\252', '\002', '\036', 'G', 'o', 'o', 'g', 'l', 'e', '.', 'P', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'W', 'e', 'l', 'l', 'K', +'n', 'o', 'w', 'n', 'T', 'y', 'p', 'e', 's', 'b', '\006', 'p', 'r', 'o', 't', 'o', '3', +}; + +static void google_protobuf_type_proto_AddDescriptor() { + if (DescriptorPool_HasFile("google/protobuf/type.proto")) return; + google_protobuf_any_proto_AddDescriptor(); + google_protobuf_source_context_proto_AddDescriptor(); + DescriptorPool_AddDescriptor("google/protobuf/type.proto", google_protobuf_type_proto_descriptor, + sizeof(google_protobuf_type_proto_descriptor)); +} + +static PHP_METHOD(GPBMetadata_Google_Protobuf_Type, initOnce) { + google_protobuf_type_proto_AddDescriptor(); +} + +static zend_function_entry GPBMetadata_Google_Protobuf_Type_methods[] = { + PHP_ME(GPBMetadata_Google_Protobuf_Type, initOnce, arginfo_void, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + ZEND_FE_END +}; + +static void GPBMetadata_Google_Protobuf_Type_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "GPBMetadata\\Google\\Protobuf\\Type", + GPBMetadata_Google_Protobuf_Type_methods); + + GPBMetadata_Google_Protobuf_Type_ce = zend_register_internal_class(&tmp_ce); +} + +/* google_protobuf_Type */ + +zend_class_entry* google_protobuf_Type_ce; + +static PHP_METHOD(google_protobuf_Type, __construct) { + google_protobuf_type_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_Type, getName) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "name"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Type, setName) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "name"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Type, getFields) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "fields"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Type, setFields) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "fields"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Type, getOneofs) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "oneofs"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Type, setOneofs) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "oneofs"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Type, getOptions) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "options"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Type, setOptions) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "options"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Type, getSourceContext) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "source_context"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Type, setSourceContext) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "source_context"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Type, getSyntax) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "syntax"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Type, setSyntax) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "syntax"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static zend_function_entry google_protobuf_Type_phpmethods[] = { + PHP_ME(google_protobuf_Type, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Type, getName, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Type, setName, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Type, getFields, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Type, setFields, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Type, getOneofs, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Type, setOneofs, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Type, getOptions, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Type, setOptions, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Type, getSourceContext, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Type, setSourceContext, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Type, getSyntax, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Type, setSyntax, arginfo_setter, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_Type_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\Type", + google_protobuf_Type_phpmethods); + + google_protobuf_Type_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_Type_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_Type_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_Type_ce, message_ce); +} + +/* google_protobuf_Field */ + +zend_class_entry* google_protobuf_Field_ce; + +static PHP_METHOD(google_protobuf_Field, __construct) { + google_protobuf_type_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_Field, getKind) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "kind"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Field, setKind) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "kind"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Field, getCardinality) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "cardinality"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Field, setCardinality) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "cardinality"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Field, getNumber) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "number"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Field, setNumber) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "number"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Field, getName) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "name"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Field, setName) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "name"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Field, getTypeUrl) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "type_url"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Field, setTypeUrl) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "type_url"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Field, getOneofIndex) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "oneof_index"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Field, setOneofIndex) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "oneof_index"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Field, getPacked) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "packed"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Field, setPacked) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "packed"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Field, getOptions) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "options"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Field, setOptions) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "options"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Field, getJsonName) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "json_name"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Field, setJsonName) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "json_name"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Field, getDefaultValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "default_value"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Field, setDefaultValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "default_value"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static zend_function_entry google_protobuf_Field_phpmethods[] = { + PHP_ME(google_protobuf_Field, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Field, getKind, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Field, setKind, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Field, getCardinality, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Field, setCardinality, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Field, getNumber, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Field, setNumber, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Field, getName, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Field, setName, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Field, getTypeUrl, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Field, setTypeUrl, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Field, getOneofIndex, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Field, setOneofIndex, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Field, getPacked, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Field, setPacked, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Field, getOptions, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Field, setOptions, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Field, getJsonName, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Field, setJsonName, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Field, getDefaultValue, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Field, setDefaultValue, arginfo_setter, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_Field_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\Field", + google_protobuf_Field_phpmethods); + + google_protobuf_Field_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_Field_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_Field_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_Field_ce, message_ce); +} + +/* google_protobuf_Field_Kind */ + +zend_class_entry* google_protobuf_Field_Kind_ce; + +PHP_METHOD(google_protobuf_Field_Kind, name) { + google_protobuf_type_proto_AddDescriptor(); + const upb_symtab *symtab = DescriptorPool_GetSymbolTable(); + const upb_enumdef *e = upb_symtab_lookupenum(symtab, "google.protobuf.Field.Kind"); + const char *name; + zend_long value; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &value) == + FAILURE) { + return; + } + name = upb_enumdef_iton(e, value); + if (!name) { + zend_throw_exception_ex(NULL, 0, + "Google\\Protobuf\\Field\\Kind has no name " + "defined for value " ZEND_LONG_FMT ".", + value); + return; + } + RETURN_STRING(name); +} + +PHP_METHOD(google_protobuf_Field_Kind, value) { + google_protobuf_type_proto_AddDescriptor(); + const upb_symtab *symtab = DescriptorPool_GetSymbolTable(); + const upb_enumdef *e = upb_symtab_lookupenum(symtab, "google.protobuf.Field.Kind"); + char *name = NULL; + size_t name_len; + int32_t num; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &name, + &name_len) == FAILURE) { + return; + } + if (!upb_enumdef_ntoi(e, name, name_len, &num)) { + zend_throw_exception_ex(NULL, 0, + "Google\\Protobuf\\Field\\Kind has no value " + "defined for name %s.", + name); + return; + } + RETURN_LONG(num); +} + +static zend_function_entry google_protobuf_Field_Kind_phpmethods[] = { + PHP_ME(google_protobuf_Field_Kind, name, arginfo_lookup, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + PHP_ME(google_protobuf_Field_Kind, value, arginfo_lookup, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + ZEND_FE_END +}; + +static void google_protobuf_Field_Kind_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\Field\\Kind", + google_protobuf_Field_Kind_phpmethods); + + google_protobuf_Field_Kind_ce = zend_register_internal_class(&tmp_ce); + zend_declare_class_constant_long(google_protobuf_Field_Kind_ce, "TYPE_UNKNOWN", + strlen("TYPE_UNKNOWN"), 0); + zend_declare_class_constant_long(google_protobuf_Field_Kind_ce, "TYPE_DOUBLE", + strlen("TYPE_DOUBLE"), 1); + zend_declare_class_constant_long(google_protobuf_Field_Kind_ce, "TYPE_FLOAT", + strlen("TYPE_FLOAT"), 2); + zend_declare_class_constant_long(google_protobuf_Field_Kind_ce, "TYPE_INT64", + strlen("TYPE_INT64"), 3); + zend_declare_class_constant_long(google_protobuf_Field_Kind_ce, "TYPE_UINT64", + strlen("TYPE_UINT64"), 4); + zend_declare_class_constant_long(google_protobuf_Field_Kind_ce, "TYPE_INT32", + strlen("TYPE_INT32"), 5); + zend_declare_class_constant_long(google_protobuf_Field_Kind_ce, "TYPE_FIXED64", + strlen("TYPE_FIXED64"), 6); + zend_declare_class_constant_long(google_protobuf_Field_Kind_ce, "TYPE_FIXED32", + strlen("TYPE_FIXED32"), 7); + zend_declare_class_constant_long(google_protobuf_Field_Kind_ce, "TYPE_BOOL", + strlen("TYPE_BOOL"), 8); + zend_declare_class_constant_long(google_protobuf_Field_Kind_ce, "TYPE_STRING", + strlen("TYPE_STRING"), 9); + zend_declare_class_constant_long(google_protobuf_Field_Kind_ce, "TYPE_GROUP", + strlen("TYPE_GROUP"), 10); + zend_declare_class_constant_long(google_protobuf_Field_Kind_ce, "TYPE_MESSAGE", + strlen("TYPE_MESSAGE"), 11); + zend_declare_class_constant_long(google_protobuf_Field_Kind_ce, "TYPE_BYTES", + strlen("TYPE_BYTES"), 12); + zend_declare_class_constant_long(google_protobuf_Field_Kind_ce, "TYPE_UINT32", + strlen("TYPE_UINT32"), 13); + zend_declare_class_constant_long(google_protobuf_Field_Kind_ce, "TYPE_ENUM", + strlen("TYPE_ENUM"), 14); + zend_declare_class_constant_long(google_protobuf_Field_Kind_ce, "TYPE_SFIXED32", + strlen("TYPE_SFIXED32"), 15); + zend_declare_class_constant_long(google_protobuf_Field_Kind_ce, "TYPE_SFIXED64", + strlen("TYPE_SFIXED64"), 16); + zend_declare_class_constant_long(google_protobuf_Field_Kind_ce, "TYPE_SINT32", + strlen("TYPE_SINT32"), 17); + zend_declare_class_constant_long(google_protobuf_Field_Kind_ce, "TYPE_SINT64", + strlen("TYPE_SINT64"), 18); +} + +/* google_protobuf_Field_Cardinality */ + +zend_class_entry* google_protobuf_Field_Cardinality_ce; + +PHP_METHOD(google_protobuf_Field_Cardinality, name) { + google_protobuf_type_proto_AddDescriptor(); + const upb_symtab *symtab = DescriptorPool_GetSymbolTable(); + const upb_enumdef *e = upb_symtab_lookupenum(symtab, "google.protobuf.Field.Cardinality"); + const char *name; + zend_long value; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &value) == + FAILURE) { + return; + } + name = upb_enumdef_iton(e, value); + if (!name) { + zend_throw_exception_ex(NULL, 0, + "Google\\Protobuf\\Field\\Cardinality has no name " + "defined for value " ZEND_LONG_FMT ".", + value); + return; + } + RETURN_STRING(name); +} + +PHP_METHOD(google_protobuf_Field_Cardinality, value) { + google_protobuf_type_proto_AddDescriptor(); + const upb_symtab *symtab = DescriptorPool_GetSymbolTable(); + const upb_enumdef *e = upb_symtab_lookupenum(symtab, "google.protobuf.Field.Cardinality"); + char *name = NULL; + size_t name_len; + int32_t num; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &name, + &name_len) == FAILURE) { + return; + } + if (!upb_enumdef_ntoi(e, name, name_len, &num)) { + zend_throw_exception_ex(NULL, 0, + "Google\\Protobuf\\Field\\Cardinality has no value " + "defined for name %s.", + name); + return; + } + RETURN_LONG(num); +} + +static zend_function_entry google_protobuf_Field_Cardinality_phpmethods[] = { + PHP_ME(google_protobuf_Field_Cardinality, name, arginfo_lookup, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + PHP_ME(google_protobuf_Field_Cardinality, value, arginfo_lookup, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + ZEND_FE_END +}; + +static void google_protobuf_Field_Cardinality_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\Field\\Cardinality", + google_protobuf_Field_Cardinality_phpmethods); + + google_protobuf_Field_Cardinality_ce = zend_register_internal_class(&tmp_ce); + zend_declare_class_constant_long(google_protobuf_Field_Cardinality_ce, "CARDINALITY_UNKNOWN", + strlen("CARDINALITY_UNKNOWN"), 0); + zend_declare_class_constant_long(google_protobuf_Field_Cardinality_ce, "CARDINALITY_OPTIONAL", + strlen("CARDINALITY_OPTIONAL"), 1); + zend_declare_class_constant_long(google_protobuf_Field_Cardinality_ce, "CARDINALITY_REQUIRED", + strlen("CARDINALITY_REQUIRED"), 2); + zend_declare_class_constant_long(google_protobuf_Field_Cardinality_ce, "CARDINALITY_REPEATED", + strlen("CARDINALITY_REPEATED"), 3); +} + +/* google_protobuf_Enum */ + +zend_class_entry* google_protobuf_Enum_ce; + +static PHP_METHOD(google_protobuf_Enum, __construct) { + google_protobuf_type_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_Enum, getName) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "name"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Enum, setName) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "name"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Enum, getEnumvalue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "enumvalue"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Enum, setEnumvalue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "enumvalue"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Enum, getOptions) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "options"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Enum, setOptions) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "options"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Enum, getSourceContext) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "source_context"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Enum, setSourceContext) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "source_context"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Enum, getSyntax) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "syntax"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Enum, setSyntax) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "syntax"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static zend_function_entry google_protobuf_Enum_phpmethods[] = { + PHP_ME(google_protobuf_Enum, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Enum, getName, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Enum, setName, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Enum, getEnumvalue, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Enum, setEnumvalue, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Enum, getOptions, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Enum, setOptions, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Enum, getSourceContext, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Enum, setSourceContext, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Enum, getSyntax, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Enum, setSyntax, arginfo_setter, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_Enum_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\Enum", + google_protobuf_Enum_phpmethods); + + google_protobuf_Enum_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_Enum_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_Enum_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_Enum_ce, message_ce); +} + +/* google_protobuf_EnumValue */ + +zend_class_entry* google_protobuf_EnumValue_ce; + +static PHP_METHOD(google_protobuf_EnumValue, __construct) { + google_protobuf_type_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_EnumValue, getName) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "name"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_EnumValue, setName) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "name"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_EnumValue, getNumber) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "number"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_EnumValue, setNumber) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "number"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_EnumValue, getOptions) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "options"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_EnumValue, setOptions) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "options"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static zend_function_entry google_protobuf_EnumValue_phpmethods[] = { + PHP_ME(google_protobuf_EnumValue, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_EnumValue, getName, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_EnumValue, setName, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_EnumValue, getNumber, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_EnumValue, setNumber, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_EnumValue, getOptions, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_EnumValue, setOptions, arginfo_setter, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_EnumValue_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\EnumValue", + google_protobuf_EnumValue_phpmethods); + + google_protobuf_EnumValue_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_EnumValue_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_EnumValue_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_EnumValue_ce, message_ce); +} + +/* google_protobuf_Option */ + +zend_class_entry* google_protobuf_Option_ce; + +static PHP_METHOD(google_protobuf_Option, __construct) { + google_protobuf_type_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_Option, getName) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "name"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Option, setName) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "name"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Option, getValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Option, setValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static zend_function_entry google_protobuf_Option_phpmethods[] = { + PHP_ME(google_protobuf_Option, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Option, getName, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Option, setName, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Option, getValue, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Option, setValue, arginfo_setter, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_Option_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\Option", + google_protobuf_Option_phpmethods); + + google_protobuf_Option_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_Option_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_Option_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_Option_ce, message_ce); +} + +/* google_protobuf_Syntax */ + +zend_class_entry* google_protobuf_Syntax_ce; + +PHP_METHOD(google_protobuf_Syntax, name) { + google_protobuf_type_proto_AddDescriptor(); + const upb_symtab *symtab = DescriptorPool_GetSymbolTable(); + const upb_enumdef *e = upb_symtab_lookupenum(symtab, "google.protobuf.Syntax"); + const char *name; + zend_long value; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &value) == + FAILURE) { + return; + } + name = upb_enumdef_iton(e, value); + if (!name) { + zend_throw_exception_ex(NULL, 0, + "Google\\Protobuf\\Syntax has no name " + "defined for value " ZEND_LONG_FMT ".", + value); + return; + } + RETURN_STRING(name); +} + +PHP_METHOD(google_protobuf_Syntax, value) { + google_protobuf_type_proto_AddDescriptor(); + const upb_symtab *symtab = DescriptorPool_GetSymbolTable(); + const upb_enumdef *e = upb_symtab_lookupenum(symtab, "google.protobuf.Syntax"); + char *name = NULL; + size_t name_len; + int32_t num; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &name, + &name_len) == FAILURE) { + return; + } + if (!upb_enumdef_ntoi(e, name, name_len, &num)) { + zend_throw_exception_ex(NULL, 0, + "Google\\Protobuf\\Syntax has no value " + "defined for name %s.", + name); + return; + } + RETURN_LONG(num); +} + +static zend_function_entry google_protobuf_Syntax_phpmethods[] = { + PHP_ME(google_protobuf_Syntax, name, arginfo_lookup, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + PHP_ME(google_protobuf_Syntax, value, arginfo_lookup, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + ZEND_FE_END +}; + +static void google_protobuf_Syntax_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\Syntax", + google_protobuf_Syntax_phpmethods); + + google_protobuf_Syntax_ce = zend_register_internal_class(&tmp_ce); + zend_declare_class_constant_long(google_protobuf_Syntax_ce, "SYNTAX_PROTO2", + strlen("SYNTAX_PROTO2"), 0); + zend_declare_class_constant_long(google_protobuf_Syntax_ce, "SYNTAX_PROTO3", + strlen("SYNTAX_PROTO3"), 1); +} + +/* google/protobuf/timestamp.proto */ + +zend_class_entry* GPBMetadata_Google_Protobuf_Timestamp_ce; + +const char google_protobuf_timestamp_proto_descriptor [239] = { +'\n', '\037', 'g', 'o', 'o', 'g', 'l', 'e', '/', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '/', 't', 'i', 'm', 'e', 's', 't', 'a', +'m', 'p', '.', 'p', 'r', 'o', 't', 'o', '\022', '\017', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', +'\"', '+', '\n', '\t', 'T', 'i', 'm', 'e', 's', 't', 'a', 'm', 'p', '\022', '\017', '\n', '\007', 's', 'e', 'c', 'o', 'n', 'd', 's', '\030', +'\001', ' ', '\001', '(', '\003', '\022', '\r', '\n', '\005', 'n', 'a', 'n', 'o', 's', '\030', '\002', ' ', '\001', '(', '\005', 'B', '\205', '\001', '\n', '\023', +'c', 'o', 'm', '.', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', 'B', '\016', 'T', 'i', 'm', 'e', +'s', 't', 'a', 'm', 'p', 'P', 'r', 'o', 't', 'o', 'P', '\001', 'Z', '2', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'g', 'o', 'l', 'a', +'n', 'g', '.', 'o', 'r', 'g', '/', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '/', 't', 'y', 'p', 'e', 's', '/', 'k', 'n', 'o', +'w', 'n', '/', 't', 'i', 'm', 'e', 's', 't', 'a', 'm', 'p', 'p', 'b', '\370', '\001', '\001', '\242', '\002', '\003', 'G', 'P', 'B', '\252', '\002', +'\036', 'G', 'o', 'o', 'g', 'l', 'e', '.', 'P', 'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'W', 'e', 'l', 'l', 'K', 'n', 'o', 'w', +'n', 'T', 'y', 'p', 'e', 's', 'b', '\006', 'p', 'r', 'o', 't', 'o', '3', +}; + +static void google_protobuf_timestamp_proto_AddDescriptor() { + if (DescriptorPool_HasFile("google/protobuf/timestamp.proto")) return; + DescriptorPool_AddDescriptor("google/protobuf/timestamp.proto", google_protobuf_timestamp_proto_descriptor, + sizeof(google_protobuf_timestamp_proto_descriptor)); +} + +static PHP_METHOD(GPBMetadata_Google_Protobuf_Timestamp, initOnce) { + google_protobuf_timestamp_proto_AddDescriptor(); +} + +static zend_function_entry GPBMetadata_Google_Protobuf_Timestamp_methods[] = { + PHP_ME(GPBMetadata_Google_Protobuf_Timestamp, initOnce, arginfo_void, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + ZEND_FE_END +}; + +static void GPBMetadata_Google_Protobuf_Timestamp_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "GPBMetadata\\Google\\Protobuf\\Timestamp", + GPBMetadata_Google_Protobuf_Timestamp_methods); + + GPBMetadata_Google_Protobuf_Timestamp_ce = zend_register_internal_class(&tmp_ce); +} + +/* google_protobuf_Timestamp */ + +zend_class_entry* google_protobuf_Timestamp_ce; + +static PHP_METHOD(google_protobuf_Timestamp, __construct) { + google_protobuf_timestamp_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_Timestamp, getSeconds) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "seconds"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Timestamp, setSeconds) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "seconds"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static PHP_METHOD(google_protobuf_Timestamp, getNanos) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "nanos"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Timestamp, setNanos) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "nanos"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +ZEND_BEGIN_ARG_INFO_EX(arginfo_timestamp_fromdatetime, 0, 0, 1) + ZEND_ARG_INFO(0, datetime) +ZEND_END_ARG_INFO() + +static zend_function_entry google_protobuf_Timestamp_phpmethods[] = { + PHP_ME(google_protobuf_Timestamp, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Timestamp, getSeconds, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Timestamp, setSeconds, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Timestamp, getNanos, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Timestamp, setNanos, arginfo_setter, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Timestamp, fromDateTime, arginfo_timestamp_fromdatetime, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Timestamp, toDateTime, arginfo_void, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_Timestamp_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\Timestamp", + google_protobuf_Timestamp_phpmethods); + + google_protobuf_Timestamp_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_Timestamp_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_Timestamp_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_Timestamp_ce, message_ce); +} + +/* google/protobuf/wrappers.proto */ + +zend_class_entry* GPBMetadata_Google_Protobuf_Wrappers_ce; + +const char google_protobuf_wrappers_proto_descriptor [455] = { +'\n', '\036', 'g', 'o', 'o', 'g', 'l', 'e', '/', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '/', 'w', 'r', 'a', 'p', 'p', 'e', 'r', +'s', '.', 'p', 'r', 'o', 't', 'o', '\022', '\017', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', '\"', +'\034', '\n', '\013', 'D', 'o', 'u', 'b', 'l', 'e', 'V', 'a', 'l', 'u', 'e', '\022', '\r', '\n', '\005', 'v', 'a', 'l', 'u', 'e', '\030', '\001', +' ', '\001', '(', '\001', '\"', '\033', '\n', '\n', 'F', 'l', 'o', 'a', 't', 'V', 'a', 'l', 'u', 'e', '\022', '\r', '\n', '\005', 'v', 'a', 'l', +'u', 'e', '\030', '\001', ' ', '\001', '(', '\002', '\"', '\033', '\n', '\n', 'I', 'n', 't', '6', '4', 'V', 'a', 'l', 'u', 'e', '\022', '\r', '\n', +'\005', 'v', 'a', 'l', 'u', 'e', '\030', '\001', ' ', '\001', '(', '\003', '\"', '\034', '\n', '\013', 'U', 'I', 'n', 't', '6', '4', 'V', 'a', 'l', +'u', 'e', '\022', '\r', '\n', '\005', 'v', 'a', 'l', 'u', 'e', '\030', '\001', ' ', '\001', '(', '\004', '\"', '\033', '\n', '\n', 'I', 'n', 't', '3', +'2', 'V', 'a', 'l', 'u', 'e', '\022', '\r', '\n', '\005', 'v', 'a', 'l', 'u', 'e', '\030', '\001', ' ', '\001', '(', '\005', '\"', '\034', '\n', '\013', +'U', 'I', 'n', 't', '3', '2', 'V', 'a', 'l', 'u', 'e', '\022', '\r', '\n', '\005', 'v', 'a', 'l', 'u', 'e', '\030', '\001', ' ', '\001', '(', +'\r', '\"', '\032', '\n', '\t', 'B', 'o', 'o', 'l', 'V', 'a', 'l', 'u', 'e', '\022', '\r', '\n', '\005', 'v', 'a', 'l', 'u', 'e', '\030', '\001', +' ', '\001', '(', '\010', '\"', '\034', '\n', '\013', 'S', 't', 'r', 'i', 'n', 'g', 'V', 'a', 'l', 'u', 'e', '\022', '\r', '\n', '\005', 'v', 'a', +'l', 'u', 'e', '\030', '\001', ' ', '\001', '(', '\t', '\"', '\033', '\n', '\n', 'B', 'y', 't', 'e', 's', 'V', 'a', 'l', 'u', 'e', '\022', '\r', +'\n', '\005', 'v', 'a', 'l', 'u', 'e', '\030', '\001', ' ', '\001', '(', '\014', 'B', '\203', '\001', '\n', '\023', 'c', 'o', 'm', '.', 'g', 'o', 'o', +'g', 'l', 'e', '.', 'p', 'r', 'o', 't', 'o', 'b', 'u', 'f', 'B', '\r', 'W', 'r', 'a', 'p', 'p', 'e', 'r', 's', 'P', 'r', 'o', +'t', 'o', 'P', '\001', 'Z', '1', 'g', 'o', 'o', 'g', 'l', 'e', '.', 'g', 'o', 'l', 'a', 'n', 'g', '.', 'o', 'r', 'g', '/', 'p', +'r', 'o', 't', 'o', 'b', 'u', 'f', '/', 't', 'y', 'p', 'e', 's', '/', 'k', 'n', 'o', 'w', 'n', '/', 'w', 'r', 'a', 'p', 'p', +'e', 'r', 's', 'p', 'b', '\370', '\001', '\001', '\242', '\002', '\003', 'G', 'P', 'B', '\252', '\002', '\036', 'G', 'o', 'o', 'g', 'l', 'e', '.', 'P', +'r', 'o', 't', 'o', 'b', 'u', 'f', '.', 'W', 'e', 'l', 'l', 'K', 'n', 'o', 'w', 'n', 'T', 'y', 'p', 'e', 's', 'b', '\006', 'p', +'r', 'o', 't', 'o', '3', +}; + +static void google_protobuf_wrappers_proto_AddDescriptor() { + if (DescriptorPool_HasFile("google/protobuf/wrappers.proto")) return; + DescriptorPool_AddDescriptor("google/protobuf/wrappers.proto", google_protobuf_wrappers_proto_descriptor, + sizeof(google_protobuf_wrappers_proto_descriptor)); +} + +static PHP_METHOD(GPBMetadata_Google_Protobuf_Wrappers, initOnce) { + google_protobuf_wrappers_proto_AddDescriptor(); +} + +static zend_function_entry GPBMetadata_Google_Protobuf_Wrappers_methods[] = { + PHP_ME(GPBMetadata_Google_Protobuf_Wrappers, initOnce, arginfo_void, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) + ZEND_FE_END +}; + +static void GPBMetadata_Google_Protobuf_Wrappers_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "GPBMetadata\\Google\\Protobuf\\Wrappers", + GPBMetadata_Google_Protobuf_Wrappers_methods); + + GPBMetadata_Google_Protobuf_Wrappers_ce = zend_register_internal_class(&tmp_ce); +} + +/* google_protobuf_DoubleValue */ + +zend_class_entry* google_protobuf_DoubleValue_ce; + +static PHP_METHOD(google_protobuf_DoubleValue, __construct) { + google_protobuf_wrappers_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_DoubleValue, getValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_DoubleValue, setValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static zend_function_entry google_protobuf_DoubleValue_phpmethods[] = { + PHP_ME(google_protobuf_DoubleValue, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_DoubleValue, getValue, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_DoubleValue, setValue, arginfo_setter, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_DoubleValue_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\DoubleValue", + google_protobuf_DoubleValue_phpmethods); + + google_protobuf_DoubleValue_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_DoubleValue_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_DoubleValue_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_DoubleValue_ce, message_ce); +} + +/* google_protobuf_FloatValue */ + +zend_class_entry* google_protobuf_FloatValue_ce; + +static PHP_METHOD(google_protobuf_FloatValue, __construct) { + google_protobuf_wrappers_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_FloatValue, getValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_FloatValue, setValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static zend_function_entry google_protobuf_FloatValue_phpmethods[] = { + PHP_ME(google_protobuf_FloatValue, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_FloatValue, getValue, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_FloatValue, setValue, arginfo_setter, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_FloatValue_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\FloatValue", + google_protobuf_FloatValue_phpmethods); + + google_protobuf_FloatValue_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_FloatValue_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_FloatValue_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_FloatValue_ce, message_ce); +} + +/* google_protobuf_Int64Value */ + +zend_class_entry* google_protobuf_Int64Value_ce; + +static PHP_METHOD(google_protobuf_Int64Value, __construct) { + google_protobuf_wrappers_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_Int64Value, getValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Int64Value, setValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static zend_function_entry google_protobuf_Int64Value_phpmethods[] = { + PHP_ME(google_protobuf_Int64Value, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Int64Value, getValue, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Int64Value, setValue, arginfo_setter, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_Int64Value_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\Int64Value", + google_protobuf_Int64Value_phpmethods); + + google_protobuf_Int64Value_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_Int64Value_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_Int64Value_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_Int64Value_ce, message_ce); +} + +/* google_protobuf_UInt64Value */ + +zend_class_entry* google_protobuf_UInt64Value_ce; + +static PHP_METHOD(google_protobuf_UInt64Value, __construct) { + google_protobuf_wrappers_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_UInt64Value, getValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_UInt64Value, setValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static zend_function_entry google_protobuf_UInt64Value_phpmethods[] = { + PHP_ME(google_protobuf_UInt64Value, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_UInt64Value, getValue, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_UInt64Value, setValue, arginfo_setter, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_UInt64Value_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\UInt64Value", + google_protobuf_UInt64Value_phpmethods); + + google_protobuf_UInt64Value_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_UInt64Value_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_UInt64Value_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_UInt64Value_ce, message_ce); +} + +/* google_protobuf_Int32Value */ + +zend_class_entry* google_protobuf_Int32Value_ce; + +static PHP_METHOD(google_protobuf_Int32Value, __construct) { + google_protobuf_wrappers_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_Int32Value, getValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_Int32Value, setValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static zend_function_entry google_protobuf_Int32Value_phpmethods[] = { + PHP_ME(google_protobuf_Int32Value, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Int32Value, getValue, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_Int32Value, setValue, arginfo_setter, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_Int32Value_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\Int32Value", + google_protobuf_Int32Value_phpmethods); + + google_protobuf_Int32Value_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_Int32Value_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_Int32Value_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_Int32Value_ce, message_ce); +} + +/* google_protobuf_UInt32Value */ + +zend_class_entry* google_protobuf_UInt32Value_ce; + +static PHP_METHOD(google_protobuf_UInt32Value, __construct) { + google_protobuf_wrappers_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_UInt32Value, getValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_UInt32Value, setValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static zend_function_entry google_protobuf_UInt32Value_phpmethods[] = { + PHP_ME(google_protobuf_UInt32Value, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_UInt32Value, getValue, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_UInt32Value, setValue, arginfo_setter, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_UInt32Value_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\UInt32Value", + google_protobuf_UInt32Value_phpmethods); + + google_protobuf_UInt32Value_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_UInt32Value_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_UInt32Value_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_UInt32Value_ce, message_ce); +} + +/* google_protobuf_BoolValue */ + +zend_class_entry* google_protobuf_BoolValue_ce; + +static PHP_METHOD(google_protobuf_BoolValue, __construct) { + google_protobuf_wrappers_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_BoolValue, getValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_BoolValue, setValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static zend_function_entry google_protobuf_BoolValue_phpmethods[] = { + PHP_ME(google_protobuf_BoolValue, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_BoolValue, getValue, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_BoolValue, setValue, arginfo_setter, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_BoolValue_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\BoolValue", + google_protobuf_BoolValue_phpmethods); + + google_protobuf_BoolValue_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_BoolValue_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_BoolValue_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_BoolValue_ce, message_ce); +} + +/* google_protobuf_StringValue */ + +zend_class_entry* google_protobuf_StringValue_ce; + +static PHP_METHOD(google_protobuf_StringValue, __construct) { + google_protobuf_wrappers_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_StringValue, getValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_StringValue, setValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static zend_function_entry google_protobuf_StringValue_phpmethods[] = { + PHP_ME(google_protobuf_StringValue, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_StringValue, getValue, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_StringValue, setValue, arginfo_setter, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_StringValue_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\StringValue", + google_protobuf_StringValue_phpmethods); + + google_protobuf_StringValue_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_StringValue_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_StringValue_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_StringValue_ce, message_ce); +} + +/* google_protobuf_BytesValue */ + +zend_class_entry* google_protobuf_BytesValue_ce; + +static PHP_METHOD(google_protobuf_BytesValue, __construct) { + google_protobuf_wrappers_proto_AddDescriptor(); + zim_Message___construct(INTERNAL_FUNCTION_PARAM_PASSTHRU); +} + +static PHP_METHOD(google_protobuf_BytesValue, getValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval ret; + Message_get(intern, f, &ret); + RETURN_COPY_VALUE(&ret); +} + +static PHP_METHOD(google_protobuf_BytesValue, setValue) { + Message* intern = (Message*)Z_OBJ_P(getThis()); + const upb_fielddef *f = upb_msgdef_ntofz(intern->desc->msgdef, + "value"); + zval *val; + if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &val) + == FAILURE) { + return; + } + Message_set(intern, f, val); + RETURN_COPY(getThis()); +} + +static zend_function_entry google_protobuf_BytesValue_phpmethods[] = { + PHP_ME(google_protobuf_BytesValue, __construct, arginfo_construct, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_BytesValue, getValue, arginfo_void, ZEND_ACC_PUBLIC) + PHP_ME(google_protobuf_BytesValue, setValue, arginfo_setter, ZEND_ACC_PUBLIC) + ZEND_FE_END +}; + +static void google_protobuf_BytesValue_ModuleInit() { + zend_class_entry tmp_ce; + + INIT_CLASS_ENTRY(tmp_ce, "Google\\Protobuf\\BytesValue", + google_protobuf_BytesValue_phpmethods); + + google_protobuf_BytesValue_ce = zend_register_internal_class(&tmp_ce); + google_protobuf_BytesValue_ce->ce_flags |= ZEND_ACC_FINAL; + google_protobuf_BytesValue_ce->create_object = Message_create; + zend_do_inheritance(google_protobuf_BytesValue_ce, message_ce); +} + +static void WellKnownTypes_ModuleInit() { + GPBMetadata_Google_Protobuf_Any_ModuleInit(); + google_protobuf_Any_ModuleInit(); + GPBMetadata_Google_Protobuf_Api_ModuleInit(); + google_protobuf_Api_ModuleInit(); + google_protobuf_Method_ModuleInit(); + google_protobuf_Mixin_ModuleInit(); + GPBMetadata_Google_Protobuf_Duration_ModuleInit(); + google_protobuf_Duration_ModuleInit(); + GPBMetadata_Google_Protobuf_GPBEmpty_ModuleInit(); + google_protobuf_Empty_ModuleInit(); + GPBMetadata_Google_Protobuf_FieldMask_ModuleInit(); + google_protobuf_FieldMask_ModuleInit(); + GPBMetadata_Google_Protobuf_SourceContext_ModuleInit(); + google_protobuf_SourceContext_ModuleInit(); + GPBMetadata_Google_Protobuf_Struct_ModuleInit(); + google_protobuf_Struct_ModuleInit(); + google_protobuf_Struct_FieldsEntry_ModuleInit(); + google_protobuf_Value_ModuleInit(); + google_protobuf_ListValue_ModuleInit(); + google_protobuf_NullValue_ModuleInit(); + GPBMetadata_Google_Protobuf_Type_ModuleInit(); + google_protobuf_Type_ModuleInit(); + google_protobuf_Field_ModuleInit(); + google_protobuf_Field_Kind_ModuleInit(); + google_protobuf_Field_Cardinality_ModuleInit(); + google_protobuf_Enum_ModuleInit(); + google_protobuf_EnumValue_ModuleInit(); + google_protobuf_Option_ModuleInit(); + google_protobuf_Syntax_ModuleInit(); + GPBMetadata_Google_Protobuf_Timestamp_ModuleInit(); + google_protobuf_Timestamp_ModuleInit(); + GPBMetadata_Google_Protobuf_Wrappers_ModuleInit(); + google_protobuf_DoubleValue_ModuleInit(); + google_protobuf_FloatValue_ModuleInit(); + google_protobuf_Int64Value_ModuleInit(); + google_protobuf_UInt64Value_ModuleInit(); + google_protobuf_Int32Value_ModuleInit(); + google_protobuf_UInt32Value_ModuleInit(); + google_protobuf_BoolValue_ModuleInit(); + google_protobuf_StringValue_ModuleInit(); + google_protobuf_BytesValue_ModuleInit(); +} diff --git a/tools/go-generator/cmd/generator/_protobuf/php/src/GPBMetadata/Google/Protobuf/Any.php b/tools/go-generator/cmd/generator/_protobuf/php/src/GPBMetadata/Google/Protobuf/Any.php new file mode 100644 index 0000000..fbce4bf --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/src/GPBMetadata/Google/Protobuf/Any.php @@ -0,0 +1,30 @@ +internalAddGeneratedFile( + ' +Ô +google/protobuf/any.protogoogle.protobuf"& +Any +type_url (  +value ( Bv +com.google.protobufBAnyProtoPZ,google.golang.org/protobuf/types/known/anypb¢GPBªGoogle.Protobuf.WellKnownTypesbproto3' + , true); + + static::$is_initialized = true; + } +} + diff --git a/tools/go-generator/cmd/generator/_protobuf/php/src/GPBMetadata/Google/Protobuf/Duration.php b/tools/go-generator/cmd/generator/_protobuf/php/src/GPBMetadata/Google/Protobuf/Duration.php new file mode 100644 index 0000000..5d8023e --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/src/GPBMetadata/Google/Protobuf/Duration.php @@ -0,0 +1,30 @@ +internalAddGeneratedFile( + ' +ë +google/protobuf/duration.protogoogle.protobuf"* +Duration +seconds ( +nanos (Bƒ +com.google.protobufB DurationProtoPZ1google.golang.org/protobuf/types/known/durationpbø¢GPBªGoogle.Protobuf.WellKnownTypesbproto3' + , true); + + static::$is_initialized = true; + } +} + diff --git a/tools/go-generator/cmd/generator/_protobuf/php/src/GPBMetadata/Google/Protobuf/GPBEmpty.php b/tools/go-generator/cmd/generator/_protobuf/php/src/GPBMetadata/Google/Protobuf/GPBEmpty.php new file mode 100644 index 0000000..5e42536 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/src/GPBMetadata/Google/Protobuf/GPBEmpty.php @@ -0,0 +1,29 @@ +internalAddGeneratedFile( + ' +¾ +google/protobuf/empty.protogoogle.protobuf" +EmptyB} +com.google.protobufB +EmptyProtoPZ.google.golang.org/protobuf/types/known/emptypbø¢GPBªGoogle.Protobuf.WellKnownTypesbproto3' + , true); + + static::$is_initialized = true; + } +} + diff --git a/tools/go-generator/cmd/generator/_protobuf/php/src/GPBMetadata/Google/Protobuf/Internal/Descriptor.php b/tools/go-generator/cmd/generator/_protobuf/php/src/GPBMetadata/Google/Protobuf/Internal/Descriptor.php new file mode 100644 index 0000000..ea0edc5 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/src/GPBMetadata/Google/Protobuf/Internal/Descriptor.php @@ -0,0 +1,278 @@ +addMessage('google.protobuf.internal.FileDescriptorSet', \Google\Protobuf\Internal\FileDescriptorSet::class) + ->repeated('file', \Google\Protobuf\Internal\GPBType::MESSAGE, 1, 'google.protobuf.internal.FileDescriptorProto') + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.FileDescriptorProto', \Google\Protobuf\Internal\FileDescriptorProto::class) + ->optional('name', \Google\Protobuf\Internal\GPBType::STRING, 1) + ->optional('package', \Google\Protobuf\Internal\GPBType::STRING, 2) + ->repeated('dependency', \Google\Protobuf\Internal\GPBType::STRING, 3) + ->repeated('public_dependency', \Google\Protobuf\Internal\GPBType::INT32, 10) + ->repeated('weak_dependency', \Google\Protobuf\Internal\GPBType::INT32, 11) + ->repeated('message_type', \Google\Protobuf\Internal\GPBType::MESSAGE, 4, 'google.protobuf.internal.DescriptorProto') + ->repeated('enum_type', \Google\Protobuf\Internal\GPBType::MESSAGE, 5, 'google.protobuf.internal.EnumDescriptorProto') + ->repeated('service', \Google\Protobuf\Internal\GPBType::MESSAGE, 6, 'google.protobuf.internal.ServiceDescriptorProto') + ->repeated('extension', \Google\Protobuf\Internal\GPBType::MESSAGE, 7, 'google.protobuf.internal.FieldDescriptorProto') + ->optional('options', \Google\Protobuf\Internal\GPBType::MESSAGE, 8, 'google.protobuf.internal.FileOptions') + ->optional('source_code_info', \Google\Protobuf\Internal\GPBType::MESSAGE, 9, 'google.protobuf.internal.SourceCodeInfo') + ->optional('syntax', \Google\Protobuf\Internal\GPBType::STRING, 12) + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.DescriptorProto', \Google\Protobuf\Internal\DescriptorProto::class) + ->optional('name', \Google\Protobuf\Internal\GPBType::STRING, 1) + ->repeated('field', \Google\Protobuf\Internal\GPBType::MESSAGE, 2, 'google.protobuf.internal.FieldDescriptorProto') + ->repeated('extension', \Google\Protobuf\Internal\GPBType::MESSAGE, 6, 'google.protobuf.internal.FieldDescriptorProto') + ->repeated('nested_type', \Google\Protobuf\Internal\GPBType::MESSAGE, 3, 'google.protobuf.internal.DescriptorProto') + ->repeated('enum_type', \Google\Protobuf\Internal\GPBType::MESSAGE, 4, 'google.protobuf.internal.EnumDescriptorProto') + ->repeated('extension_range', \Google\Protobuf\Internal\GPBType::MESSAGE, 5, 'google.protobuf.internal.DescriptorProto.ExtensionRange') + ->repeated('oneof_decl', \Google\Protobuf\Internal\GPBType::MESSAGE, 8, 'google.protobuf.internal.OneofDescriptorProto') + ->optional('options', \Google\Protobuf\Internal\GPBType::MESSAGE, 7, 'google.protobuf.internal.MessageOptions') + ->repeated('reserved_range', \Google\Protobuf\Internal\GPBType::MESSAGE, 9, 'google.protobuf.internal.DescriptorProto.ReservedRange') + ->repeated('reserved_name', \Google\Protobuf\Internal\GPBType::STRING, 10) + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.DescriptorProto.ExtensionRange', \Google\Protobuf\Internal\DescriptorProto\ExtensionRange::class) + ->optional('start', \Google\Protobuf\Internal\GPBType::INT32, 1) + ->optional('end', \Google\Protobuf\Internal\GPBType::INT32, 2) + ->optional('options', \Google\Protobuf\Internal\GPBType::MESSAGE, 3, 'google.protobuf.internal.ExtensionRangeOptions') + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.DescriptorProto.ReservedRange', \Google\Protobuf\Internal\DescriptorProto\ReservedRange::class) + ->optional('start', \Google\Protobuf\Internal\GPBType::INT32, 1) + ->optional('end', \Google\Protobuf\Internal\GPBType::INT32, 2) + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.ExtensionRangeOptions', \Google\Protobuf\Internal\ExtensionRangeOptions::class) + ->repeated('uninterpreted_option', \Google\Protobuf\Internal\GPBType::MESSAGE, 999, 'google.protobuf.internal.UninterpretedOption') + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.FieldDescriptorProto', \Google\Protobuf\Internal\FieldDescriptorProto::class) + ->optional('name', \Google\Protobuf\Internal\GPBType::STRING, 1) + ->optional('number', \Google\Protobuf\Internal\GPBType::INT32, 3) + ->optional('label', \Google\Protobuf\Internal\GPBType::ENUM, 4, 'google.protobuf.internal.FieldDescriptorProto.Label') + ->optional('type', \Google\Protobuf\Internal\GPBType::ENUM, 5, 'google.protobuf.internal.FieldDescriptorProto.Type') + ->optional('type_name', \Google\Protobuf\Internal\GPBType::STRING, 6) + ->optional('extendee', \Google\Protobuf\Internal\GPBType::STRING, 2) + ->optional('default_value', \Google\Protobuf\Internal\GPBType::STRING, 7) + ->optional('oneof_index', \Google\Protobuf\Internal\GPBType::INT32, 9) + ->optional('json_name', \Google\Protobuf\Internal\GPBType::STRING, 10) + ->optional('options', \Google\Protobuf\Internal\GPBType::MESSAGE, 8, 'google.protobuf.internal.FieldOptions') + ->optional('proto3_optional', \Google\Protobuf\Internal\GPBType::BOOL, 17) + ->finalizeToPool(); + + $pool->addEnum('google.protobuf.internal.FieldDescriptorProto.Type', \Google\Protobuf\Internal\Type::class) + ->value("TYPE_DOUBLE", 1) + ->value("TYPE_FLOAT", 2) + ->value("TYPE_INT64", 3) + ->value("TYPE_UINT64", 4) + ->value("TYPE_INT32", 5) + ->value("TYPE_FIXED64", 6) + ->value("TYPE_FIXED32", 7) + ->value("TYPE_BOOL", 8) + ->value("TYPE_STRING", 9) + ->value("TYPE_GROUP", 10) + ->value("TYPE_MESSAGE", 11) + ->value("TYPE_BYTES", 12) + ->value("TYPE_UINT32", 13) + ->value("TYPE_ENUM", 14) + ->value("TYPE_SFIXED32", 15) + ->value("TYPE_SFIXED64", 16) + ->value("TYPE_SINT32", 17) + ->value("TYPE_SINT64", 18) + ->finalizeToPool(); + + $pool->addEnum('google.protobuf.internal.FieldDescriptorProto.Label', \Google\Protobuf\Internal\Label::class) + ->value("LABEL_OPTIONAL", 1) + ->value("LABEL_REQUIRED", 2) + ->value("LABEL_REPEATED", 3) + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.OneofDescriptorProto', \Google\Protobuf\Internal\OneofDescriptorProto::class) + ->optional('name', \Google\Protobuf\Internal\GPBType::STRING, 1) + ->optional('options', \Google\Protobuf\Internal\GPBType::MESSAGE, 2, 'google.protobuf.internal.OneofOptions') + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.EnumDescriptorProto', \Google\Protobuf\Internal\EnumDescriptorProto::class) + ->optional('name', \Google\Protobuf\Internal\GPBType::STRING, 1) + ->repeated('value', \Google\Protobuf\Internal\GPBType::MESSAGE, 2, 'google.protobuf.internal.EnumValueDescriptorProto') + ->optional('options', \Google\Protobuf\Internal\GPBType::MESSAGE, 3, 'google.protobuf.internal.EnumOptions') + ->repeated('reserved_range', \Google\Protobuf\Internal\GPBType::MESSAGE, 4, 'google.protobuf.internal.EnumDescriptorProto.EnumReservedRange') + ->repeated('reserved_name', \Google\Protobuf\Internal\GPBType::STRING, 5) + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.EnumDescriptorProto.EnumReservedRange', \Google\Protobuf\Internal\EnumDescriptorProto\EnumReservedRange::class) + ->optional('start', \Google\Protobuf\Internal\GPBType::INT32, 1) + ->optional('end', \Google\Protobuf\Internal\GPBType::INT32, 2) + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.EnumValueDescriptorProto', \Google\Protobuf\Internal\EnumValueDescriptorProto::class) + ->optional('name', \Google\Protobuf\Internal\GPBType::STRING, 1) + ->optional('number', \Google\Protobuf\Internal\GPBType::INT32, 2) + ->optional('options', \Google\Protobuf\Internal\GPBType::MESSAGE, 3, 'google.protobuf.internal.EnumValueOptions') + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.ServiceDescriptorProto', \Google\Protobuf\Internal\ServiceDescriptorProto::class) + ->optional('name', \Google\Protobuf\Internal\GPBType::STRING, 1) + ->repeated('method', \Google\Protobuf\Internal\GPBType::MESSAGE, 2, 'google.protobuf.internal.MethodDescriptorProto') + ->optional('options', \Google\Protobuf\Internal\GPBType::MESSAGE, 3, 'google.protobuf.internal.ServiceOptions') + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.MethodDescriptorProto', \Google\Protobuf\Internal\MethodDescriptorProto::class) + ->optional('name', \Google\Protobuf\Internal\GPBType::STRING, 1) + ->optional('input_type', \Google\Protobuf\Internal\GPBType::STRING, 2) + ->optional('output_type', \Google\Protobuf\Internal\GPBType::STRING, 3) + ->optional('options', \Google\Protobuf\Internal\GPBType::MESSAGE, 4, 'google.protobuf.internal.MethodOptions') + ->optional('client_streaming', \Google\Protobuf\Internal\GPBType::BOOL, 5) + ->optional('server_streaming', \Google\Protobuf\Internal\GPBType::BOOL, 6) + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.FileOptions', \Google\Protobuf\Internal\FileOptions::class) + ->optional('java_package', \Google\Protobuf\Internal\GPBType::STRING, 1) + ->optional('java_outer_classname', \Google\Protobuf\Internal\GPBType::STRING, 8) + ->optional('java_multiple_files', \Google\Protobuf\Internal\GPBType::BOOL, 10) + ->optional('java_generate_equals_and_hash', \Google\Protobuf\Internal\GPBType::BOOL, 20) + ->optional('java_string_check_utf8', \Google\Protobuf\Internal\GPBType::BOOL, 27) + ->optional('optimize_for', \Google\Protobuf\Internal\GPBType::ENUM, 9, 'google.protobuf.internal.FileOptions.OptimizeMode') + ->optional('go_package', \Google\Protobuf\Internal\GPBType::STRING, 11) + ->optional('cc_generic_services', \Google\Protobuf\Internal\GPBType::BOOL, 16) + ->optional('java_generic_services', \Google\Protobuf\Internal\GPBType::BOOL, 17) + ->optional('py_generic_services', \Google\Protobuf\Internal\GPBType::BOOL, 18) + ->optional('php_generic_services', \Google\Protobuf\Internal\GPBType::BOOL, 42) + ->optional('deprecated', \Google\Protobuf\Internal\GPBType::BOOL, 23) + ->optional('cc_enable_arenas', \Google\Protobuf\Internal\GPBType::BOOL, 31) + ->optional('objc_class_prefix', \Google\Protobuf\Internal\GPBType::STRING, 36) + ->optional('csharp_namespace', \Google\Protobuf\Internal\GPBType::STRING, 37) + ->optional('swift_prefix', \Google\Protobuf\Internal\GPBType::STRING, 39) + ->optional('php_class_prefix', \Google\Protobuf\Internal\GPBType::STRING, 40) + ->optional('php_namespace', \Google\Protobuf\Internal\GPBType::STRING, 41) + ->optional('php_metadata_namespace', \Google\Protobuf\Internal\GPBType::STRING, 44) + ->optional('ruby_package', \Google\Protobuf\Internal\GPBType::STRING, 45) + ->repeated('uninterpreted_option', \Google\Protobuf\Internal\GPBType::MESSAGE, 999, 'google.protobuf.internal.UninterpretedOption') + ->finalizeToPool(); + + $pool->addEnum('google.protobuf.internal.FileOptions.OptimizeMode', \Google\Protobuf\Internal\OptimizeMode::class) + ->value("SPEED", 1) + ->value("CODE_SIZE", 2) + ->value("LITE_RUNTIME", 3) + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.MessageOptions', \Google\Protobuf\Internal\MessageOptions::class) + ->optional('message_set_wire_format', \Google\Protobuf\Internal\GPBType::BOOL, 1) + ->optional('no_standard_descriptor_accessor', \Google\Protobuf\Internal\GPBType::BOOL, 2) + ->optional('deprecated', \Google\Protobuf\Internal\GPBType::BOOL, 3) + ->optional('map_entry', \Google\Protobuf\Internal\GPBType::BOOL, 7) + ->repeated('uninterpreted_option', \Google\Protobuf\Internal\GPBType::MESSAGE, 999, 'google.protobuf.internal.UninterpretedOption') + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.FieldOptions', \Google\Protobuf\Internal\FieldOptions::class) + ->optional('ctype', \Google\Protobuf\Internal\GPBType::ENUM, 1, 'google.protobuf.internal.FieldOptions.CType') + ->optional('packed', \Google\Protobuf\Internal\GPBType::BOOL, 2) + ->optional('jstype', \Google\Protobuf\Internal\GPBType::ENUM, 6, 'google.protobuf.internal.FieldOptions.JSType') + ->optional('lazy', \Google\Protobuf\Internal\GPBType::BOOL, 5) + ->optional('deprecated', \Google\Protobuf\Internal\GPBType::BOOL, 3) + ->optional('weak', \Google\Protobuf\Internal\GPBType::BOOL, 10) + ->repeated('uninterpreted_option', \Google\Protobuf\Internal\GPBType::MESSAGE, 999, 'google.protobuf.internal.UninterpretedOption') + ->finalizeToPool(); + + $pool->addEnum('google.protobuf.internal.FieldOptions.CType', \Google\Protobuf\Internal\CType::class) + ->value("STRING", 0) + ->value("CORD", 1) + ->value("STRING_PIECE", 2) + ->finalizeToPool(); + + $pool->addEnum('google.protobuf.internal.FieldOptions.JSType', \Google\Protobuf\Internal\JSType::class) + ->value("JS_NORMAL", 0) + ->value("JS_STRING", 1) + ->value("JS_NUMBER", 2) + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.OneofOptions', \Google\Protobuf\Internal\OneofOptions::class) + ->repeated('uninterpreted_option', \Google\Protobuf\Internal\GPBType::MESSAGE, 999, 'google.protobuf.internal.UninterpretedOption') + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.EnumOptions', \Google\Protobuf\Internal\EnumOptions::class) + ->optional('allow_alias', \Google\Protobuf\Internal\GPBType::BOOL, 2) + ->optional('deprecated', \Google\Protobuf\Internal\GPBType::BOOL, 3) + ->repeated('uninterpreted_option', \Google\Protobuf\Internal\GPBType::MESSAGE, 999, 'google.protobuf.internal.UninterpretedOption') + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.EnumValueOptions', \Google\Protobuf\Internal\EnumValueOptions::class) + ->optional('deprecated', \Google\Protobuf\Internal\GPBType::BOOL, 1) + ->repeated('uninterpreted_option', \Google\Protobuf\Internal\GPBType::MESSAGE, 999, 'google.protobuf.internal.UninterpretedOption') + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.ServiceOptions', \Google\Protobuf\Internal\ServiceOptions::class) + ->optional('deprecated', \Google\Protobuf\Internal\GPBType::BOOL, 33) + ->repeated('uninterpreted_option', \Google\Protobuf\Internal\GPBType::MESSAGE, 999, 'google.protobuf.internal.UninterpretedOption') + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.MethodOptions', \Google\Protobuf\Internal\MethodOptions::class) + ->optional('deprecated', \Google\Protobuf\Internal\GPBType::BOOL, 33) + ->optional('idempotency_level', \Google\Protobuf\Internal\GPBType::ENUM, 34, 'google.protobuf.internal.MethodOptions.IdempotencyLevel') + ->repeated('uninterpreted_option', \Google\Protobuf\Internal\GPBType::MESSAGE, 999, 'google.protobuf.internal.UninterpretedOption') + ->finalizeToPool(); + + $pool->addEnum('google.protobuf.internal.MethodOptions.IdempotencyLevel', \Google\Protobuf\Internal\IdempotencyLevel::class) + ->value("IDEMPOTENCY_UNKNOWN", 0) + ->value("NO_SIDE_EFFECTS", 1) + ->value("IDEMPOTENT", 2) + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.UninterpretedOption', \Google\Protobuf\Internal\UninterpretedOption::class) + ->repeated('name', \Google\Protobuf\Internal\GPBType::MESSAGE, 2, 'google.protobuf.internal.UninterpretedOption.NamePart') + ->optional('identifier_value', \Google\Protobuf\Internal\GPBType::STRING, 3) + ->optional('positive_int_value', \Google\Protobuf\Internal\GPBType::UINT64, 4) + ->optional('negative_int_value', \Google\Protobuf\Internal\GPBType::INT64, 5) + ->optional('double_value', \Google\Protobuf\Internal\GPBType::DOUBLE, 6) + ->optional('string_value', \Google\Protobuf\Internal\GPBType::BYTES, 7) + ->optional('aggregate_value', \Google\Protobuf\Internal\GPBType::STRING, 8) + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.UninterpretedOption.NamePart', \Google\Protobuf\Internal\UninterpretedOption\NamePart::class) + ->required('name_part', \Google\Protobuf\Internal\GPBType::STRING, 1) + ->required('is_extension', \Google\Protobuf\Internal\GPBType::BOOL, 2) + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.SourceCodeInfo', \Google\Protobuf\Internal\SourceCodeInfo::class) + ->repeated('location', \Google\Protobuf\Internal\GPBType::MESSAGE, 1, 'google.protobuf.internal.SourceCodeInfo.Location') + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.SourceCodeInfo.Location', \Google\Protobuf\Internal\SourceCodeInfo\Location::class) + ->repeated('path', \Google\Protobuf\Internal\GPBType::INT32, 1) + ->repeated('span', \Google\Protobuf\Internal\GPBType::INT32, 2) + ->optional('leading_comments', \Google\Protobuf\Internal\GPBType::STRING, 3) + ->optional('trailing_comments', \Google\Protobuf\Internal\GPBType::STRING, 4) + ->repeated('leading_detached_comments', \Google\Protobuf\Internal\GPBType::STRING, 6) + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.GeneratedCodeInfo', \Google\Protobuf\Internal\GeneratedCodeInfo::class) + ->repeated('annotation', \Google\Protobuf\Internal\GPBType::MESSAGE, 1, 'google.protobuf.internal.GeneratedCodeInfo.Annotation') + ->finalizeToPool(); + + $pool->addMessage('google.protobuf.internal.GeneratedCodeInfo.Annotation', \Google\Protobuf\Internal\GeneratedCodeInfo\Annotation::class) + ->repeated('path', \Google\Protobuf\Internal\GPBType::INT32, 1) + ->optional('source_file', \Google\Protobuf\Internal\GPBType::STRING, 2) + ->optional('begin', \Google\Protobuf\Internal\GPBType::INT32, 3) + ->optional('end', \Google\Protobuf\Internal\GPBType::INT32, 4) + ->finalizeToPool(); + + $pool->finish(); + static::$is_initialized = true; + } +} + diff --git a/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/BytesValue.php b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/BytesValue.php new file mode 100644 index 0000000..1582e14 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/BytesValue.php @@ -0,0 +1,68 @@ +google.protobuf.BytesValue + */ +class BytesValue extends \Google\Protobuf\Internal\Message +{ + /** + * The bytes value. + * + * Generated from protobuf field bytes value = 1; + */ + protected $value = ''; + + /** + * Constructor. + * + * @param array $data { + * Optional. Data for populating the Message object. + * + * @type string $value + * The bytes value. + * } + */ + public function __construct($data = NULL) { + \GPBMetadata\Google\Protobuf\Wrappers::initOnce(); + parent::__construct($data); + } + + /** + * The bytes value. + * + * Generated from protobuf field bytes value = 1; + * @return string + */ + public function getValue() + { + return $this->value; + } + + /** + * The bytes value. + * + * Generated from protobuf field bytes value = 1; + * @param string $var + * @return $this + */ + public function setValue($var) + { + GPBUtil::checkString($var, False); + $this->value = $var; + + return $this; + } + +} + diff --git a/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/DoubleValue.php b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/DoubleValue.php new file mode 100644 index 0000000..b72399f --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/DoubleValue.php @@ -0,0 +1,68 @@ +google.protobuf.DoubleValue + */ +class DoubleValue extends \Google\Protobuf\Internal\Message +{ + /** + * The double value. + * + * Generated from protobuf field double value = 1; + */ + protected $value = 0.0; + + /** + * Constructor. + * + * @param array $data { + * Optional. Data for populating the Message object. + * + * @type float $value + * The double value. + * } + */ + public function __construct($data = NULL) { + \GPBMetadata\Google\Protobuf\Wrappers::initOnce(); + parent::__construct($data); + } + + /** + * The double value. + * + * Generated from protobuf field double value = 1; + * @return float + */ + public function getValue() + { + return $this->value; + } + + /** + * The double value. + * + * Generated from protobuf field double value = 1; + * @param float $var + * @return $this + */ + public function setValue($var) + { + GPBUtil::checkDouble($var); + $this->value = $var; + + return $this; + } + +} + diff --git a/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Enum.php b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Enum.php new file mode 100644 index 0000000..e803e93 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Enum.php @@ -0,0 +1,213 @@ +google.protobuf.Enum + */ +class Enum extends \Google\Protobuf\Internal\Message +{ + /** + * Enum type name. + * + * Generated from protobuf field string name = 1; + */ + protected $name = ''; + /** + * Enum value definitions. + * + * Generated from protobuf field repeated .google.protobuf.EnumValue enumvalue = 2; + */ + private $enumvalue; + /** + * Protocol buffer options. + * + * Generated from protobuf field repeated .google.protobuf.Option options = 3; + */ + private $options; + /** + * The source context. + * + * Generated from protobuf field .google.protobuf.SourceContext source_context = 4; + */ + protected $source_context = null; + /** + * The source syntax. + * + * Generated from protobuf field .google.protobuf.Syntax syntax = 5; + */ + protected $syntax = 0; + + /** + * Constructor. + * + * @param array $data { + * Optional. Data for populating the Message object. + * + * @type string $name + * Enum type name. + * @type \Google\Protobuf\EnumValue[]|\Google\Protobuf\Internal\RepeatedField $enumvalue + * Enum value definitions. + * @type \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $options + * Protocol buffer options. + * @type \Google\Protobuf\SourceContext $source_context + * The source context. + * @type int $syntax + * The source syntax. + * } + */ + public function __construct($data = NULL) { + \GPBMetadata\Google\Protobuf\Type::initOnce(); + parent::__construct($data); + } + + /** + * Enum type name. + * + * Generated from protobuf field string name = 1; + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Enum type name. + * + * Generated from protobuf field string name = 1; + * @param string $var + * @return $this + */ + public function setName($var) + { + GPBUtil::checkString($var, True); + $this->name = $var; + + return $this; + } + + /** + * Enum value definitions. + * + * Generated from protobuf field repeated .google.protobuf.EnumValue enumvalue = 2; + * @return \Google\Protobuf\Internal\RepeatedField + */ + public function getEnumvalue() + { + return $this->enumvalue; + } + + /** + * Enum value definitions. + * + * Generated from protobuf field repeated .google.protobuf.EnumValue enumvalue = 2; + * @param \Google\Protobuf\EnumValue[]|\Google\Protobuf\Internal\RepeatedField $var + * @return $this + */ + public function setEnumvalue($var) + { + $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\EnumValue::class); + $this->enumvalue = $arr; + + return $this; + } + + /** + * Protocol buffer options. + * + * Generated from protobuf field repeated .google.protobuf.Option options = 3; + * @return \Google\Protobuf\Internal\RepeatedField + */ + public function getOptions() + { + return $this->options; + } + + /** + * Protocol buffer options. + * + * Generated from protobuf field repeated .google.protobuf.Option options = 3; + * @param \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $var + * @return $this + */ + public function setOptions($var) + { + $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Option::class); + $this->options = $arr; + + return $this; + } + + /** + * The source context. + * + * Generated from protobuf field .google.protobuf.SourceContext source_context = 4; + * @return \Google\Protobuf\SourceContext|null + */ + public function getSourceContext() + { + return $this->source_context; + } + + public function hasSourceContext() + { + return isset($this->source_context); + } + + public function clearSourceContext() + { + unset($this->source_context); + } + + /** + * The source context. + * + * Generated from protobuf field .google.protobuf.SourceContext source_context = 4; + * @param \Google\Protobuf\SourceContext $var + * @return $this + */ + public function setSourceContext($var) + { + GPBUtil::checkMessage($var, \Google\Protobuf\SourceContext::class); + $this->source_context = $var; + + return $this; + } + + /** + * The source syntax. + * + * Generated from protobuf field .google.protobuf.Syntax syntax = 5; + * @return int + */ + public function getSyntax() + { + return $this->syntax; + } + + /** + * The source syntax. + * + * Generated from protobuf field .google.protobuf.Syntax syntax = 5; + * @param int $var + * @return $this + */ + public function setSyntax($var) + { + GPBUtil::checkEnum($var, \Google\Protobuf\Syntax::class); + $this->syntax = $var; + + return $this; + } + +} + diff --git a/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/EnumValue.php b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/EnumValue.php new file mode 100644 index 0000000..905f4ad --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/EnumValue.php @@ -0,0 +1,135 @@ +google.protobuf.EnumValue + */ +class EnumValue extends \Google\Protobuf\Internal\Message +{ + /** + * Enum value name. + * + * Generated from protobuf field string name = 1; + */ + protected $name = ''; + /** + * Enum value number. + * + * Generated from protobuf field int32 number = 2; + */ + protected $number = 0; + /** + * Protocol buffer options. + * + * Generated from protobuf field repeated .google.protobuf.Option options = 3; + */ + private $options; + + /** + * Constructor. + * + * @param array $data { + * Optional. Data for populating the Message object. + * + * @type string $name + * Enum value name. + * @type int $number + * Enum value number. + * @type \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $options + * Protocol buffer options. + * } + */ + public function __construct($data = NULL) { + \GPBMetadata\Google\Protobuf\Type::initOnce(); + parent::__construct($data); + } + + /** + * Enum value name. + * + * Generated from protobuf field string name = 1; + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Enum value name. + * + * Generated from protobuf field string name = 1; + * @param string $var + * @return $this + */ + public function setName($var) + { + GPBUtil::checkString($var, True); + $this->name = $var; + + return $this; + } + + /** + * Enum value number. + * + * Generated from protobuf field int32 number = 2; + * @return int + */ + public function getNumber() + { + return $this->number; + } + + /** + * Enum value number. + * + * Generated from protobuf field int32 number = 2; + * @param int $var + * @return $this + */ + public function setNumber($var) + { + GPBUtil::checkInt32($var); + $this->number = $var; + + return $this; + } + + /** + * Protocol buffer options. + * + * Generated from protobuf field repeated .google.protobuf.Option options = 3; + * @return \Google\Protobuf\Internal\RepeatedField + */ + public function getOptions() + { + return $this->options; + } + + /** + * Protocol buffer options. + * + * Generated from protobuf field repeated .google.protobuf.Option options = 3; + * @param \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $var + * @return $this + */ + public function setOptions($var) + { + $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Protobuf\Option::class); + $this->options = $arr; + + return $this; + } + +} + diff --git a/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/EnumValueDescriptor.php b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/EnumValueDescriptor.php new file mode 100644 index 0000000..e76e199 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/EnumValueDescriptor.php @@ -0,0 +1,64 @@ +name = $name; + $this->number = $number; + } + + /** + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * @return int + */ + public function getNumber() + { + return $this->number; + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/DescriptorProto/ExtensionRange.php b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/DescriptorProto/ExtensionRange.php new file mode 100644 index 0000000..43c33c4 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/DescriptorProto/ExtensionRange.php @@ -0,0 +1,161 @@ +google.protobuf.DescriptorProto.ExtensionRange + */ +class ExtensionRange extends \Google\Protobuf\Internal\Message +{ + /** + * Inclusive. + * + * Generated from protobuf field optional int32 start = 1; + */ + protected $start = null; + /** + * Exclusive. + * + * Generated from protobuf field optional int32 end = 2; + */ + protected $end = null; + /** + * Generated from protobuf field optional .google.protobuf.ExtensionRangeOptions options = 3; + */ + protected $options = null; + + /** + * Constructor. + * + * @param array $data { + * Optional. Data for populating the Message object. + * + * @type int $start + * Inclusive. + * @type int $end + * Exclusive. + * @type \Google\Protobuf\Internal\ExtensionRangeOptions $options + * } + */ + public function __construct($data = NULL) { + \GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce(); + parent::__construct($data); + } + + /** + * Inclusive. + * + * Generated from protobuf field optional int32 start = 1; + * @return int + */ + public function getStart() + { + return isset($this->start) ? $this->start : 0; + } + + public function hasStart() + { + return isset($this->start); + } + + public function clearStart() + { + unset($this->start); + } + + /** + * Inclusive. + * + * Generated from protobuf field optional int32 start = 1; + * @param int $var + * @return $this + */ + public function setStart($var) + { + GPBUtil::checkInt32($var); + $this->start = $var; + + return $this; + } + + /** + * Exclusive. + * + * Generated from protobuf field optional int32 end = 2; + * @return int + */ + public function getEnd() + { + return isset($this->end) ? $this->end : 0; + } + + public function hasEnd() + { + return isset($this->end); + } + + public function clearEnd() + { + unset($this->end); + } + + /** + * Exclusive. + * + * Generated from protobuf field optional int32 end = 2; + * @param int $var + * @return $this + */ + public function setEnd($var) + { + GPBUtil::checkInt32($var); + $this->end = $var; + + return $this; + } + + /** + * Generated from protobuf field optional .google.protobuf.ExtensionRangeOptions options = 3; + * @return \Google\Protobuf\Internal\ExtensionRangeOptions|null + */ + public function getOptions() + { + return $this->options; + } + + public function hasOptions() + { + return isset($this->options); + } + + public function clearOptions() + { + unset($this->options); + } + + /** + * Generated from protobuf field optional .google.protobuf.ExtensionRangeOptions options = 3; + * @param \Google\Protobuf\Internal\ExtensionRangeOptions $var + * @return $this + */ + public function setOptions($var) + { + GPBUtil::checkMessage($var, \Google\Protobuf\Internal\ExtensionRangeOptions::class); + $this->options = $var; + + return $this; + } + +} + +// Adding a class alias for backwards compatibility with the previous class name. +class_alias(ExtensionRange::class, \Google\Protobuf\Internal\DescriptorProto_ExtensionRange::class); + diff --git a/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/DescriptorProto/ReservedRange.php b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/DescriptorProto/ReservedRange.php new file mode 100644 index 0000000..f099cc3 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/DescriptorProto/ReservedRange.php @@ -0,0 +1,128 @@ +google.protobuf.DescriptorProto.ReservedRange + */ +class ReservedRange extends \Google\Protobuf\Internal\Message +{ + /** + * Inclusive. + * + * Generated from protobuf field optional int32 start = 1; + */ + protected $start = null; + /** + * Exclusive. + * + * Generated from protobuf field optional int32 end = 2; + */ + protected $end = null; + + /** + * Constructor. + * + * @param array $data { + * Optional. Data for populating the Message object. + * + * @type int $start + * Inclusive. + * @type int $end + * Exclusive. + * } + */ + public function __construct($data = NULL) { + \GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce(); + parent::__construct($data); + } + + /** + * Inclusive. + * + * Generated from protobuf field optional int32 start = 1; + * @return int + */ + public function getStart() + { + return isset($this->start) ? $this->start : 0; + } + + public function hasStart() + { + return isset($this->start); + } + + public function clearStart() + { + unset($this->start); + } + + /** + * Inclusive. + * + * Generated from protobuf field optional int32 start = 1; + * @param int $var + * @return $this + */ + public function setStart($var) + { + GPBUtil::checkInt32($var); + $this->start = $var; + + return $this; + } + + /** + * Exclusive. + * + * Generated from protobuf field optional int32 end = 2; + * @return int + */ + public function getEnd() + { + return isset($this->end) ? $this->end : 0; + } + + public function hasEnd() + { + return isset($this->end); + } + + public function clearEnd() + { + unset($this->end); + } + + /** + * Exclusive. + * + * Generated from protobuf field optional int32 end = 2; + * @param int $var + * @return $this + */ + public function setEnd($var) + { + GPBUtil::checkInt32($var); + $this->end = $var; + + return $this; + } + +} + +// Adding a class alias for backwards compatibility with the previous class name. +class_alias(ReservedRange::class, \Google\Protobuf\Internal\DescriptorProto_ReservedRange::class); + diff --git a/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/EnumBuilderContext.php b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/EnumBuilderContext.php new file mode 100644 index 0000000..0839728 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/EnumBuilderContext.php @@ -0,0 +1,63 @@ +descriptor = new EnumDescriptor(); + $this->descriptor->setFullName($full_name); + $this->descriptor->setClass($klass); + $this->pool = $pool; + } + + public function value($name, $number) + { + $value = new EnumValueDescriptor($name, $number); + $this->descriptor->addValue($number, $value); + return $this; + } + + public function finalizeToPool() + { + $this->pool->addEnumDescriptor($this->descriptor); + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/EnumValueDescriptorProto.php b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/EnumValueDescriptorProto.php new file mode 100644 index 0000000..0feaea6 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/EnumValueDescriptorProto.php @@ -0,0 +1,146 @@ +google.protobuf.EnumValueDescriptorProto + */ +class EnumValueDescriptorProto extends \Google\Protobuf\Internal\Message +{ + /** + * Generated from protobuf field optional string name = 1; + */ + protected $name = null; + /** + * Generated from protobuf field optional int32 number = 2; + */ + protected $number = null; + /** + * Generated from protobuf field optional .google.protobuf.EnumValueOptions options = 3; + */ + protected $options = null; + + /** + * Constructor. + * + * @param array $data { + * Optional. Data for populating the Message object. + * + * @type string $name + * @type int $number + * @type \Google\Protobuf\Internal\EnumValueOptions $options + * } + */ + public function __construct($data = NULL) { + \GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce(); + parent::__construct($data); + } + + /** + * Generated from protobuf field optional string name = 1; + * @return string + */ + public function getName() + { + return isset($this->name) ? $this->name : ''; + } + + public function hasName() + { + return isset($this->name); + } + + public function clearName() + { + unset($this->name); + } + + /** + * Generated from protobuf field optional string name = 1; + * @param string $var + * @return $this + */ + public function setName($var) + { + GPBUtil::checkString($var, True); + $this->name = $var; + + return $this; + } + + /** + * Generated from protobuf field optional int32 number = 2; + * @return int + */ + public function getNumber() + { + return isset($this->number) ? $this->number : 0; + } + + public function hasNumber() + { + return isset($this->number); + } + + public function clearNumber() + { + unset($this->number); + } + + /** + * Generated from protobuf field optional int32 number = 2; + * @param int $var + * @return $this + */ + public function setNumber($var) + { + GPBUtil::checkInt32($var); + $this->number = $var; + + return $this; + } + + /** + * Generated from protobuf field optional .google.protobuf.EnumValueOptions options = 3; + * @return \Google\Protobuf\Internal\EnumValueOptions|null + */ + public function getOptions() + { + return $this->options; + } + + public function hasOptions() + { + return isset($this->options); + } + + public function clearOptions() + { + unset($this->options); + } + + /** + * Generated from protobuf field optional .google.protobuf.EnumValueOptions options = 3; + * @param \Google\Protobuf\Internal\EnumValueOptions $var + * @return $this + */ + public function setOptions($var) + { + GPBUtil::checkMessage($var, \Google\Protobuf\Internal\EnumValueOptions::class); + $this->options = $var; + + return $this; + } + +} + diff --git a/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/FieldDescriptorProto_Label.php b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/FieldDescriptorProto_Label.php new file mode 100644 index 0000000..218a846 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/FieldDescriptorProto_Label.php @@ -0,0 +1,16 @@ +google.protobuf.FieldOptions.CType + */ +class CType +{ + /** + * Default mode. + * + * Generated from protobuf enum STRING = 0; + */ + const STRING = 0; + /** + * Generated from protobuf enum CORD = 1; + */ + const CORD = 1; + /** + * Generated from protobuf enum STRING_PIECE = 2; + */ + const STRING_PIECE = 2; + + private static $valueToName = [ + self::STRING => 'STRING', + self::CORD => 'CORD', + self::STRING_PIECE => 'STRING_PIECE', + ]; + + public static function name($value) + { + if (!isset(self::$valueToName[$value])) { + throw new UnexpectedValueException(sprintf( + 'Enum %s has no name defined for value %s', __CLASS__, $value)); + } + return self::$valueToName[$value]; + } + + + public static function value($name) + { + $const = __CLASS__ . '::' . strtoupper($name); + if (!defined($const)) { + throw new UnexpectedValueException(sprintf( + 'Enum %s has no value defined for name %s', __CLASS__, $name)); + } + return constant($const); + } +} + +// Adding a class alias for backwards compatibility with the previous class name. +class_alias(CType::class, \Google\Protobuf\Internal\FieldOptions_CType::class); + diff --git a/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/FieldOptions/JSType.php b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/FieldOptions/JSType.php new file mode 100644 index 0000000..175a433 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/FieldOptions/JSType.php @@ -0,0 +1,62 @@ +google.protobuf.FieldOptions.JSType + */ +class JSType +{ + /** + * Use the default type. + * + * Generated from protobuf enum JS_NORMAL = 0; + */ + const JS_NORMAL = 0; + /** + * Use JavaScript strings. + * + * Generated from protobuf enum JS_STRING = 1; + */ + const JS_STRING = 1; + /** + * Use JavaScript numbers. + * + * Generated from protobuf enum JS_NUMBER = 2; + */ + const JS_NUMBER = 2; + + private static $valueToName = [ + self::JS_NORMAL => 'JS_NORMAL', + self::JS_STRING => 'JS_STRING', + self::JS_NUMBER => 'JS_NUMBER', + ]; + + public static function name($value) + { + if (!isset(self::$valueToName[$value])) { + throw new UnexpectedValueException(sprintf( + 'Enum %s has no name defined for value %s', __CLASS__, $value)); + } + return self::$valueToName[$value]; + } + + + public static function value($name) + { + $const = __CLASS__ . '::' . strtoupper($name); + if (!defined($const)) { + throw new UnexpectedValueException(sprintf( + 'Enum %s has no value defined for name %s', __CLASS__, $name)); + } + return constant($const); + } +} + +// Adding a class alias for backwards compatibility with the previous class name. +class_alias(JSType::class, \Google\Protobuf\Internal\FieldOptions_JSType::class); + diff --git a/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/GPBType.php b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/GPBType.php new file mode 100644 index 0000000..fa849ce --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/GPBType.php @@ -0,0 +1,55 @@ +public_desc; + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/Message.php b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/Message.php new file mode 100644 index 0000000..19b48f0 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/Message.php @@ -0,0 +1,2034 @@ +initWithDescriptor($data); + } else { + $this->initWithGeneratedPool(); + if (is_array($data)) { + $this->mergeFromArray($data); + } else if (!empty($data)) { + throw new \InvalidArgumentException( + 'Message constructor must be an array or null.' + ); + } + } + } + + /** + * @ignore + */ + private function initWithGeneratedPool() + { + $pool = DescriptorPool::getGeneratedPool(); + $this->desc = $pool->getDescriptorByClassName(get_class($this)); + if (is_null($this->desc)) { + throw new \InvalidArgumentException( + get_class($this) ." is not found in descriptor pool. " . + 'Only generated classes may derive from Message.'); + } + foreach ($this->desc->getField() as $field) { + $setter = $field->getSetter(); + if ($field->isMap()) { + $message_type = $field->getMessageType(); + $key_field = $message_type->getFieldByNumber(1); + $value_field = $message_type->getFieldByNumber(2); + switch ($value_field->getType()) { + case GPBType::MESSAGE: + case GPBType::GROUP: + $map_field = new MapField( + $key_field->getType(), + $value_field->getType(), + $value_field->getMessageType()->getClass()); + $this->$setter($map_field); + break; + case GPBType::ENUM: + $map_field = new MapField( + $key_field->getType(), + $value_field->getType(), + $value_field->getEnumType()->getClass()); + $this->$setter($map_field); + break; + default: + $map_field = new MapField( + $key_field->getType(), + $value_field->getType()); + $this->$setter($map_field); + break; + } + } else if ($field->getLabel() === GPBLabel::REPEATED) { + switch ($field->getType()) { + case GPBType::MESSAGE: + case GPBType::GROUP: + $repeated_field = new RepeatedField( + $field->getType(), + $field->getMessageType()->getClass()); + $this->$setter($repeated_field); + break; + case GPBType::ENUM: + $repeated_field = new RepeatedField( + $field->getType(), + $field->getEnumType()->getClass()); + $this->$setter($repeated_field); + break; + default: + $repeated_field = new RepeatedField($field->getType()); + $this->$setter($repeated_field); + break; + } + } else if ($field->getOneofIndex() !== -1) { + $oneof = $this->desc->getOneofDecl()[$field->getOneofIndex()]; + $oneof_name = $oneof->getName(); + $this->$oneof_name = new OneofField($oneof); + } else if ($field->getLabel() === GPBLabel::OPTIONAL && + PHP_INT_SIZE == 4) { + switch ($field->getType()) { + case GPBType::INT64: + case GPBType::UINT64: + case GPBType::FIXED64: + case GPBType::SFIXED64: + case GPBType::SINT64: + $this->$setter("0"); + } + } + } + } + + /** + * @ignore + */ + private function initWithDescriptor(Descriptor $desc) + { + $this->desc = $desc; + foreach ($desc->getField() as $field) { + $setter = $field->getSetter(); + $defaultValue = $this->defaultValue($field); + $this->$setter($defaultValue); + } + } + + protected function readWrapperValue($member) + { + $field = $this->desc->getFieldByName($member); + $oneof_index = $field->getOneofIndex(); + if ($oneof_index === -1) { + $wrapper = $this->$member; + } else { + $wrapper = $this->readOneof($field->getNumber()); + } + + if (is_null($wrapper)) { + return NULL; + } else { + return $wrapper->getValue(); + } + } + + protected function writeWrapperValue($member, $value) + { + $field = $this->desc->getFieldByName($member); + $wrapped_value = $value; + if (!is_null($value)) { + $desc = $field->getMessageType(); + $klass = $desc->getClass(); + $wrapped_value = new $klass; + $wrapped_value->setValue($value); + } + + $oneof_index = $field->getOneofIndex(); + if ($oneof_index === -1) { + $this->$member = $wrapped_value; + } else { + $this->writeOneof($field->getNumber(), $wrapped_value); + } + } + + protected function readOneof($number) + { + $field = $this->desc->getFieldByNumber($number); + $oneof = $this->desc->getOneofDecl()[$field->getOneofIndex()]; + $oneof_name = $oneof->getName(); + $oneof_field = $this->$oneof_name; + if ($number === $oneof_field->getNumber()) { + return $oneof_field->getValue(); + } else { + return $this->defaultValue($field); + } + } + + protected function hasOneof($number) + { + $field = $this->desc->getFieldByNumber($number); + $oneof = $this->desc->getOneofDecl()[$field->getOneofIndex()]; + $oneof_name = $oneof->getName(); + $oneof_field = $this->$oneof_name; + return $number === $oneof_field->getNumber(); + } + + protected function writeOneof($number, $value) + { + $field = $this->desc->getFieldByNumber($number); + $oneof = $this->desc->getOneofDecl()[$field->getOneofIndex()]; + $oneof_name = $oneof->getName(); + if ($value === null) { + $this->$oneof_name = new OneofField($oneof); + } else { + $oneof_field = $this->$oneof_name; + $oneof_field->setValue($value); + $oneof_field->setFieldName($field->getName()); + $oneof_field->setNumber($number); + } + } + + protected function whichOneof($oneof_name) + { + $oneof_field = $this->$oneof_name; + $number = $oneof_field->getNumber(); + if ($number == 0) { + return ""; + } + $field = $this->desc->getFieldByNumber($number); + return $field->getName(); + } + + /** + * @ignore + */ + private function defaultValue($field) + { + $value = null; + + switch ($field->getType()) { + case GPBType::DOUBLE: + case GPBType::FLOAT: + return 0.0; + case GPBType::UINT32: + case GPBType::INT32: + case GPBType::FIXED32: + case GPBType::SFIXED32: + case GPBType::SINT32: + case GPBType::ENUM: + return 0; + case GPBType::INT64: + case GPBType::UINT64: + case GPBType::FIXED64: + case GPBType::SFIXED64: + case GPBType::SINT64: + if (PHP_INT_SIZE === 4) { + return '0'; + } else { + return 0; + } + case GPBType::BOOL: + return false; + case GPBType::STRING: + case GPBType::BYTES: + return ""; + case GPBType::GROUP: + case GPBType::MESSAGE: + return null; + default: + user_error("Unsupported type."); + return false; + } + } + + /** + * @ignore + */ + private function skipField($input, $tag) + { + $number = GPBWire::getTagFieldNumber($tag); + if ($number === 0) { + throw new GPBDecodeException("Illegal field number zero."); + } + + $start = $input->current(); + switch (GPBWire::getTagWireType($tag)) { + case GPBWireType::VARINT: + $uint64 = 0; + if (!$input->readVarint64($uint64)) { + throw new GPBDecodeException( + "Unexpected EOF inside varint."); + } + break; + case GPBWireType::FIXED64: + $uint64 = 0; + if (!$input->readLittleEndian64($uint64)) { + throw new GPBDecodeException( + "Unexpected EOF inside fixed64."); + } + break; + case GPBWireType::FIXED32: + $uint32 = 0; + if (!$input->readLittleEndian32($uint32)) { + throw new GPBDecodeException( + "Unexpected EOF inside fixed32."); + } + break; + case GPBWireType::LENGTH_DELIMITED: + $length = 0; + if (!$input->readVarint32($length)) { + throw new GPBDecodeException( + "Unexpected EOF inside length."); + } + $data = NULL; + if (!$input->readRaw($length, $data)) { + throw new GPBDecodeException( + "Unexpected EOF inside length delimited data."); + } + break; + case GPBWireType::START_GROUP: + case GPBWireType::END_GROUP: + throw new GPBDecodeException("Unexpected wire type."); + default: + throw new GPBDecodeException("Unexpected wire type."); + } + $end = $input->current(); + + $bytes = str_repeat(chr(0), CodedOutputStream::MAX_VARINT64_BYTES); + $size = CodedOutputStream::writeVarintToArray($tag, $bytes, true); + $this->unknown .= substr($bytes, 0, $size) . $input->substr($start, $end); + } + + /** + * @ignore + */ + private static function parseFieldFromStreamNoTag($input, $field, &$value) + { + switch ($field->getType()) { + case GPBType::DOUBLE: + if (!GPBWire::readDouble($input, $value)) { + throw new GPBDecodeException( + "Unexpected EOF inside double field."); + } + break; + case GPBType::FLOAT: + if (!GPBWire::readFloat($input, $value)) { + throw new GPBDecodeException( + "Unexpected EOF inside float field."); + } + break; + case GPBType::INT64: + if (!GPBWire::readInt64($input, $value)) { + throw new GPBDecodeException( + "Unexpected EOF inside int64 field."); + } + break; + case GPBType::UINT64: + if (!GPBWire::readUint64($input, $value)) { + throw new GPBDecodeException( + "Unexpected EOF inside uint64 field."); + } + break; + case GPBType::INT32: + if (!GPBWire::readInt32($input, $value)) { + throw new GPBDecodeException( + "Unexpected EOF inside int32 field."); + } + break; + case GPBType::FIXED64: + if (!GPBWire::readFixed64($input, $value)) { + throw new GPBDecodeException( + "Unexpected EOF inside fixed64 field."); + } + break; + case GPBType::FIXED32: + if (!GPBWire::readFixed32($input, $value)) { + throw new GPBDecodeException( + "Unexpected EOF inside fixed32 field."); + } + break; + case GPBType::BOOL: + if (!GPBWire::readBool($input, $value)) { + throw new GPBDecodeException( + "Unexpected EOF inside bool field."); + } + break; + case GPBType::STRING: + // TODO(teboring): Add utf-8 check. + if (!GPBWire::readString($input, $value)) { + throw new GPBDecodeException( + "Unexpected EOF inside string field."); + } + break; + case GPBType::GROUP: + trigger_error("Not implemented.", E_ERROR); + break; + case GPBType::MESSAGE: + if ($field->isMap()) { + $value = new MapEntry($field->getMessageType()); + } else { + $klass = $field->getMessageType()->getClass(); + $value = new $klass; + } + if (!GPBWire::readMessage($input, $value)) { + throw new GPBDecodeException( + "Unexpected EOF inside message."); + } + break; + case GPBType::BYTES: + if (!GPBWire::readString($input, $value)) { + throw new GPBDecodeException( + "Unexpected EOF inside bytes field."); + } + break; + case GPBType::UINT32: + if (!GPBWire::readUint32($input, $value)) { + throw new GPBDecodeException( + "Unexpected EOF inside uint32 field."); + } + break; + case GPBType::ENUM: + // TODO(teboring): Check unknown enum value. + if (!GPBWire::readInt32($input, $value)) { + throw new GPBDecodeException( + "Unexpected EOF inside enum field."); + } + break; + case GPBType::SFIXED32: + if (!GPBWire::readSfixed32($input, $value)) { + throw new GPBDecodeException( + "Unexpected EOF inside sfixed32 field."); + } + break; + case GPBType::SFIXED64: + if (!GPBWire::readSfixed64($input, $value)) { + throw new GPBDecodeException( + "Unexpected EOF inside sfixed64 field."); + } + break; + case GPBType::SINT32: + if (!GPBWire::readSint32($input, $value)) { + throw new GPBDecodeException( + "Unexpected EOF inside sint32 field."); + } + break; + case GPBType::SINT64: + if (!GPBWire::readSint64($input, $value)) { + throw new GPBDecodeException( + "Unexpected EOF inside sint64 field."); + } + break; + default: + user_error("Unsupported type."); + return false; + } + return true; + } + + /** + * @ignore + */ + private function parseFieldFromStream($tag, $input, $field) + { + $value = null; + + if (is_null($field)) { + $value_format = GPBWire::UNKNOWN; + } elseif (GPBWire::getTagWireType($tag) === + GPBWire::getWireType($field->getType())) { + $value_format = GPBWire::NORMAL_FORMAT; + } elseif ($field->isPackable() && + GPBWire::getTagWireType($tag) === + GPBWire::WIRETYPE_LENGTH_DELIMITED) { + $value_format = GPBWire::PACKED_FORMAT; + } else { + // the wire type doesn't match. Put it in our unknown field set. + $value_format = GPBWire::UNKNOWN; + } + + if ($value_format === GPBWire::UNKNOWN) { + $this->skipField($input, $tag); + return; + } elseif ($value_format === GPBWire::NORMAL_FORMAT) { + self::parseFieldFromStreamNoTag($input, $field, $value); + } elseif ($value_format === GPBWire::PACKED_FORMAT) { + $length = 0; + if (!GPBWire::readInt32($input, $length)) { + throw new GPBDecodeException( + "Unexpected EOF inside packed length."); + } + $limit = $input->pushLimit($length); + $getter = $field->getGetter(); + while ($input->bytesUntilLimit() > 0) { + self::parseFieldFromStreamNoTag($input, $field, $value); + $this->appendHelper($field, $value); + } + $input->popLimit($limit); + return; + } else { + return; + } + + if ($field->isMap()) { + $this->kvUpdateHelper($field, $value->getKey(), $value->getValue()); + } else if ($field->isRepeated()) { + $this->appendHelper($field, $value); + } else { + $setter = $field->getSetter(); + $this->$setter($value); + } + } + + /** + * Clear all containing fields. + * @return null. + */ + public function clear() + { + $this->unknown = ""; + foreach ($this->desc->getField() as $field) { + $setter = $field->getSetter(); + if ($field->isMap()) { + $message_type = $field->getMessageType(); + $key_field = $message_type->getFieldByNumber(1); + $value_field = $message_type->getFieldByNumber(2); + switch ($value_field->getType()) { + case GPBType::MESSAGE: + case GPBType::GROUP: + $map_field = new MapField( + $key_field->getType(), + $value_field->getType(), + $value_field->getMessageType()->getClass()); + $this->$setter($map_field); + break; + case GPBType::ENUM: + $map_field = new MapField( + $key_field->getType(), + $value_field->getType(), + $value_field->getEnumType()->getClass()); + $this->$setter($map_field); + break; + default: + $map_field = new MapField( + $key_field->getType(), + $value_field->getType()); + $this->$setter($map_field); + break; + } + } else if ($field->getLabel() === GPBLabel::REPEATED) { + switch ($field->getType()) { + case GPBType::MESSAGE: + case GPBType::GROUP: + $repeated_field = new RepeatedField( + $field->getType(), + $field->getMessageType()->getClass()); + $this->$setter($repeated_field); + break; + case GPBType::ENUM: + $repeated_field = new RepeatedField( + $field->getType(), + $field->getEnumType()->getClass()); + $this->$setter($repeated_field); + break; + default: + $repeated_field = new RepeatedField($field->getType()); + $this->$setter($repeated_field); + break; + } + } else if ($field->getOneofIndex() !== -1) { + $oneof = $this->desc->getOneofDecl()[$field->getOneofIndex()]; + $oneof_name = $oneof->getName(); + $this->$oneof_name = new OneofField($oneof); + } else if ($field->getLabel() === GPBLabel::OPTIONAL) { + switch ($field->getType()) { + case GPBType::DOUBLE : + case GPBType::FLOAT : + $this->$setter(0.0); + break; + case GPBType::INT32 : + case GPBType::FIXED32 : + case GPBType::UINT32 : + case GPBType::SFIXED32 : + case GPBType::SINT32 : + case GPBType::ENUM : + $this->$setter(0); + break; + case GPBType::BOOL : + $this->$setter(false); + break; + case GPBType::STRING : + case GPBType::BYTES : + $this->$setter(""); + break; + case GPBType::GROUP : + case GPBType::MESSAGE : + $null = null; + $this->$setter($null); + break; + } + if (PHP_INT_SIZE == 4) { + switch ($field->getType()) { + case GPBType::INT64: + case GPBType::UINT64: + case GPBType::FIXED64: + case GPBType::SFIXED64: + case GPBType::SINT64: + $this->$setter("0"); + } + } else { + switch ($field->getType()) { + case GPBType::INT64: + case GPBType::UINT64: + case GPBType::FIXED64: + case GPBType::SFIXED64: + case GPBType::SINT64: + $this->$setter(0); + } + } + } + } + } + + /** + * Clear all unknown fields previously parsed. + * @return null. + */ + public function discardUnknownFields() + { + $this->unknown = ""; + foreach ($this->desc->getField() as $field) { + if ($field->getType() != GPBType::MESSAGE) { + continue; + } + if ($field->isMap()) { + $value_field = $field->getMessageType()->getFieldByNumber(2); + if ($value_field->getType() != GPBType::MESSAGE) { + continue; + } + $getter = $field->getGetter(); + $map = $this->$getter(); + foreach ($map as $key => $value) { + $value->discardUnknownFields(); + } + } else if ($field->getLabel() === GPBLabel::REPEATED) { + $getter = $field->getGetter(); + $arr = $this->$getter(); + foreach ($arr as $sub) { + $sub->discardUnknownFields(); + } + } else if ($field->getLabel() === GPBLabel::OPTIONAL) { + $getter = $field->getGetter(); + $sub = $this->$getter(); + if (!is_null($sub)) { + $sub->discardUnknownFields(); + } + } + } + } + + /** + * Merges the contents of the specified message into current message. + * + * This method merges the contents of the specified message into the + * current message. Singular fields that are set in the specified message + * overwrite the corresponding fields in the current message. Repeated + * fields are appended. Map fields key-value pairs are overwritten. + * Singular/Oneof sub-messages are recursively merged. All overwritten + * sub-messages are deep-copied. + * + * @param object $msg Protobuf message to be merged from. + * @return null. + */ + public function mergeFrom($msg) + { + if (get_class($this) !== get_class($msg)) { + user_error("Cannot merge messages with different class."); + return; + } + + foreach ($this->desc->getField() as $field) { + $setter = $field->getSetter(); + $getter = $field->getGetter(); + if ($field->isMap()) { + if (count($msg->$getter()) != 0) { + $value_field = $field->getMessageType()->getFieldByNumber(2); + foreach ($msg->$getter() as $key => $value) { + if ($value_field->getType() == GPBType::MESSAGE) { + $klass = $value_field->getMessageType()->getClass(); + $copy = new $klass; + $copy->mergeFrom($value); + + $this->kvUpdateHelper($field, $key, $copy); + } else { + $this->kvUpdateHelper($field, $key, $value); + } + } + } + } else if ($field->getLabel() === GPBLabel::REPEATED) { + if (count($msg->$getter()) != 0) { + foreach ($msg->$getter() as $tmp) { + if ($field->getType() == GPBType::MESSAGE) { + $klass = $field->getMessageType()->getClass(); + $copy = new $klass; + $copy->mergeFrom($tmp); + $this->appendHelper($field, $copy); + } else { + $this->appendHelper($field, $tmp); + } + } + } + } else if ($field->getLabel() === GPBLabel::OPTIONAL) { + if($msg->$getter() !== $this->defaultValue($field)) { + $tmp = $msg->$getter(); + if ($field->getType() == GPBType::MESSAGE) { + if (is_null($this->$getter())) { + $klass = $field->getMessageType()->getClass(); + $new_msg = new $klass; + $this->$setter($new_msg); + } + $this->$getter()->mergeFrom($tmp); + } else { + $this->$setter($tmp); + } + } + } + } + } + + /** + * Parses a protocol buffer contained in a string. + * + * This function takes a string in the (non-human-readable) binary wire + * format, matching the encoding output by serializeToString(). + * See mergeFrom() for merging behavior, if the field is already set in the + * specified message. + * + * @param string $data Binary protobuf data. + * @return null. + * @throws \Exception Invalid data. + */ + public function mergeFromString($data) + { + $input = new CodedInputStream($data); + $this->parseFromStream($input); + } + + /** + * Parses a json string to protobuf message. + * + * This function takes a string in the json wire format, matching the + * encoding output by serializeToJsonString(). + * See mergeFrom() for merging behavior, if the field is already set in the + * specified message. + * + * @param string $data Json protobuf data. + * @return null. + * @throws \Exception Invalid data. + */ + public function mergeFromJsonString($data, $ignore_unknown = false) + { + $input = new RawInputStream($data); + $this->parseFromJsonStream($input, $ignore_unknown); + } + + /** + * @ignore + */ + public function parseFromStream($input) + { + while (true) { + $tag = $input->readTag(); + // End of input. This is a valid place to end, so return true. + if ($tag === 0) { + return true; + } + + $number = GPBWire::getTagFieldNumber($tag); + $field = $this->desc->getFieldByNumber($number); + + $this->parseFieldFromStream($tag, $input, $field); + } + } + + private function convertJsonValueToProtoValue( + $value, + $field, + $ignore_unknown, + $is_map_key = false) + { + switch ($field->getType()) { + case GPBType::MESSAGE: + $klass = $field->getMessageType()->getClass(); + $submsg = new $klass; + + if (is_a($submsg, "Google\Protobuf\Duration")) { + if (is_null($value)) { + return $this->defaultValue($field); + } else if (!is_string($value)) { + throw new GPBDecodeException("Expect string."); + } + return GPBUtil::parseDuration($value); + } else if ($field->isTimestamp()) { + if (is_null($value)) { + return $this->defaultValue($field); + } else if (!is_string($value)) { + throw new GPBDecodeException("Expect string."); + } + try { + $timestamp = GPBUtil::parseTimestamp($value); + } catch (\Exception $e) { + throw new GPBDecodeException( + "Invalid RFC 3339 timestamp: ".$e->getMessage()); + } + + $submsg->setSeconds($timestamp->getSeconds()); + $submsg->setNanos($timestamp->getNanos()); + } else if (is_a($submsg, "Google\Protobuf\FieldMask")) { + if (is_null($value)) { + return $this->defaultValue($field); + } + try { + return GPBUtil::parseFieldMask($value); + } catch (\Exception $e) { + throw new GPBDecodeException( + "Invalid FieldMask: ".$e->getMessage()); + } + } else { + if (is_null($value) && + !is_a($submsg, "Google\Protobuf\Value")) { + return $this->defaultValue($field); + } + if (GPBUtil::hasSpecialJsonMapping($submsg)) { + } elseif (!is_object($value) && !is_array($value)) { + throw new GPBDecodeException("Expect message."); + } + $submsg->mergeFromJsonArray($value, $ignore_unknown); + } + return $submsg; + case GPBType::ENUM: + if (is_null($value)) { + return $this->defaultValue($field); + } + if (is_integer($value)) { + return $value; + } + $enum_value = $field->getEnumType()->getValueByName($value); + if (!is_null($enum_value)) { + return $enum_value->getNumber(); + } else if ($ignore_unknown) { + return $this->defaultValue($field); + } else { + throw new GPBDecodeException( + "Enum field only accepts integer or enum value name"); + } + case GPBType::STRING: + if (is_null($value)) { + return $this->defaultValue($field); + } + if (is_numeric($value)) { + return strval($value); + } + if (!is_string($value)) { + throw new GPBDecodeException( + "String field only accepts string value"); + } + return $value; + case GPBType::BYTES: + if (is_null($value)) { + return $this->defaultValue($field); + } + if (!is_string($value)) { + throw new GPBDecodeException( + "Byte field only accepts string value"); + } + $proto_value = base64_decode($value, true); + if ($proto_value === false) { + throw new GPBDecodeException("Invalid base64 characters"); + } + return $proto_value; + case GPBType::BOOL: + if (is_null($value)) { + return $this->defaultValue($field); + } + if ($is_map_key) { + if ($value === "true") { + return true; + } + if ($value === "false") { + return false; + } + throw new GPBDecodeException( + "Bool field only accepts bool value"); + } + if (!is_bool($value)) { + throw new GPBDecodeException( + "Bool field only accepts bool value"); + } + return $value; + case GPBType::FLOAT: + case GPBType::DOUBLE: + if (is_null($value)) { + return $this->defaultValue($field); + } + if ($value === "Infinity") { + return INF; + } + if ($value === "-Infinity") { + return -INF; + } + if ($value === "NaN") { + return NAN; + } + return $value; + case GPBType::INT32: + case GPBType::SINT32: + case GPBType::SFIXED32: + if (is_null($value)) { + return $this->defaultValue($field); + } + if (!is_numeric($value)) { + throw new GPBDecodeException( + "Invalid data type for int32 field"); + } + if (is_string($value) && trim($value) !== $value) { + throw new GPBDecodeException( + "Invalid data type for int32 field"); + } + if (bccomp($value, "2147483647") > 0) { + throw new GPBDecodeException( + "Int32 too large"); + } + if (bccomp($value, "-2147483648") < 0) { + throw new GPBDecodeException( + "Int32 too small"); + } + return $value; + case GPBType::UINT32: + case GPBType::FIXED32: + if (is_null($value)) { + return $this->defaultValue($field); + } + if (!is_numeric($value)) { + throw new GPBDecodeException( + "Invalid data type for uint32 field"); + } + if (is_string($value) && trim($value) !== $value) { + throw new GPBDecodeException( + "Invalid data type for int32 field"); + } + if (bccomp($value, 4294967295) > 0) { + throw new GPBDecodeException( + "Uint32 too large"); + } + return $value; + case GPBType::INT64: + case GPBType::SINT64: + case GPBType::SFIXED64: + if (is_null($value)) { + return $this->defaultValue($field); + } + if (!is_numeric($value)) { + throw new GPBDecodeException( + "Invalid data type for int64 field"); + } + if (is_string($value) && trim($value) !== $value) { + throw new GPBDecodeException( + "Invalid data type for int64 field"); + } + if (bccomp($value, "9223372036854775807") > 0) { + throw new GPBDecodeException( + "Int64 too large"); + } + if (bccomp($value, "-9223372036854775808") < 0) { + throw new GPBDecodeException( + "Int64 too small"); + } + return $value; + case GPBType::UINT64: + case GPBType::FIXED64: + if (is_null($value)) { + return $this->defaultValue($field); + } + if (!is_numeric($value)) { + throw new GPBDecodeException( + "Invalid data type for int64 field"); + } + if (is_string($value) && trim($value) !== $value) { + throw new GPBDecodeException( + "Invalid data type for int64 field"); + } + if (bccomp($value, "18446744073709551615") > 0) { + throw new GPBDecodeException( + "Uint64 too large"); + } + if (bccomp($value, "9223372036854775807") > 0) { + $value = bcsub($value, "18446744073709551616"); + } + return $value; + default: + return $value; + } + } + + /** + * Populates the message from a user-supplied PHP array. Array keys + * correspond to Message properties and nested message properties. + * + * Example: + * ``` + * $message->mergeFromArray([ + * 'name' => 'This is a message name', + * 'interval' => [ + * 'startTime' => time() - 60, + * 'endTime' => time(), + * ] + * ]); + * ``` + * + * This method will trigger an error if it is passed data that cannot + * be converted to the correct type. For example, a StringValue field + * must receive data that is either a string or a StringValue object. + * + * @param array $array An array containing message properties and values. + * @return null. + */ + protected function mergeFromArray(array $array) + { + // Just call the setters for the field names + foreach ($array as $key => $value) { + $field = $this->desc->getFieldByName($key); + if (is_null($field)) { + throw new \UnexpectedValueException( + 'Invalid message property: ' . $key); + } + $setter = $field->getSetter(); + if ($field->isMap()) { + $valueField = $field->getMessageType()->getFieldByName('value'); + if (!is_null($valueField) && $valueField->isWrapperType()) { + self::normalizeArrayElementsToMessageType($value, $valueField->getMessageType()->getClass()); + } + } elseif ($field->isWrapperType()) { + $class = $field->getMessageType()->getClass(); + if ($field->isRepeated()) { + self::normalizeArrayElementsToMessageType($value, $class); + } else { + self::normalizeToMessageType($value, $class); + } + } + $this->$setter($value); + } + } + + /** + * Tries to normalize the elements in $value into a provided protobuf + * wrapper type $class. If $value is any type other than array, we do + * not do any conversion, and instead rely on the existing protobuf + * type checking. If $value is an array, we process each element and + * try to convert it to an instance of $class. + * + * @param mixed $value The array of values to normalize. + * @param string $class The expected wrapper class name + */ + private static function normalizeArrayElementsToMessageType(&$value, $class) + { + if (!is_array($value)) { + // In the case that $value is not an array, we do not want to + // attempt any conversion. Note that this includes the cases + // when $value is a RepeatedField of MapField. In those cases, + // we do not need to convert the elements, as they should + // already be the correct types. + return; + } else { + // Normalize each element in the array. + foreach ($value as $key => &$elementValue) { + self::normalizeToMessageType($elementValue, $class); + } + } + } + + /** + * Tries to normalize $value into a provided protobuf wrapper type $class. + * If $value is any type other than an object, we attempt to construct an + * instance of $class and assign $value to it using the setValue method + * shared by all wrapper types. + * + * This method will raise an error if it receives a type that cannot be + * assigned to the wrapper type via setValue. + * + * @param mixed $value The value to normalize. + * @param string $class The expected wrapper class name + */ + private static function normalizeToMessageType(&$value, $class) + { + if (is_null($value) || is_object($value)) { + // This handles the case that $value is an instance of $class. We + // choose not to do any more strict checking here, relying on the + // existing type checking done by GPBUtil. + return; + } else { + // Try to instantiate $class and set the value + try { + $msg = new $class; + $msg->setValue($value); + $value = $msg; + return; + } catch (\Exception $exception) { + trigger_error( + "Error normalizing value to type '$class': " . $exception->getMessage(), + E_USER_ERROR + ); + } + } + } + + protected function mergeFromJsonArray($array, $ignore_unknown) + { + if (is_a($this, "Google\Protobuf\Any")) { + $this->clear(); + $this->setTypeUrl($array["@type"]); + $msg = $this->unpack(); + if (GPBUtil::hasSpecialJsonMapping($msg)) { + $msg->mergeFromJsonArray($array["value"], $ignore_unknown); + } else { + unset($array["@type"]); + $msg->mergeFromJsonArray($array, $ignore_unknown); + } + $this->setValue($msg->serializeToString()); + return; + } + if (is_a($this, "Google\Protobuf\DoubleValue") || + is_a($this, "Google\Protobuf\FloatValue") || + is_a($this, "Google\Protobuf\Int64Value") || + is_a($this, "Google\Protobuf\UInt64Value") || + is_a($this, "Google\Protobuf\Int32Value") || + is_a($this, "Google\Protobuf\UInt32Value") || + is_a($this, "Google\Protobuf\BoolValue") || + is_a($this, "Google\Protobuf\StringValue")) { + $this->setValue($array); + return; + } + if (is_a($this, "Google\Protobuf\BytesValue")) { + $this->setValue(base64_decode($array)); + return; + } + if (is_a($this, "Google\Protobuf\Duration")) { + $this->mergeFrom(GPBUtil::parseDuration($array)); + return; + } + if (is_a($this, "Google\Protobuf\FieldMask")) { + $this->mergeFrom(GPBUtil::parseFieldMask($array)); + return; + } + if (is_a($this, "Google\Protobuf\Timestamp")) { + $this->mergeFrom(GPBUtil::parseTimestamp($array)); + return; + } + if (is_a($this, "Google\Protobuf\Struct")) { + $fields = $this->getFields(); + foreach($array as $key => $value) { + $v = new Value(); + $v->mergeFromJsonArray($value, $ignore_unknown); + $fields[$key] = $v; + } + return; + } + if (is_a($this, "Google\Protobuf\Value")) { + if (is_bool($array)) { + $this->setBoolValue($array); + } elseif (is_string($array)) { + $this->setStringValue($array); + } elseif (is_null($array)) { + $this->setNullValue(0); + } elseif (is_double($array) || is_integer($array)) { + $this->setNumberValue($array); + } elseif (is_array($array)) { + if (array_values($array) !== $array) { + // Associative array + $struct_value = $this->getStructValue(); + if (is_null($struct_value)) { + $struct_value = new Struct(); + $this->setStructValue($struct_value); + } + foreach ($array as $key => $v) { + $value = new Value(); + $value->mergeFromJsonArray($v, $ignore_unknown); + $values = $struct_value->getFields(); + $values[$key]= $value; + } + } else { + // Array + $list_value = $this->getListValue(); + if (is_null($list_value)) { + $list_value = new ListValue(); + $this->setListValue($list_value); + } + foreach ($array as $v) { + $value = new Value(); + $value->mergeFromJsonArray($v, $ignore_unknown); + $values = $list_value->getValues(); + $values[]= $value; + } + } + } else { + throw new GPBDecodeException("Invalid type for Value."); + } + return; + } + $this->mergeFromArrayJsonImpl($array, $ignore_unknown); + } + + private function mergeFromArrayJsonImpl($array, $ignore_unknown) + { + foreach ($array as $key => $value) { + $field = $this->desc->getFieldByJsonName($key); + if (is_null($field)) { + $field = $this->desc->getFieldByName($key); + if (is_null($field)) { + if ($ignore_unknown) { + continue; + } else { + throw new GPBDecodeException( + $key . ' is unknown.' + ); + } + } + } + if ($field->isMap()) { + if (is_null($value)) { + continue; + } + $key_field = $field->getMessageType()->getFieldByNumber(1); + $value_field = $field->getMessageType()->getFieldByNumber(2); + foreach ($value as $tmp_key => $tmp_value) { + if (is_null($tmp_value)) { + throw new \Exception( + "Map value field element cannot be null."); + } + $proto_key = $this->convertJsonValueToProtoValue( + $tmp_key, + $key_field, + $ignore_unknown, + true); + $proto_value = $this->convertJsonValueToProtoValue( + $tmp_value, + $value_field, + $ignore_unknown); + self::kvUpdateHelper($field, $proto_key, $proto_value); + } + } else if ($field->isRepeated()) { + if (is_null($value)) { + continue; + } + foreach ($value as $tmp) { + if (is_null($tmp)) { + throw new \Exception( + "Repeated field elements cannot be null."); + } + $proto_value = $this->convertJsonValueToProtoValue( + $tmp, + $field, + $ignore_unknown); + self::appendHelper($field, $proto_value); + } + } else { + $setter = $field->getSetter(); + $proto_value = $this->convertJsonValueToProtoValue( + $value, + $field, + $ignore_unknown); + if ($field->getType() === GPBType::MESSAGE) { + if (is_null($proto_value)) { + continue; + } + $getter = $field->getGetter(); + $submsg = $this->$getter(); + if (!is_null($submsg)) { + $submsg->mergeFrom($proto_value); + continue; + } + } + $this->$setter($proto_value); + } + } + } + + /** + * @ignore + */ + public function parseFromJsonStream($input, $ignore_unknown) + { + $array = json_decode($input->getData(), true, 512, JSON_BIGINT_AS_STRING); + if ($this instanceof \Google\Protobuf\ListValue) { + $array = ["values"=>$array]; + } + if (is_null($array)) { + if ($this instanceof \Google\Protobuf\Value) { + $this->setNullValue(\Google\Protobuf\NullValue::NULL_VALUE); + return; + } else { + throw new GPBDecodeException( + "Cannot decode json string: " . $input->getData()); + } + } + try { + $this->mergeFromJsonArray($array, $ignore_unknown); + } catch (\Exception $e) { + throw new GPBDecodeException($e->getMessage()); + } + } + + /** + * @ignore + */ + private function serializeSingularFieldToStream($field, &$output) + { + if (!$this->existField($field)) { + return true; + } + $getter = $field->getGetter(); + $value = $this->$getter(); + if (!GPBWire::serializeFieldToStream($value, $field, true, $output)) { + return false; + } + return true; + } + + /** + * @ignore + */ + private function serializeRepeatedFieldToStream($field, &$output) + { + $getter = $field->getGetter(); + $values = $this->$getter(); + $count = count($values); + if ($count === 0) { + return true; + } + + $packed = $field->getPacked(); + if ($packed) { + if (!GPBWire::writeTag( + $output, + GPBWire::makeTag($field->getNumber(), GPBType::STRING))) { + return false; + } + $size = 0; + foreach ($values as $value) { + $size += $this->fieldDataOnlyByteSize($field, $value); + } + if (!$output->writeVarint32($size, true)) { + return false; + } + } + + foreach ($values as $value) { + if (!GPBWire::serializeFieldToStream( + $value, + $field, + !$packed, + $output)) { + return false; + } + } + return true; + } + + /** + * @ignore + */ + private function serializeMapFieldToStream($field, $output) + { + $getter = $field->getGetter(); + $values = $this->$getter(); + $count = count($values); + if ($count === 0) { + return true; + } + + foreach ($values as $key => $value) { + $map_entry = new MapEntry($field->getMessageType()); + $map_entry->setKey($key); + $map_entry->setValue($value); + if (!GPBWire::serializeFieldToStream( + $map_entry, + $field, + true, + $output)) { + return false; + } + } + return true; + } + + /** + * @ignore + */ + private function serializeFieldToStream(&$output, $field) + { + if ($field->isMap()) { + return $this->serializeMapFieldToStream($field, $output); + } elseif ($field->isRepeated()) { + return $this->serializeRepeatedFieldToStream($field, $output); + } else { + return $this->serializeSingularFieldToStream($field, $output); + } + } + + /** + * @ignore + */ + private function serializeFieldToJsonStream(&$output, $field) + { + $getter = $field->getGetter(); + $values = $this->$getter(); + return GPBJsonWire::serializeFieldToStream( + $values, $field, $output, !GPBUtil::hasSpecialJsonMapping($this)); + } + + /** + * @ignore + */ + public function serializeToStream(&$output) + { + $fields = $this->desc->getField(); + foreach ($fields as $field) { + if (!$this->serializeFieldToStream($output, $field)) { + return false; + } + } + $output->writeRaw($this->unknown, strlen($this->unknown)); + return true; + } + + /** + * @ignore + */ + public function serializeToJsonStream(&$output) + { + if (is_a($this, 'Google\Protobuf\Any')) { + $output->writeRaw("{", 1); + $type_field = $this->desc->getFieldByNumber(1); + $value_msg = $this->unpack(); + + // Serialize type url. + $output->writeRaw("\"@type\":", 8); + $output->writeRaw("\"", 1); + $output->writeRaw($this->getTypeUrl(), strlen($this->getTypeUrl())); + $output->writeRaw("\"", 1); + + // Serialize value + if (GPBUtil::hasSpecialJsonMapping($value_msg)) { + $output->writeRaw(",\"value\":", 9); + $value_msg->serializeToJsonStream($output); + } else { + $value_fields = $value_msg->desc->getField(); + foreach ($value_fields as $field) { + if ($value_msg->existField($field)) { + $output->writeRaw(",", 1); + if (!$value_msg->serializeFieldToJsonStream($output, $field)) { + return false; + } + } + } + } + + $output->writeRaw("}", 1); + } elseif (is_a($this, 'Google\Protobuf\FieldMask')) { + $field_mask = GPBUtil::formatFieldMask($this); + $output->writeRaw("\"", 1); + $output->writeRaw($field_mask, strlen($field_mask)); + $output->writeRaw("\"", 1); + } elseif (is_a($this, 'Google\Protobuf\Duration')) { + $duration = GPBUtil::formatDuration($this) . "s"; + $output->writeRaw("\"", 1); + $output->writeRaw($duration, strlen($duration)); + $output->writeRaw("\"", 1); + } elseif (get_class($this) === 'Google\Protobuf\Timestamp') { + $timestamp = GPBUtil::formatTimestamp($this); + $timestamp = json_encode($timestamp); + $output->writeRaw($timestamp, strlen($timestamp)); + } elseif (get_class($this) === 'Google\Protobuf\ListValue') { + $field = $this->desc->getField()[1]; + if (!$this->existField($field)) { + $output->writeRaw("[]", 2); + } else { + if (!$this->serializeFieldToJsonStream($output, $field)) { + return false; + } + } + } elseif (get_class($this) === 'Google\Protobuf\Struct') { + $field = $this->desc->getField()[1]; + if (!$this->existField($field)) { + $output->writeRaw("{}", 2); + } else { + if (!$this->serializeFieldToJsonStream($output, $field)) { + return false; + } + } + } else { + if (!GPBUtil::hasSpecialJsonMapping($this)) { + $output->writeRaw("{", 1); + } + $fields = $this->desc->getField(); + $first = true; + foreach ($fields as $field) { + if ($this->existField($field) || + GPBUtil::hasJsonValue($this)) { + if ($first) { + $first = false; + } else { + $output->writeRaw(",", 1); + } + if (!$this->serializeFieldToJsonStream($output, $field)) { + return false; + } + } + } + if (!GPBUtil::hasSpecialJsonMapping($this)) { + $output->writeRaw("}", 1); + } + } + return true; + } + + /** + * Serialize the message to string. + * @return string Serialized binary protobuf data. + */ + public function serializeToString() + { + $output = new CodedOutputStream($this->byteSize()); + $this->serializeToStream($output); + return $output->getData(); + } + + /** + * Serialize the message to json string. + * @return string Serialized json protobuf data. + */ + public function serializeToJsonString() + { + $output = new CodedOutputStream($this->jsonByteSize()); + $this->serializeToJsonStream($output); + return $output->getData(); + } + + /** + * @ignore + */ + private function existField($field) + { + $getter = $field->getGetter(); + $hazzer = "has" . substr($getter, 3); + + if (method_exists($this, $hazzer)) { + return $this->$hazzer(); + } else if ($field->getOneofIndex() !== -1) { + // For old generated code, which does not have hazzers for oneof + // fields. + $oneof = $this->desc->getOneofDecl()[$field->getOneofIndex()]; + $oneof_name = $oneof->getName(); + return $this->$oneof_name->getNumber() === $field->getNumber(); + } + + $values = $this->$getter(); + if ($field->isMap()) { + return count($values) !== 0; + } elseif ($field->isRepeated()) { + return count($values) !== 0; + } else { + return $values !== $this->defaultValue($field); + } + } + + /** + * @ignore + */ + private function repeatedFieldDataOnlyByteSize($field) + { + $size = 0; + + $getter = $field->getGetter(); + $values = $this->$getter(); + $count = count($values); + if ($count !== 0) { + $size += $count * GPBWire::tagSize($field); + foreach ($values as $value) { + $size += $this->singularFieldDataOnlyByteSize($field); + } + } + } + + /** + * @ignore + */ + private function fieldDataOnlyByteSize($field, $value) + { + $size = 0; + + switch ($field->getType()) { + case GPBType::BOOL: + $size += 1; + break; + case GPBType::FLOAT: + case GPBType::FIXED32: + case GPBType::SFIXED32: + $size += 4; + break; + case GPBType::DOUBLE: + case GPBType::FIXED64: + case GPBType::SFIXED64: + $size += 8; + break; + case GPBType::INT32: + case GPBType::ENUM: + $size += GPBWire::varint32Size($value, true); + break; + case GPBType::UINT32: + $size += GPBWire::varint32Size($value); + break; + case GPBType::UINT64: + case GPBType::INT64: + $size += GPBWire::varint64Size($value); + break; + case GPBType::SINT32: + $size += GPBWire::sint32Size($value); + break; + case GPBType::SINT64: + $size += GPBWire::sint64Size($value); + break; + case GPBType::STRING: + case GPBType::BYTES: + $size += strlen($value); + $size += GPBWire::varint32Size($size); + break; + case GPBType::MESSAGE: + $size += $value->byteSize(); + $size += GPBWire::varint32Size($size); + break; + case GPBType::GROUP: + // TODO(teboring): Add support. + user_error("Unsupported type."); + break; + default: + user_error("Unsupported type."); + return 0; + } + + return $size; + } + + /** + * @ignore + */ + private function fieldDataOnlyJsonByteSize($field, $value) + { + $size = 0; + + switch ($field->getType()) { + case GPBType::SFIXED32: + case GPBType::SINT32: + case GPBType::INT32: + $size += strlen(strval($value)); + break; + case GPBType::FIXED32: + case GPBType::UINT32: + if ($value < 0) { + $value = bcadd($value, "4294967296"); + } + $size += strlen(strval($value)); + break; + case GPBType::FIXED64: + case GPBType::UINT64: + if ($value < 0) { + $value = bcadd($value, "18446744073709551616"); + } + // Intentional fall through. + case GPBType::SFIXED64: + case GPBType::INT64: + case GPBType::SINT64: + $size += 2; // size for "" + $size += strlen(strval($value)); + break; + case GPBType::FLOAT: + if (is_nan($value)) { + $size += strlen("NaN") + 2; + } elseif ($value === INF) { + $size += strlen("Infinity") + 2; + } elseif ($value === -INF) { + $size += strlen("-Infinity") + 2; + } else { + $size += strlen(sprintf("%.8g", $value)); + } + break; + case GPBType::DOUBLE: + if (is_nan($value)) { + $size += strlen("NaN") + 2; + } elseif ($value === INF) { + $size += strlen("Infinity") + 2; + } elseif ($value === -INF) { + $size += strlen("-Infinity") + 2; + } else { + $size += strlen(sprintf("%.17g", $value)); + } + break; + case GPBType::ENUM: + $enum_desc = $field->getEnumType(); + if ($enum_desc->getClass() === "Google\Protobuf\NullValue") { + $size += 4; + break; + } + $enum_value_desc = $enum_desc->getValueByNumber($value); + if (!is_null($enum_value_desc)) { + $size += 2; // size for "" + $size += strlen($enum_value_desc->getName()); + } else { + $str_value = strval($value); + $size += strlen($str_value); + } + break; + case GPBType::BOOL: + if ($value) { + $size += 4; + } else { + $size += 5; + } + break; + case GPBType::STRING: + $value = json_encode($value, JSON_UNESCAPED_UNICODE); + $size += strlen($value); + break; + case GPBType::BYTES: + # if (is_a($this, "Google\Protobuf\BytesValue")) { + # $size += strlen(json_encode($value)); + # } else { + # $size += strlen(base64_encode($value)); + # $size += 2; // size for \"\" + # } + $size += strlen(base64_encode($value)); + $size += 2; // size for \"\" + break; + case GPBType::MESSAGE: + $size += $value->jsonByteSize(); + break; +# case GPBType::GROUP: +# // TODO(teboring): Add support. +# user_error("Unsupported type."); +# break; + default: + user_error("Unsupported type " . $field->getType()); + return 0; + } + + return $size; + } + + /** + * @ignore + */ + private function fieldByteSize($field) + { + $size = 0; + if ($field->isMap()) { + $getter = $field->getGetter(); + $values = $this->$getter(); + $count = count($values); + if ($count !== 0) { + $size += $count * GPBWire::tagSize($field); + $message_type = $field->getMessageType(); + $key_field = $message_type->getFieldByNumber(1); + $value_field = $message_type->getFieldByNumber(2); + foreach ($values as $key => $value) { + $data_size = 0; + if ($key != $this->defaultValue($key_field)) { + $data_size += $this->fieldDataOnlyByteSize( + $key_field, + $key); + $data_size += GPBWire::tagSize($key_field); + } + if ($value != $this->defaultValue($value_field)) { + $data_size += $this->fieldDataOnlyByteSize( + $value_field, + $value); + $data_size += GPBWire::tagSize($value_field); + } + $size += GPBWire::varint32Size($data_size) + $data_size; + } + } + } elseif ($field->isRepeated()) { + $getter = $field->getGetter(); + $values = $this->$getter(); + $count = count($values); + if ($count !== 0) { + if ($field->getPacked()) { + $data_size = 0; + foreach ($values as $value) { + $data_size += $this->fieldDataOnlyByteSize($field, $value); + } + $size += GPBWire::tagSize($field); + $size += GPBWire::varint32Size($data_size); + $size += $data_size; + } else { + $size += $count * GPBWire::tagSize($field); + foreach ($values as $value) { + $size += $this->fieldDataOnlyByteSize($field, $value); + } + } + } + } elseif ($this->existField($field)) { + $size += GPBWire::tagSize($field); + $getter = $field->getGetter(); + $value = $this->$getter(); + $size += $this->fieldDataOnlyByteSize($field, $value); + } + return $size; + } + + /** + * @ignore + */ + private function fieldJsonByteSize($field) + { + $size = 0; + + if ($field->isMap()) { + $getter = $field->getGetter(); + $values = $this->$getter(); + $count = count($values); + if ($count !== 0) { + if (!GPBUtil::hasSpecialJsonMapping($this)) { + $size += 3; // size for "\"\":". + $size += strlen($field->getJsonName()); // size for field name + } + $size += 2; // size for "{}". + $size += $count - 1; // size for commas + $getter = $field->getGetter(); + $map_entry = $field->getMessageType(); + $key_field = $map_entry->getFieldByNumber(1); + $value_field = $map_entry->getFieldByNumber(2); + switch ($key_field->getType()) { + case GPBType::STRING: + case GPBType::SFIXED64: + case GPBType::INT64: + case GPBType::SINT64: + case GPBType::FIXED64: + case GPBType::UINT64: + $additional_quote = false; + break; + default: + $additional_quote = true; + } + foreach ($values as $key => $value) { + if ($additional_quote) { + $size += 2; // size for "" + } + $size += $this->fieldDataOnlyJsonByteSize($key_field, $key); + $size += $this->fieldDataOnlyJsonByteSize($value_field, $value); + $size += 1; // size for : + } + } + } elseif ($field->isRepeated()) { + $getter = $field->getGetter(); + $values = $this->$getter(); + $count = count($values); + if ($count !== 0) { + if (!GPBUtil::hasSpecialJsonMapping($this)) { + $size += 3; // size for "\"\":". + $size += strlen($field->getJsonName()); // size for field name + } + $size += 2; // size for "[]". + $size += $count - 1; // size for commas + $getter = $field->getGetter(); + foreach ($values as $value) { + $size += $this->fieldDataOnlyJsonByteSize($field, $value); + } + } + } elseif ($this->existField($field) || GPBUtil::hasJsonValue($this)) { + if (!GPBUtil::hasSpecialJsonMapping($this)) { + $size += 3; // size for "\"\":". + $size += strlen($field->getJsonName()); // size for field name + } + $getter = $field->getGetter(); + $value = $this->$getter(); + $size += $this->fieldDataOnlyJsonByteSize($field, $value); + } + return $size; + } + + /** + * @ignore + */ + public function byteSize() + { + $size = 0; + + $fields = $this->desc->getField(); + foreach ($fields as $field) { + $size += $this->fieldByteSize($field); + } + $size += strlen($this->unknown); + return $size; + } + + private function appendHelper($field, $append_value) + { + $getter = $field->getGetter(); + $setter = $field->getSetter(); + + $field_arr_value = $this->$getter(); + $field_arr_value[] = $append_value; + + if (!is_object($field_arr_value)) { + $this->$setter($field_arr_value); + } + } + + private function kvUpdateHelper($field, $update_key, $update_value) + { + $getter = $field->getGetter(); + $setter = $field->getSetter(); + + $field_arr_value = $this->$getter(); + $field_arr_value[$update_key] = $update_value; + + if (!is_object($field_arr_value)) { + $this->$setter($field_arr_value); + } + } + + /** + * @ignore + */ + public function jsonByteSize() + { + $size = 0; + if (is_a($this, 'Google\Protobuf\Any')) { + // Size for "{}". + $size += 2; + + // Size for "\"@type\":". + $size += 8; + + // Size for url. +2 for "" /. + $size += strlen($this->getTypeUrl()) + 2; + + $value_msg = $this->unpack(); + if (GPBUtil::hasSpecialJsonMapping($value_msg)) { + // Size for "\",value\":". + $size += 9; + $size += $value_msg->jsonByteSize(); + } else { + // Size for value. +1 for comma, -2 for "{}". + $size += $value_msg->jsonByteSize() -1; + } + } elseif (get_class($this) === 'Google\Protobuf\FieldMask') { + $field_mask = GPBUtil::formatFieldMask($this); + $size += strlen($field_mask) + 2; // 2 for "" + } elseif (get_class($this) === 'Google\Protobuf\Duration') { + $duration = GPBUtil::formatDuration($this) . "s"; + $size += strlen($duration) + 2; // 2 for "" + } elseif (get_class($this) === 'Google\Protobuf\Timestamp') { + $timestamp = GPBUtil::formatTimestamp($this); + $timestamp = json_encode($timestamp); + $size += strlen($timestamp); + } elseif (get_class($this) === 'Google\Protobuf\ListValue') { + $field = $this->desc->getField()[1]; + if ($this->existField($field)) { + $field_size = $this->fieldJsonByteSize($field); + $size += $field_size; + } else { + // Size for "[]". + $size += 2; + } + } elseif (get_class($this) === 'Google\Protobuf\Struct') { + $field = $this->desc->getField()[1]; + if ($this->existField($field)) { + $field_size = $this->fieldJsonByteSize($field); + $size += $field_size; + } else { + // Size for "{}". + $size += 2; + } + } else { + if (!GPBUtil::hasSpecialJsonMapping($this)) { + // Size for "{}". + $size += 2; + } + + $fields = $this->desc->getField(); + $count = 0; + foreach ($fields as $field) { + $field_size = $this->fieldJsonByteSize($field); + $size += $field_size; + if ($field_size != 0) { + $count++; + } + } + // size for comma + $size += $count > 0 ? ($count - 1) : 0; + } + return $size; + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/MessageBuilderContext.php b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/MessageBuilderContext.php new file mode 100644 index 0000000..2724d26 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/MessageBuilderContext.php @@ -0,0 +1,120 @@ +descriptor = new Descriptor(); + $this->descriptor->setFullName($full_name); + $this->descriptor->setClass($klass); + $this->pool = $pool; + } + + private function getFieldDescriptor($name, $label, $type, + $number, $type_name = null) + { + $field = new FieldDescriptor(); + $field->setName($name); + $camel_name = implode('', array_map('ucwords', explode('_', $name))); + $field->setGetter('get' . $camel_name); + $field->setSetter('set' . $camel_name); + $field->setType($type); + $field->setNumber($number); + $field->setLabel($label); + + // At this time, the message/enum type may have not been added to pool. + // So we use the type name as place holder and will replace it with the + // actual descriptor in cross building. + switch ($type) { + case GPBType::MESSAGE: + $field->setMessageType($type_name); + break; + case GPBType::ENUM: + $field->setEnumType($type_name); + break; + default: + break; + } + + return $field; + } + + public function optional($name, $type, $number, $type_name = null) + { + $this->descriptor->addField($this->getFieldDescriptor( + $name, + GPBLabel::OPTIONAL, + $type, + $number, + $type_name)); + return $this; + } + + public function repeated($name, $type, $number, $type_name = null) + { + $this->descriptor->addField($this->getFieldDescriptor( + $name, + GPBLabel::REPEATED, + $type, + $number, + $type_name)); + return $this; + } + + public function required($name, $type, $number, $type_name = null) + { + $this->descriptor->addField($this->getFieldDescriptor( + $name, + GPBLabel::REQUIRED, + $type, + $number, + $type_name)); + return $this; + } + + public function finalizeToPool() + { + $this->pool->addDescriptor($this->descriptor); + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/OneofField.php b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/OneofField.php new file mode 100644 index 0000000..2c689e8 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/OneofField.php @@ -0,0 +1,77 @@ +desc = $desc; + } + + public function setValue($value) + { + $this->value = $value; + } + + public function getValue() + { + return $this->value; + } + + public function setFieldName($field_name) + { + $this->field_name = $field_name; + } + + public function getFieldName() + { + return $this->field_name; + } + + public function setNumber($number) + { + $this->number = $number; + } + + public function getNumber() + { + return $this->number; + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/SourceCodeInfo/Location.php b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/SourceCodeInfo/Location.php new file mode 100644 index 0000000..c4cc667 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Internal/SourceCodeInfo/Location.php @@ -0,0 +1,448 @@ +google.protobuf.SourceCodeInfo.Location + */ +class Location extends \Google\Protobuf\Internal\Message +{ + /** + * Identifies which part of the FileDescriptorProto was defined at this + * location. + * Each element is a field number or an index. They form a path from + * the root FileDescriptorProto to the place where the definition. For + * example, this path: + * [ 4, 3, 2, 7, 1 ] + * refers to: + * file.message_type(3) // 4, 3 + * .field(7) // 2, 7 + * .name() // 1 + * This is because FileDescriptorProto.message_type has field number 4: + * repeated DescriptorProto message_type = 4; + * and DescriptorProto.field has field number 2: + * repeated FieldDescriptorProto field = 2; + * and FieldDescriptorProto.name has field number 1: + * optional string name = 1; + * Thus, the above path gives the location of a field name. If we removed + * the last element: + * [ 4, 3, 2, 7 ] + * this path refers to the whole field declaration (from the beginning + * of the label to the terminating semicolon). + * + * Generated from protobuf field repeated int32 path = 1 [packed = true]; + */ + private $path; + /** + * Always has exactly three or four elements: start line, start column, + * end line (optional, otherwise assumed same as start line), end column. + * These are packed into a single field for efficiency. Note that line + * and column numbers are zero-based -- typically you will want to add + * 1 to each before displaying to a user. + * + * Generated from protobuf field repeated int32 span = 2 [packed = true]; + */ + private $span; + /** + * If this SourceCodeInfo represents a complete declaration, these are any + * comments appearing before and after the declaration which appear to be + * attached to the declaration. + * A series of line comments appearing on consecutive lines, with no other + * tokens appearing on those lines, will be treated as a single comment. + * leading_detached_comments will keep paragraphs of comments that appear + * before (but not connected to) the current element. Each paragraph, + * separated by empty lines, will be one comment element in the repeated + * field. + * Only the comment content is provided; comment markers (e.g. //) are + * stripped out. For block comments, leading whitespace and an asterisk + * will be stripped from the beginning of each line other than the first. + * Newlines are included in the output. + * Examples: + * optional int32 foo = 1; // Comment attached to foo. + * // Comment attached to bar. + * optional int32 bar = 2; + * optional string baz = 3; + * // Comment attached to baz. + * // Another line attached to baz. + * // Comment attached to qux. + * // + * // Another line attached to qux. + * optional double qux = 4; + * // Detached comment for corge. This is not leading or trailing comments + * // to qux or corge because there are blank lines separating it from + * // both. + * // Detached comment for corge paragraph 2. + * optional string corge = 5; + * /* Block comment attached + * * to corge. Leading asterisks + * * will be removed. */ + * /* Block comment attached to + * * grault. */ + * optional int32 grault = 6; + * // ignored detached comments. + * + * Generated from protobuf field optional string leading_comments = 3; + */ + protected $leading_comments = null; + /** + * Generated from protobuf field optional string trailing_comments = 4; + */ + protected $trailing_comments = null; + /** + * Generated from protobuf field repeated string leading_detached_comments = 6; + */ + private $leading_detached_comments; + + /** + * Constructor. + * + * @param array $data { + * Optional. Data for populating the Message object. + * + * @type int[]|\Google\Protobuf\Internal\RepeatedField $path + * Identifies which part of the FileDescriptorProto was defined at this + * location. + * Each element is a field number or an index. They form a path from + * the root FileDescriptorProto to the place where the definition. For + * example, this path: + * [ 4, 3, 2, 7, 1 ] + * refers to: + * file.message_type(3) // 4, 3 + * .field(7) // 2, 7 + * .name() // 1 + * This is because FileDescriptorProto.message_type has field number 4: + * repeated DescriptorProto message_type = 4; + * and DescriptorProto.field has field number 2: + * repeated FieldDescriptorProto field = 2; + * and FieldDescriptorProto.name has field number 1: + * optional string name = 1; + * Thus, the above path gives the location of a field name. If we removed + * the last element: + * [ 4, 3, 2, 7 ] + * this path refers to the whole field declaration (from the beginning + * of the label to the terminating semicolon). + * @type int[]|\Google\Protobuf\Internal\RepeatedField $span + * Always has exactly three or four elements: start line, start column, + * end line (optional, otherwise assumed same as start line), end column. + * These are packed into a single field for efficiency. Note that line + * and column numbers are zero-based -- typically you will want to add + * 1 to each before displaying to a user. + * @type string $leading_comments + * If this SourceCodeInfo represents a complete declaration, these are any + * comments appearing before and after the declaration which appear to be + * attached to the declaration. + * A series of line comments appearing on consecutive lines, with no other + * tokens appearing on those lines, will be treated as a single comment. + * leading_detached_comments will keep paragraphs of comments that appear + * before (but not connected to) the current element. Each paragraph, + * separated by empty lines, will be one comment element in the repeated + * field. + * Only the comment content is provided; comment markers (e.g. //) are + * stripped out. For block comments, leading whitespace and an asterisk + * will be stripped from the beginning of each line other than the first. + * Newlines are included in the output. + * Examples: + * optional int32 foo = 1; // Comment attached to foo. + * // Comment attached to bar. + * optional int32 bar = 2; + * optional string baz = 3; + * // Comment attached to baz. + * // Another line attached to baz. + * // Comment attached to qux. + * // + * // Another line attached to qux. + * optional double qux = 4; + * // Detached comment for corge. This is not leading or trailing comments + * // to qux or corge because there are blank lines separating it from + * // both. + * // Detached comment for corge paragraph 2. + * optional string corge = 5; + * /* Block comment attached + * * to corge. Leading asterisks + * * will be removed. */ + * /* Block comment attached to + * * grault. */ + * optional int32 grault = 6; + * // ignored detached comments. + * @type string $trailing_comments + * @type string[]|\Google\Protobuf\Internal\RepeatedField $leading_detached_comments + * } + */ + public function __construct($data = NULL) { + \GPBMetadata\Google\Protobuf\Internal\Descriptor::initOnce(); + parent::__construct($data); + } + + /** + * Identifies which part of the FileDescriptorProto was defined at this + * location. + * Each element is a field number or an index. They form a path from + * the root FileDescriptorProto to the place where the definition. For + * example, this path: + * [ 4, 3, 2, 7, 1 ] + * refers to: + * file.message_type(3) // 4, 3 + * .field(7) // 2, 7 + * .name() // 1 + * This is because FileDescriptorProto.message_type has field number 4: + * repeated DescriptorProto message_type = 4; + * and DescriptorProto.field has field number 2: + * repeated FieldDescriptorProto field = 2; + * and FieldDescriptorProto.name has field number 1: + * optional string name = 1; + * Thus, the above path gives the location of a field name. If we removed + * the last element: + * [ 4, 3, 2, 7 ] + * this path refers to the whole field declaration (from the beginning + * of the label to the terminating semicolon). + * + * Generated from protobuf field repeated int32 path = 1 [packed = true]; + * @return \Google\Protobuf\Internal\RepeatedField + */ + public function getPath() + { + return $this->path; + } + + /** + * Identifies which part of the FileDescriptorProto was defined at this + * location. + * Each element is a field number or an index. They form a path from + * the root FileDescriptorProto to the place where the definition. For + * example, this path: + * [ 4, 3, 2, 7, 1 ] + * refers to: + * file.message_type(3) // 4, 3 + * .field(7) // 2, 7 + * .name() // 1 + * This is because FileDescriptorProto.message_type has field number 4: + * repeated DescriptorProto message_type = 4; + * and DescriptorProto.field has field number 2: + * repeated FieldDescriptorProto field = 2; + * and FieldDescriptorProto.name has field number 1: + * optional string name = 1; + * Thus, the above path gives the location of a field name. If we removed + * the last element: + * [ 4, 3, 2, 7 ] + * this path refers to the whole field declaration (from the beginning + * of the label to the terminating semicolon). + * + * Generated from protobuf field repeated int32 path = 1 [packed = true]; + * @param int[]|\Google\Protobuf\Internal\RepeatedField $var + * @return $this + */ + public function setPath($var) + { + $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::INT32); + $this->path = $arr; + + return $this; + } + + /** + * Always has exactly three or four elements: start line, start column, + * end line (optional, otherwise assumed same as start line), end column. + * These are packed into a single field for efficiency. Note that line + * and column numbers are zero-based -- typically you will want to add + * 1 to each before displaying to a user. + * + * Generated from protobuf field repeated int32 span = 2 [packed = true]; + * @return \Google\Protobuf\Internal\RepeatedField + */ + public function getSpan() + { + return $this->span; + } + + /** + * Always has exactly three or four elements: start line, start column, + * end line (optional, otherwise assumed same as start line), end column. + * These are packed into a single field for efficiency. Note that line + * and column numbers are zero-based -- typically you will want to add + * 1 to each before displaying to a user. + * + * Generated from protobuf field repeated int32 span = 2 [packed = true]; + * @param int[]|\Google\Protobuf\Internal\RepeatedField $var + * @return $this + */ + public function setSpan($var) + { + $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::INT32); + $this->span = $arr; + + return $this; + } + + /** + * If this SourceCodeInfo represents a complete declaration, these are any + * comments appearing before and after the declaration which appear to be + * attached to the declaration. + * A series of line comments appearing on consecutive lines, with no other + * tokens appearing on those lines, will be treated as a single comment. + * leading_detached_comments will keep paragraphs of comments that appear + * before (but not connected to) the current element. Each paragraph, + * separated by empty lines, will be one comment element in the repeated + * field. + * Only the comment content is provided; comment markers (e.g. //) are + * stripped out. For block comments, leading whitespace and an asterisk + * will be stripped from the beginning of each line other than the first. + * Newlines are included in the output. + * Examples: + * optional int32 foo = 1; // Comment attached to foo. + * // Comment attached to bar. + * optional int32 bar = 2; + * optional string baz = 3; + * // Comment attached to baz. + * // Another line attached to baz. + * // Comment attached to qux. + * // + * // Another line attached to qux. + * optional double qux = 4; + * // Detached comment for corge. This is not leading or trailing comments + * // to qux or corge because there are blank lines separating it from + * // both. + * // Detached comment for corge paragraph 2. + * optional string corge = 5; + * /* Block comment attached + * * to corge. Leading asterisks + * * will be removed. */ + * /* Block comment attached to + * * grault. */ + * optional int32 grault = 6; + * // ignored detached comments. + * + * Generated from protobuf field optional string leading_comments = 3; + * @return string + */ + public function getLeadingComments() + { + return isset($this->leading_comments) ? $this->leading_comments : ''; + } + + public function hasLeadingComments() + { + return isset($this->leading_comments); + } + + public function clearLeadingComments() + { + unset($this->leading_comments); + } + + /** + * If this SourceCodeInfo represents a complete declaration, these are any + * comments appearing before and after the declaration which appear to be + * attached to the declaration. + * A series of line comments appearing on consecutive lines, with no other + * tokens appearing on those lines, will be treated as a single comment. + * leading_detached_comments will keep paragraphs of comments that appear + * before (but not connected to) the current element. Each paragraph, + * separated by empty lines, will be one comment element in the repeated + * field. + * Only the comment content is provided; comment markers (e.g. //) are + * stripped out. For block comments, leading whitespace and an asterisk + * will be stripped from the beginning of each line other than the first. + * Newlines are included in the output. + * Examples: + * optional int32 foo = 1; // Comment attached to foo. + * // Comment attached to bar. + * optional int32 bar = 2; + * optional string baz = 3; + * // Comment attached to baz. + * // Another line attached to baz. + * // Comment attached to qux. + * // + * // Another line attached to qux. + * optional double qux = 4; + * // Detached comment for corge. This is not leading or trailing comments + * // to qux or corge because there are blank lines separating it from + * // both. + * // Detached comment for corge paragraph 2. + * optional string corge = 5; + * /* Block comment attached + * * to corge. Leading asterisks + * * will be removed. */ + * /* Block comment attached to + * * grault. */ + * optional int32 grault = 6; + * // ignored detached comments. + * + * Generated from protobuf field optional string leading_comments = 3; + * @param string $var + * @return $this + */ + public function setLeadingComments($var) + { + GPBUtil::checkString($var, True); + $this->leading_comments = $var; + + return $this; + } + + /** + * Generated from protobuf field optional string trailing_comments = 4; + * @return string + */ + public function getTrailingComments() + { + return isset($this->trailing_comments) ? $this->trailing_comments : ''; + } + + public function hasTrailingComments() + { + return isset($this->trailing_comments); + } + + public function clearTrailingComments() + { + unset($this->trailing_comments); + } + + /** + * Generated from protobuf field optional string trailing_comments = 4; + * @param string $var + * @return $this + */ + public function setTrailingComments($var) + { + GPBUtil::checkString($var, True); + $this->trailing_comments = $var; + + return $this; + } + + /** + * Generated from protobuf field repeated string leading_detached_comments = 6; + * @return \Google\Protobuf\Internal\RepeatedField + */ + public function getLeadingDetachedComments() + { + return $this->leading_detached_comments; + } + + /** + * Generated from protobuf field repeated string leading_detached_comments = 6; + * @param string[]|\Google\Protobuf\Internal\RepeatedField $var + * @return $this + */ + public function setLeadingDetachedComments($var) + { + $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::STRING); + $this->leading_detached_comments = $arr; + + return $this; + } + +} + +// Adding a class alias for backwards compatibility with the previous class name. +class_alias(Location::class, \Google\Protobuf\Internal\SourceCodeInfo_Location::class); + diff --git a/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Syntax.php b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Syntax.php new file mode 100644 index 0000000..10952bf --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/src/Google/Protobuf/Syntax.php @@ -0,0 +1,54 @@ +google.protobuf.Syntax + */ +class Syntax +{ + /** + * Syntax `proto2`. + * + * Generated from protobuf enum SYNTAX_PROTO2 = 0; + */ + const SYNTAX_PROTO2 = 0; + /** + * Syntax `proto3`. + * + * Generated from protobuf enum SYNTAX_PROTO3 = 1; + */ + const SYNTAX_PROTO3 = 1; + + private static $valueToName = [ + self::SYNTAX_PROTO2 => 'SYNTAX_PROTO2', + self::SYNTAX_PROTO3 => 'SYNTAX_PROTO3', + ]; + + public static function name($value) + { + if (!isset(self::$valueToName[$value])) { + throw new UnexpectedValueException(sprintf( + 'Enum %s has no name defined for value %s', __CLASS__, $value)); + } + return self::$valueToName[$value]; + } + + + public static function value($name) + { + $const = __CLASS__ . '::' . strtoupper($name); + if (!defined($const)) { + throw new UnexpectedValueException(sprintf( + 'Enum %s has no value defined for name %s', __CLASS__, $name)); + } + return constant($const); + } +} + diff --git a/tools/go-generator/cmd/generator/_protobuf/php/tests/WrapperTypeSettersTest.php b/tools/go-generator/cmd/generator/_protobuf/php/tests/WrapperTypeSettersTest.php new file mode 100644 index 0000000..045fa66 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/tests/WrapperTypeSettersTest.php @@ -0,0 +1,317 @@ + $value]); + + // Set values using new and old setters + $oldSetterMsg->$setter($wrappedValue); + $newSetterMsg->$valueSetter($value); + + // Get expected values old getter + $expectedValue = $oldSetterMsg->$getter(); + + // Check that old getter returns the same value after using the + // new setter + $actualValue = $newSetterMsg->$getter(); + $this->assertEquals($expectedValue, $actualValue); + + // Check that new getter returns the unwrapped value from + // $expectedValue + $actualValueNewGetter = $newSetterMsg->$valueGetter(); + if (is_null($expectedValue)) { + $this->assertNull($actualValueNewGetter); + } else { + $this->assertEquals($expectedValue->getValue(), $actualValueNewGetter); + } + } + } + + public function gettersAndSettersDataProvider() + { + return [ + [TestWrapperSetters::class, DoubleValue::class, "setDoubleValue", "setDoubleValueUnwrapped", "getDoubleValue", "getDoubleValueUnwrapped", [ + [1.1, new DoubleValue(["value" => 1.1])], + [2.2, new DoubleValue(["value" => 2.2])], + [null, null], + [0, new DoubleValue()], + ]], + [TestWrapperSetters::class, FloatValue::class, "setFloatValue", "setFloatValueUnwrapped", "getFloatValue", "getFloatValueUnwrapped", [ + [1.1, new FloatValue(["value" => 1.1])], + [2.2, new FloatValue(["value" => 2.2])], + [null, null], + [0, new FloatValue()], + ]], + [TestWrapperSetters::class, Int64Value::class, "setInt64Value", "setInt64ValueUnwrapped", "getInt64Value", "getInt64ValueUnwrapped", [ + [123, new Int64Value(["value" => 123])], + [-789, new Int64Value(["value" => -789])], + [null, null], + [0, new Int64Value()], + [5.5, new Int64Value(["value" => 5])], // Test conversion from float to int + ]], + [TestWrapperSetters::class, UInt64Value::class, "setUInt64Value", "setUInt64ValueUnwrapped", "getUInt64Value", "getUInt64ValueUnwrapped", [ + [123, new UInt64Value(["value" => 123])], + [789, new UInt64Value(["value" => 789])], + [null, null], + [0, new UInt64Value()], + [5.5, new UInt64Value(["value" => 5])], // Test conversion from float to int + [-7, new UInt64Value(["value" => -7])], // Test conversion from -ve to +ve + ]], + [TestWrapperSetters::class, Int32Value::class, "setInt32Value", "setInt32ValueUnwrapped", "getInt32Value", "getInt32ValueUnwrapped", [ + [123, new Int32Value(["value" => 123])], + [-789, new Int32Value(["value" => -789])], + [null, null], + [0, new Int32Value()], + [5.5, new Int32Value(["value" => 5])], // Test conversion from float to int + ]], + [TestWrapperSetters::class, UInt32Value::class, "setUInt32Value", "setUInt32ValueUnwrapped", "getUInt32Value", "getUInt32ValueUnwrapped", [ + [123, new UInt32Value(["value" => 123])], + [789, new UInt32Value(["value" => 789])], + [null, null], + [0, new UInt32Value()], + [5.5, new UInt32Value(["value" => 5])], // Test conversion from float to int + [-7, new UInt32Value(["value" => -7])], // Test conversion from -ve to +ve + ]], + [TestWrapperSetters::class, BoolValue::class, "setBoolValue", "setBoolValueUnwrapped", "getBoolValue", "getBoolValueUnwrapped", [ + [true, new BoolValue(["value" => true])], + [false, new BoolValue(["value" => false])], + [null, null], + ]], + [TestWrapperSetters::class, StringValue::class, "setStringValue", "setStringValueUnwrapped", "getStringValue", "getStringValueUnwrapped", [ + ["asdf", new StringValue(["value" => "asdf"])], + ["", new StringValue(["value" => ""])], + [null, null], + ["", new StringValue()], + [5, new StringValue(["value" => "5"])], // Test conversion from number to string + [5.5, new StringValue(["value" => "5.5"])], // Test conversion from number to string + [-7, new StringValue(["value" => "-7"])], // Test conversion from number to string + [-7.5, new StringValue(["value" => "-7.5"])], // Test conversion from number to string + ]], + [TestWrapperSetters::class, BytesValue::class, "setBytesValue", "setBytesValueUnwrapped", "getBytesValue", "getBytesValueUnwrapped", [ + ["asdf", new BytesValue(["value" => "asdf"])], + ["", new BytesValue(["value" => ""])], + [null, null], + ["", new BytesValue()], + [5, new BytesValue(["value" => "5"])], // Test conversion from number to bytes + [5.5, new BytesValue(["value" => "5.5"])], // Test conversion from number to bytes + [-7, new BytesValue(["value" => "-7"])], // Test conversion from number to bytes + [-7.5, new BytesValue(["value" => "-7.5"])], // Test conversion from number to bytes + ]], + [TestWrapperSetters::class, DoubleValue::class, "setDoubleValueOneof", "setDoubleValueOneofUnwrapped", "getDoubleValueOneof", "getDoubleValueOneofUnwrapped", [ + [1.1, new DoubleValue(["value" => 1.1])], + [2.2, new DoubleValue(["value" => 2.2])], + [null, null], + [0, new DoubleValue()], + ]], + [TestWrapperSetters::class, StringValue::class, "setStringValueOneof", "setStringValueOneofUnwrapped", "getStringValueOneof", "getStringValueOneofUnwrapped", [ + ["asdf", new StringValue(["value" => "asdf"])], + ["", new StringValue(["value" => ""])], + [null, null], + ["", new StringValue()], + [5, new StringValue(["value" => "5"])], // Test conversion from number to string + [5.5, new StringValue(["value" => "5.5"])], // Test conversion from number to string + [-7, new StringValue(["value" => "-7"])], // Test conversion from number to string + [-7.5, new StringValue(["value" => "-7.5"])], // Test conversion from number to string + ]], + ]; + } + + /** + * @dataProvider invalidSettersDataProvider + */ + public function testInvalidSetters($class, $setter, $value) + { + $this->expectException(Exception::class); + (new $class())->$setter($value); + } + + public function invalidSettersDataProvider() + { + return [ + [TestWrapperSetters::class, "setDoubleValueUnwrapped", "abc"], + [TestWrapperSetters::class, "setDoubleValueUnwrapped", []], + [TestWrapperSetters::class, "setDoubleValueUnwrapped", new stdClass()], + [TestWrapperSetters::class, "setDoubleValueUnwrapped", new DoubleValue()], + + [TestWrapperSetters::class, "setFloatValueUnwrapped", "abc"], + [TestWrapperSetters::class, "setFloatValueUnwrapped", []], + [TestWrapperSetters::class, "setFloatValueUnwrapped", new stdClass()], + [TestWrapperSetters::class, "setFloatValueUnwrapped", new FloatValue()], + + [TestWrapperSetters::class, "setInt64ValueUnwrapped", "abc"], + [TestWrapperSetters::class, "setInt64ValueUnwrapped", []], + [TestWrapperSetters::class, "setInt64ValueUnwrapped", new stdClass()], + [TestWrapperSetters::class, "setInt64ValueUnwrapped", new Int64Value()], + + [TestWrapperSetters::class, "setUInt64ValueUnwrapped", "abc"], + [TestWrapperSetters::class, "setUInt64ValueUnwrapped", []], + [TestWrapperSetters::class, "setUInt64ValueUnwrapped", new stdClass()], + [TestWrapperSetters::class, "setUInt64ValueUnwrapped", new UInt64Value()], + + [TestWrapperSetters::class, "setInt32ValueUnwrapped", "abc"], + [TestWrapperSetters::class, "setInt32ValueUnwrapped", []], + [TestWrapperSetters::class, "setInt32ValueUnwrapped", new stdClass()], + [TestWrapperSetters::class, "setInt32ValueUnwrapped", new Int32Value()], + + [TestWrapperSetters::class, "setUInt32ValueUnwrapped", "abc"], + [TestWrapperSetters::class, "setUInt32ValueUnwrapped", []], + [TestWrapperSetters::class, "setUInt32ValueUnwrapped", new stdClass()], + [TestWrapperSetters::class, "setUInt32ValueUnwrapped", new UInt32Value()], + + [TestWrapperSetters::class, "setBoolValueUnwrapped", []], + [TestWrapperSetters::class, "setBoolValueUnwrapped", new stdClass()], + [TestWrapperSetters::class, "setBoolValueUnwrapped", new BoolValue()], + + [TestWrapperSetters::class, "setStringValueUnwrapped", []], + [TestWrapperSetters::class, "setStringValueUnwrapped", new stdClass()], + [TestWrapperSetters::class, "setStringValueUnwrapped", new StringValue()], + + [TestWrapperSetters::class, "setBytesValueUnwrapped", []], + [TestWrapperSetters::class, "setBytesValueUnwrapped", new stdClass()], + [TestWrapperSetters::class, "setBytesValueUnwrapped", new BytesValue()], + ]; + } + + /** + * @dataProvider constructorWithWrapperTypeDataProvider + */ + public function testConstructorWithWrapperType($class, $wrapperClass, $wrapperField, $getter, $value) + { + $actualInstance = new $class([$wrapperField => $value]); + $expectedInstance = new $class([$wrapperField => new $wrapperClass(['value' => $value])]); + $this->assertEquals($expectedInstance->$getter()->getValue(), $actualInstance->$getter()->getValue()); + } + + public function constructorWithWrapperTypeDataProvider() + { + return [ + [TestWrapperSetters::class, DoubleValue::class, 'double_value', 'getDoubleValue', 1.1], + [TestWrapperSetters::class, FloatValue::class, 'float_value', 'getFloatValue', 2.2], + [TestWrapperSetters::class, Int64Value::class, 'int64_value', 'getInt64Value', 3], + [TestWrapperSetters::class, UInt64Value::class, 'uint64_value', 'getUInt64Value', 4], + [TestWrapperSetters::class, Int32Value::class, 'int32_value', 'getInt32Value', 5], + [TestWrapperSetters::class, UInt32Value::class, 'uint32_value', 'getUInt32Value', 6], + [TestWrapperSetters::class, BoolValue::class, 'bool_value', 'getBoolValue', true], + [TestWrapperSetters::class, StringValue::class, 'string_value', 'getStringValue', "eight"], + [TestWrapperSetters::class, BytesValue::class, 'bytes_value', 'getBytesValue', "nine"], + ]; + } + + /** + * @dataProvider constructorWithRepeatedWrapperTypeDataProvider + */ + public function testConstructorWithRepeatedWrapperType($wrapperField, $getter, $value) + { + $actualInstance = new TestWrapperSetters([$wrapperField => $value]); + foreach ($actualInstance->$getter() as $key => $actualWrapperValue) { + $actualInnerValue = $actualWrapperValue->getValue(); + $expectedElement = $value[$key]; + if (is_object($expectedElement) && is_a($expectedElement, '\Google\Protobuf\StringValue')) { + $expectedInnerValue = $expectedElement->getValue(); + } else { + $expectedInnerValue = $expectedElement; + } + $this->assertEquals($expectedInnerValue, $actualInnerValue); + } + + $this->assertTrue(true); + } + + public function constructorWithRepeatedWrapperTypeDataProvider() + { + $sv7 = new StringValue(['value' => 'seven']); + $sv8 = new StringValue(['value' => 'eight']); + + $testWrapperSetters = new TestWrapperSetters(); + $testWrapperSetters->setRepeatedStringValue([$sv7, $sv8]); + $repeatedField = $testWrapperSetters->getRepeatedStringValue(); + + return [ + ['repeated_string_value', 'getRepeatedStringValue', []], + ['repeated_string_value', 'getRepeatedStringValue', [$sv7]], + ['repeated_string_value', 'getRepeatedStringValue', [$sv7, $sv8]], + ['repeated_string_value', 'getRepeatedStringValue', ['seven']], + ['repeated_string_value', 'getRepeatedStringValue', [7]], + ['repeated_string_value', 'getRepeatedStringValue', [7.7]], + ['repeated_string_value', 'getRepeatedStringValue', ['seven', 'eight']], + ['repeated_string_value', 'getRepeatedStringValue', [$sv7, 'eight']], + ['repeated_string_value', 'getRepeatedStringValue', ['seven', $sv8]], + ['repeated_string_value', 'getRepeatedStringValue', $repeatedField], + ]; + } + + /** + * @dataProvider constructorWithMapWrapperTypeDataProvider + */ + public function testConstructorWithMapWrapperType($wrapperField, $getter, $value) + { + $actualInstance = new TestWrapperSetters([$wrapperField => $value]); + foreach ($actualInstance->$getter() as $key => $actualWrapperValue) { + $actualInnerValue = $actualWrapperValue->getValue(); + $expectedElement = $value[$key]; + if (is_object($expectedElement) && is_a($expectedElement, '\Google\Protobuf\StringValue')) { + $expectedInnerValue = $expectedElement->getValue(); + } elseif (is_object($expectedElement) && is_a($expectedElement, '\Google\Protobuf\Internal\MapEntry')) { + $expectedInnerValue = $expectedElement->getValue()->getValue(); + } else { + $expectedInnerValue = $expectedElement; + } + $this->assertEquals($expectedInnerValue, $actualInnerValue); + } + + $this->assertTrue(true); + } + + public function constructorWithMapWrapperTypeDataProvider() + { + $sv7 = new StringValue(['value' => 'seven']); + $sv8 = new StringValue(['value' => 'eight']); + + $testWrapperSetters = new TestWrapperSetters(); + $testWrapperSetters->setMapStringValue(['key' => $sv7, 'key2' => $sv8]); + $mapField = $testWrapperSetters->getMapStringValue(); + + return [ + ['map_string_value', 'getMapStringValue', []], + ['map_string_value', 'getMapStringValue', ['key' => $sv7]], + ['map_string_value', 'getMapStringValue', ['key' => $sv7, 'key2' => $sv8]], + ['map_string_value', 'getMapStringValue', ['key' => 'seven']], + ['map_string_value', 'getMapStringValue', ['key' => 7]], + ['map_string_value', 'getMapStringValue', ['key' => 7.7]], + ['map_string_value', 'getMapStringValue', ['key' => 'seven', 'key2' => 'eight']], + ['map_string_value', 'getMapStringValue', ['key' => $sv7, 'key2' => 'eight']], + ['map_string_value', 'getMapStringValue', ['key' => 'seven', 'key2' => $sv8]], + ['map_string_value', 'getMapStringValue', $mapField], + ]; + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/php/tests/proto/test_import_descriptor_proto.proto b/tools/go-generator/cmd/generator/_protobuf/php/tests/proto/test_import_descriptor_proto.proto new file mode 100644 index 0000000..b061601 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/tests/proto/test_import_descriptor_proto.proto @@ -0,0 +1,16 @@ +syntax = "proto3"; + +package foo; + +import "google/protobuf/descriptor.proto"; + +message TestImportDescriptorProto { + extend google.protobuf.MethodOptions { + int32 a = 72295727; + } +} + +extend google.protobuf.MethodOptions { + int32 a = 72295728; +} + diff --git a/tools/go-generator/cmd/generator/_protobuf/php/tests/proto/test_php_namespace.proto b/tools/go-generator/cmd/generator/_protobuf/php/tests/proto/test_php_namespace.proto new file mode 100644 index 0000000..61085bf --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/tests/proto/test_php_namespace.proto @@ -0,0 +1,31 @@ +syntax = "proto3"; + +package foo; +option php_namespace = "Php\\Test"; +option php_metadata_namespace = "Metadata\\Php\\Test"; + +message TestNamespace { + int32 a = 1; + + // Test nested messages, enums, and reserved names + NestedMessage nested_message = 2; + NestedEnum nested_enum = 3; + Empty reserved_name = 4; + message NestedMessage { + int32 a = 1; + } + enum NestedEnum { + ZERO = 0; + }; + // Test reserved name + message Empty { + NestedMessage nested_message = 1; + NestedEnum nested_enum = 2; + message NestedMessage { + int32 a = 1; + } + enum NestedEnum { + ZERO = 0; + }; + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/php/tests/proto/test_reserved_message_upper.proto b/tools/go-generator/cmd/generator/_protobuf/php/tests/proto/test_reserved_message_upper.proto new file mode 100644 index 0000000..853a17d --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/tests/proto/test_reserved_message_upper.proto @@ -0,0 +1,81 @@ +syntax = "proto3"; + +package upper; + +message ABSTRACT {} +message AND {} +message ARRAY {} +message AS {} +message BREAK {} +message CALLABLE {} +message CASE {} +message CATCH {} +message CLASS {} +message CLONE {} +message CONST {} +message CONTINUE {} +message DECLARE {} +message DEFAULT {} +message DIE {} +message DO {} +message ECHO {} +message ELSE {} +message ELSEIF {} +message EMPTY {} +message ENDDECLARE {} +message ENDFOR {} +message ENDFOREACH {} +message ENDIF {} +message ENDSWITCH {} +message ENDWHILE {} +message EVAL {} +message EXIT {} +message EXTENDS {} +message FINAL {} +message FINALLY {} +message FN {} +message FOR {} +message FOREACH {} +message FUNCTION {} +message GLOBAL {} +message GOTO {} +message IF {} +message IMPLEMENTS {} +message INCLUDE {} +message INCLUDE_ONCE {} +message INSTANCEOF {} +message INSTEADOF {} +message INTERFACE {} +message ISSET {} +message LIST {} +message MATCH {} +message NAMESPACE {} +message NEW {} +message OR {} +message PRINT {} +message PRIVATE {} +message PROTECTED {} +message PUBLIC {} +message REQUIRE {} +message REQUIRE_ONCE {} +message RETURN {} +message STATIC {} +message SWITCH {} +message THROW {} +message TRAIT {} +message TRY {} +message UNSET {} +message USE {} +message VAR {} +message WHILE {} +message XOR {} +message YIELD {} +message INT {} +message FLOAT {} +message BOOL {} +message STRING {} +message TRUE {} +message FALSE {} +message NULL {} +message VOID {} +message ITERABLE {} diff --git a/tools/go-generator/cmd/generator/_protobuf/php/tests/test_base.php b/tools/go-generator/cmd/generator/_protobuf/php/tests/test_base.php new file mode 100644 index 0000000..db884a8 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/php/tests/test_base.php @@ -0,0 +1,367 @@ +assertSame(-42, $m->getOptionalInt32()); + $this->assertSame(42, $m->getOptionalUint32()); + $this->assertSame(-44, $m->getOptionalSint32()); + $this->assertSame(46, $m->getOptionalFixed32()); + $this->assertSame(-46, $m->getOptionalSfixed32()); + $this->assertSame(1.5, $m->getOptionalFloat()); + $this->assertSame(1.6, $m->getOptionalDouble()); + $this->assertSame(true, $m->getOptionalBool()); + $this->assertSame('a', $m->getOptionalString()); + $this->assertSame('bbbb', $m->getOptionalBytes()); + $this->assertSame(TestEnum::ONE, $m->getOptionalEnum()); + $this->assertSame(33, $m->getOptionalMessage()->getA()); + if (PHP_INT_SIZE == 4) { + $this->assertSame('-43', $m->getOptionalInt64()); + $this->assertSame('43', $m->getOptionalUint64()); + $this->assertSame('-45', $m->getOptionalSint64()); + $this->assertSame('47', $m->getOptionalFixed64()); + $this->assertSame('-47', $m->getOptionalSfixed64()); + } else { + $this->assertSame(-43, $m->getOptionalInt64()); + $this->assertSame(43, $m->getOptionalUint64()); + $this->assertSame(-45, $m->getOptionalSint64()); + $this->assertSame(47, $m->getOptionalFixed64()); + $this->assertSame(-47, $m->getOptionalSfixed64()); + } + + $this->assertEquals(-42, $m->getRepeatedInt32()[0]); + $this->assertEquals(42, $m->getRepeatedUint32()[0]); + $this->assertEquals(-43, $m->getRepeatedInt64()[0]); + $this->assertEquals(43, $m->getRepeatedUint64()[0]); + $this->assertEquals(-44, $m->getRepeatedSint32()[0]); + $this->assertEquals(-45, $m->getRepeatedSint64()[0]); + $this->assertEquals(46, $m->getRepeatedFixed32()[0]); + $this->assertEquals(47, $m->getRepeatedFixed64()[0]); + $this->assertEquals(-46, $m->getRepeatedSfixed32()[0]); + $this->assertEquals(-47, $m->getRepeatedSfixed64()[0]); + $this->assertEquals(1.5, $m->getRepeatedFloat()[0]); + $this->assertEquals(1.6, $m->getRepeatedDouble()[0]); + $this->assertEquals(true, $m->getRepeatedBool()[0]); + $this->assertEquals('a', $m->getRepeatedString()[0]); + $this->assertEquals('bbbb', $m->getRepeatedBytes()[0]); + $this->assertEquals(34, $m->getRepeatedMessage()[0]->GetA()); + + $this->assertEquals(-52, $m->getRepeatedInt32()[1]); + $this->assertEquals(52, $m->getRepeatedUint32()[1]); + $this->assertEquals(-53, $m->getRepeatedInt64()[1]); + $this->assertEquals(53, $m->getRepeatedUint64()[1]); + $this->assertEquals(-54, $m->getRepeatedSint32()[1]); + $this->assertEquals(-55, $m->getRepeatedSint64()[1]); + $this->assertEquals(56, $m->getRepeatedFixed32()[1]); + $this->assertEquals(57, $m->getRepeatedFixed64()[1]); + $this->assertEquals(-56, $m->getRepeatedSfixed32()[1]); + $this->assertEquals(-57, $m->getRepeatedSfixed64()[1]); + $this->assertEquals(2.5, $m->getRepeatedFloat()[1]); + $this->assertEquals(2.6, $m->getRepeatedDouble()[1]); + $this->assertEquals(false, $m->getRepeatedBool()[1]); + $this->assertEquals('c', $m->getRepeatedString()[1]); + $this->assertEquals('dddd', $m->getRepeatedBytes()[1]); + $this->assertEquals(35, $m->getRepeatedMessage()[1]->GetA()); + + if (PHP_INT_SIZE == 4) { + $this->assertEquals('-63', $m->getMapInt64Int64()['-63']); + $this->assertEquals('63', $m->getMapUint64Uint64()['63']); + $this->assertEquals('-65', $m->getMapSint64Sint64()['-65']); + $this->assertEquals('67', $m->getMapFixed64Fixed64()['67']); + $this->assertEquals('-69', $m->getMapSfixed64Sfixed64()['-69']); + } else { + $this->assertEquals(-63, $m->getMapInt64Int64()[-63]); + $this->assertEquals(63, $m->getMapUint64Uint64()[63]); + $this->assertEquals(-65, $m->getMapSint64Sint64()[-65]); + $this->assertEquals(67, $m->getMapFixed64Fixed64()[67]); + $this->assertEquals(-69, $m->getMapSfixed64Sfixed64()[-69]); + } + $this->assertEquals(-62, $m->getMapInt32Int32()[-62]); + $this->assertEquals(62, $m->getMapUint32Uint32()[62]); + $this->assertEquals(-64, $m->getMapSint32Sint32()[-64]); + $this->assertEquals(66, $m->getMapFixed32Fixed32()[66]); + $this->assertEquals(-68, $m->getMapSfixed32Sfixed32()[-68]); + $this->assertEquals(3.5, $m->getMapInt32Float()[1]); + $this->assertEquals(3.6, $m->getMapInt32Double()[1]); + $this->assertEquals(true , $m->getMapBoolBool()[true]); + $this->assertEquals('e', $m->getMapStringString()['e']); + $this->assertEquals('ffff', $m->getMapInt32Bytes()[1]); + $this->assertEquals(TestEnum::ONE, $m->getMapInt32Enum()[1]); + $this->assertEquals(36, $m->getMapInt32Message()[1]->GetA()); + } + + // Test message merged from setFields and setFields2. + public function expectFieldsMerged(TestMessage $m) + { + $this->assertSame(-144, $m->getOptionalSint32()); + $this->assertSame(146, $m->getOptionalFixed32()); + $this->assertSame(-146, $m->getOptionalSfixed32()); + $this->assertSame(11.5, $m->getOptionalFloat()); + $this->assertSame(11.6, $m->getOptionalDouble()); + $this->assertSame(true, $m->getOptionalBool()); + $this->assertSame('aa', $m->getOptionalString()); + $this->assertSame('bb', $m->getOptionalBytes()); + $this->assertSame(133, $m->getOptionalMessage()->getA()); + if (PHP_INT_SIZE == 4) { + $this->assertSame('-143', $m->getOptionalInt64()); + $this->assertSame('143', $m->getOptionalUint64()); + $this->assertSame('-145', $m->getOptionalSint64()); + $this->assertSame('147', $m->getOptionalFixed64()); + $this->assertSame('-147', $m->getOptionalSfixed64()); + } else { + $this->assertSame(-143, $m->getOptionalInt64()); + $this->assertSame(143, $m->getOptionalUint64()); + $this->assertSame(-145, $m->getOptionalSint64()); + $this->assertSame(147, $m->getOptionalFixed64()); + $this->assertSame(-147, $m->getOptionalSfixed64()); + } + + $this->assertEquals(-42, $m->getRepeatedInt32()[0]); + $this->assertEquals(42, $m->getRepeatedUint32()[0]); + $this->assertEquals(-43, $m->getRepeatedInt64()[0]); + $this->assertEquals(43, $m->getRepeatedUint64()[0]); + $this->assertEquals(-44, $m->getRepeatedSint32()[0]); + $this->assertEquals(-45, $m->getRepeatedSint64()[0]); + $this->assertEquals(46, $m->getRepeatedFixed32()[0]); + $this->assertEquals(47, $m->getRepeatedFixed64()[0]); + $this->assertEquals(-46, $m->getRepeatedSfixed32()[0]); + $this->assertEquals(-47, $m->getRepeatedSfixed64()[0]); + $this->assertEquals(1.5, $m->getRepeatedFloat()[0]); + $this->assertEquals(1.6, $m->getRepeatedDouble()[0]); + $this->assertEquals(true, $m->getRepeatedBool()[0]); + $this->assertEquals('a', $m->getRepeatedString()[0]); + $this->assertEquals('bbbb', $m->getRepeatedBytes()[0]); + $this->assertEquals(TestEnum::ZERO, $m->getRepeatedEnum()[0]); + $this->assertEquals(34, $m->getRepeatedMessage()[0]->GetA()); + + $this->assertEquals(-52, $m->getRepeatedInt32()[1]); + $this->assertEquals(52, $m->getRepeatedUint32()[1]); + $this->assertEquals(-53, $m->getRepeatedInt64()[1]); + $this->assertEquals(53, $m->getRepeatedUint64()[1]); + $this->assertEquals(-54, $m->getRepeatedSint32()[1]); + $this->assertEquals(-55, $m->getRepeatedSint64()[1]); + $this->assertEquals(56, $m->getRepeatedFixed32()[1]); + $this->assertEquals(57, $m->getRepeatedFixed64()[1]); + $this->assertEquals(-56, $m->getRepeatedSfixed32()[1]); + $this->assertEquals(-57, $m->getRepeatedSfixed64()[1]); + $this->assertEquals(2.5, $m->getRepeatedFloat()[1]); + $this->assertEquals(2.6, $m->getRepeatedDouble()[1]); + $this->assertEquals(false, $m->getRepeatedBool()[1]); + $this->assertEquals('c', $m->getRepeatedString()[1]); + $this->assertEquals('dddd', $m->getRepeatedBytes()[1]); + $this->assertEquals(TestEnum::ONE, $m->getRepeatedEnum()[1]); + $this->assertEquals(35, $m->getRepeatedMessage()[1]->GetA()); + + $this->assertEquals(-142, $m->getRepeatedInt32()[2]); + $this->assertEquals(142, $m->getRepeatedUint32()[2]); + $this->assertEquals(-143, $m->getRepeatedInt64()[2]); + $this->assertEquals(143, $m->getRepeatedUint64()[2]); + $this->assertEquals(-144, $m->getRepeatedSint32()[2]); + $this->assertEquals(-145, $m->getRepeatedSint64()[2]); + $this->assertEquals(146, $m->getRepeatedFixed32()[2]); + $this->assertEquals(147, $m->getRepeatedFixed64()[2]); + $this->assertEquals(-146, $m->getRepeatedSfixed32()[2]); + $this->assertEquals(-147, $m->getRepeatedSfixed64()[2]); + $this->assertEquals(11.5, $m->getRepeatedFloat()[2]); + $this->assertEquals(11.6, $m->getRepeatedDouble()[2]); + $this->assertEquals(false, $m->getRepeatedBool()[2]); + $this->assertEquals('aa', $m->getRepeatedString()[2]); + $this->assertEquals('bb', $m->getRepeatedBytes()[2]); + $this->assertEquals(TestEnum::TWO, $m->getRepeatedEnum()[2]); + $this->assertEquals(134, $m->getRepeatedMessage()[2]->GetA()); + + if (PHP_INT_SIZE == 4) { + $this->assertEquals('-163', $m->getMapInt64Int64()['-63']); + $this->assertEquals('163', $m->getMapUint64Uint64()['63']); + $this->assertEquals('-165', $m->getMapSint64Sint64()['-65']); + $this->assertEquals('167', $m->getMapFixed64Fixed64()['67']); + $this->assertEquals('-169', $m->getMapSfixed64Sfixed64()['-69']); + } else { + $this->assertEquals(-163, $m->getMapInt64Int64()[-63]); + $this->assertEquals(163, $m->getMapUint64Uint64()[63]); + $this->assertEquals(-165, $m->getMapSint64Sint64()[-65]); + $this->assertEquals(167, $m->getMapFixed64Fixed64()[67]); + $this->assertEquals(-169, $m->getMapSfixed64Sfixed64()[-69]); + } + $this->assertEquals(-162, $m->getMapInt32Int32()[-62]); + $this->assertEquals(162, $m->getMapUint32Uint32()[62]); + $this->assertEquals(-164, $m->getMapSint32Sint32()[-64]); + $this->assertEquals(166, $m->getMapFixed32Fixed32()[66]); + $this->assertEquals(-168, $m->getMapSfixed32Sfixed32()[-68]); + $this->assertEquals(13.5, $m->getMapInt32Float()[1]); + $this->assertEquals(13.6, $m->getMapInt32Double()[1]); + $this->assertEquals(false , $m->getMapBoolBool()[true]); + $this->assertEquals('ee', $m->getMapStringString()['e']); + $this->assertEquals('ff', $m->getMapInt32Bytes()[1]); + $this->assertEquals(TestEnum::TWO, $m->getMapInt32Enum()[1]); + $this->assertEquals(136, $m->getMapInt32Message()[1]->GetA()); + + if (PHP_INT_SIZE == 4) { + $this->assertEquals('-163', $m->getMapInt64Int64()['-163']); + $this->assertEquals('163', $m->getMapUint64Uint64()['163']); + $this->assertEquals('-165', $m->getMapSint64Sint64()['-165']); + $this->assertEquals('167', $m->getMapFixed64Fixed64()['167']); + $this->assertEquals('-169', $m->getMapSfixed64Sfixed64()['-169']); + } else { + $this->assertEquals(-163, $m->getMapInt64Int64()[-163]); + $this->assertEquals(163, $m->getMapUint64Uint64()[163]); + $this->assertEquals(-165, $m->getMapSint64Sint64()[-165]); + $this->assertEquals(167, $m->getMapFixed64Fixed64()[167]); + $this->assertEquals(-169, $m->getMapSfixed64Sfixed64()[-169]); + } + $this->assertEquals(-162, $m->getMapInt32Int32()[-162]); + $this->assertEquals(162, $m->getMapUint32Uint32()[162]); + $this->assertEquals(-164, $m->getMapSint32Sint32()[-164]); + $this->assertEquals(166, $m->getMapFixed32Fixed32()[166]); + $this->assertEquals(-168, $m->getMapSfixed32Sfixed32()[-168]); + $this->assertEquals(13.5, $m->getMapInt32Float()[2]); + $this->assertEquals(13.6, $m->getMapInt32Double()[2]); + $this->assertEquals(false , $m->getMapBoolBool()[false]); + $this->assertEquals('ee', $m->getMapStringString()['ee']); + $this->assertEquals('ff', $m->getMapInt32Bytes()[2]); + $this->assertEquals(TestEnum::TWO, $m->getMapInt32Enum()[2]); + $this->assertEquals(136, $m->getMapInt32Message()[2]->GetA()); + } + + public function expectEmptyFields(TestMessage $m) + { + $this->assertSame(0, $m->getOptionalInt32()); + $this->assertSame(0, $m->getOptionalUint32()); + $this->assertSame(0, $m->getOptionalSint32()); + $this->assertSame(0, $m->getOptionalFixed32()); + $this->assertSame(0, $m->getOptionalSfixed32()); + $this->assertSame(0.0, $m->getOptionalFloat()); + $this->assertSame(0.0, $m->getOptionalDouble()); + $this->assertSame(false, $m->getOptionalBool()); + $this->assertSame('', $m->getOptionalString()); + $this->assertSame('', $m->getOptionalBytes()); + $this->assertSame(0, $m->getOptionalEnum()); + $this->assertNull($m->getOptionalMessage()); + $this->assertNull($m->getOptionalIncludedMessage()); + $this->assertNull($m->getRecursive()); + if (PHP_INT_SIZE == 4) { + $this->assertSame("0", $m->getOptionalInt64()); + $this->assertSame("0", $m->getOptionalUint64()); + $this->assertSame("0", $m->getOptionalSint64()); + $this->assertSame("0", $m->getOptionalFixed64()); + $this->assertSame("0", $m->getOptionalSfixed64()); + } else { + $this->assertSame(0, $m->getOptionalInt64()); + $this->assertSame(0, $m->getOptionalUint64()); + $this->assertSame(0, $m->getOptionalSint64()); + $this->assertSame(0, $m->getOptionalFixed64()); + $this->assertSame(0, $m->getOptionalSfixed64()); + } + + $this->assertEquals(0, count($m->getRepeatedInt32())); + $this->assertEquals(0, count($m->getRepeatedUint32())); + $this->assertEquals(0, count($m->getRepeatedInt64())); + $this->assertEquals(0, count($m->getRepeatedUint64())); + $this->assertEquals(0, count($m->getRepeatedSint32())); + $this->assertEquals(0, count($m->getRepeatedSint64())); + $this->assertEquals(0, count($m->getRepeatedFixed32())); + $this->assertEquals(0, count($m->getRepeatedFixed64())); + $this->assertEquals(0, count($m->getRepeatedSfixed32())); + $this->assertEquals(0, count($m->getRepeatedSfixed64())); + $this->assertEquals(0, count($m->getRepeatedFloat())); + $this->assertEquals(0, count($m->getRepeatedDouble())); + $this->assertEquals(0, count($m->getRepeatedBool())); + $this->assertEquals(0, count($m->getRepeatedString())); + $this->assertEquals(0, count($m->getRepeatedBytes())); + $this->assertEquals(0, count($m->getRepeatedEnum())); + $this->assertEquals(0, count($m->getRepeatedMessage())); + $this->assertEquals(0, count($m->getRepeatedRecursive())); + + $this->assertSame("", $m->getMyOneof()); + $this->assertSame(0, $m->getOneofInt32()); + $this->assertSame(0, $m->getOneofUint32()); + $this->assertSame(0, $m->getOneofSint32()); + $this->assertSame(0, $m->getOneofFixed32()); + $this->assertSame(0, $m->getOneofSfixed32()); + $this->assertSame(0.0, $m->getOneofFloat()); + $this->assertSame(0.0, $m->getOneofDouble()); + $this->assertSame(false, $m->getOneofBool()); + $this->assertSame('', $m->getOneofString()); + $this->assertSame('', $m->getOneofBytes()); + $this->assertSame(0, $m->getOneofEnum()); + $this->assertNull($m->getOptionalMessage()); + if (PHP_INT_SIZE == 4) { + $this->assertSame("0", $m->getOneofInt64()); + $this->assertSame("0", $m->getOneofUint64()); + $this->assertSame("0", $m->getOneofSint64()); + $this->assertSame("0", $m->getOneofFixed64()); + $this->assertSame("0", $m->getOneofSfixed64()); + } else { + $this->assertSame(0, $m->getOneofInt64()); + $this->assertSame(0, $m->getOneofUint64()); + $this->assertSame(0, $m->getOneofSint64()); + $this->assertSame(0, $m->getOneofFixed64()); + $this->assertSame(0, $m->getOneofSfixed64()); + } + + $this->assertEquals(0, count($m->getMapInt64Int64())); + $this->assertEquals(0, count($m->getMapUint64Uint64())); + $this->assertEquals(0, count($m->getMapSint64Sint64())); + $this->assertEquals(0, count($m->getMapFixed64Fixed64())); + $this->assertEquals(0, count($m->getMapInt32Int32())); + $this->assertEquals(0, count($m->getMapUint32Uint32())); + $this->assertEquals(0, count($m->getMapSint32Sint32())); + $this->assertEquals(0, count($m->getMapFixed32Fixed32())); + $this->assertEquals(0, count($m->getMapSfixed32Sfixed32())); + $this->assertEquals(0, count($m->getMapSfixed64Sfixed64())); + $this->assertEquals(0, count($m->getMapInt32Float())); + $this->assertEquals(0, count($m->getMapInt32Double())); + $this->assertEquals(0, count($m->getMapBoolBool())); + $this->assertEquals(0, count($m->getMapStringString())); + $this->assertEquals(0, count($m->getMapInt32Bytes())); + $this->assertEquals(0, count($m->getMapInt32Enum())); + $this->assertEquals(0, count($m->getMapInt32Message())); + $this->assertEquals(0, count($m->getMapRecursive())); + } + + // This test is to avoid the warning of no test by php unit. + public function testNone() + { + $this->assertTrue(true); + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/protobuf.pc.in b/tools/go-generator/cmd/generator/_protobuf/protobuf.pc.in new file mode 100644 index 0000000..e9bef5d --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/protobuf.pc.in @@ -0,0 +1,13 @@ +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +includedir=@includedir@ + +Name: Protocol Buffers +Description: Google's Data Interchange Format +Version: @VERSION@ +Libs: -L${libdir} -lprotobuf +Libs.private: @LIBS@ + +Cflags: -I${includedir} +Conflicts: protobuf-lite diff --git a/tools/go-generator/cmd/generator/_protobuf/protobuf_deps.bzl b/tools/go-generator/cmd/generator/_protobuf/protobuf_deps.bzl new file mode 100644 index 0000000..7e2caa3 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/protobuf_deps.bzl @@ -0,0 +1,93 @@ +"""Load dependencies needed to compile the protobuf library as a 3rd-party consumer.""" + +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") + +PROTOBUF_MAVEN_ARTIFACTS = [ + "com.google.code.findbugs:jsr305:3.0.2", + "com.google.code.gson:gson:2.8.9", + "com.google.errorprone:error_prone_annotations:2.3.2", + "com.google.j2objc:j2objc-annotations:1.3", + "com.google.guava:guava:30.1.1-jre", + "com.google.guava:guava-testlib:30.1.1-jre", + "com.google.truth:truth:1.1.2", + "junit:junit:4.12", + "org.easymock:easymock:3.2", +] + +def protobuf_deps(): + """Loads common dependencies needed to compile the protobuf library.""" + + if not native.existing_rule("bazel_skylib"): + http_archive( + name = "bazel_skylib", + sha256 = "97e70364e9249702246c0e9444bccdc4b847bed1eb03c5a3ece4f83dfe6abc44", + urls = [ + "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.0.2/bazel-skylib-1.0.2.tar.gz", + "https://github.com/bazelbuild/bazel-skylib/releases/download/1.0.2/bazel-skylib-1.0.2.tar.gz", + ], + ) + + if not native.existing_rule("zlib"): + http_archive( + name = "zlib", + build_file = Label("//:third_party/zlib.BUILD"), + sha256 = "629380c90a77b964d896ed37163f5c3a34f6e6d897311f1df2a7016355c45eff", + strip_prefix = "zlib-1.2.11", + urls = ["https://github.com/madler/zlib/archive/v1.2.11.tar.gz"], + ) + + if not native.existing_rule("rules_cc"): + http_archive( + name = "rules_cc", + sha256 = "9d48151ea71b3e225adfb6867e6d2c7d0dce46cbdc8710d9a9a628574dfd40a0", + strip_prefix = "rules_cc-818289e5613731ae410efb54218a4077fb9dbb03", + urls = ["https://github.com/bazelbuild/rules_cc/archive/818289e5613731ae410efb54218a4077fb9dbb03.tar.gz"], + ) + + if not native.existing_rule("rules_java"): + http_archive( + name = "rules_java", + sha256 = "f5a3e477e579231fca27bf202bb0e8fbe4fc6339d63b38ccb87c2760b533d1c3", + strip_prefix = "rules_java-981f06c3d2bd10225e85209904090eb7b5fb26bd", + urls = ["https://github.com/bazelbuild/rules_java/archive/981f06c3d2bd10225e85209904090eb7b5fb26bd.tar.gz"], + ) + + if not native.existing_rule("rules_proto"): + http_archive( + name = "rules_proto", + sha256 = "a4382f78723af788f0bc19fd4c8411f44ffe0a72723670a34692ffad56ada3ac", + strip_prefix = "rules_proto-f7a30f6f80006b591fa7c437fe5a951eb10bcbcf", + urls = ["https://github.com/bazelbuild/rules_proto/archive/f7a30f6f80006b591fa7c437fe5a951eb10bcbcf.zip"], + ) + + if not native.existing_rule("rules_python"): + http_archive( + name = "rules_python", + sha256 = "b6d46438523a3ec0f3cead544190ee13223a52f6a6765a29eae7b7cc24cc83a0", + urls = ["https://github.com/bazelbuild/rules_python/releases/download/0.1.0/rules_python-0.1.0.tar.gz"], + ) + + if not native.existing_rule("rules_jvm_external"): + http_archive( + name = "rules_jvm_external", + sha256 = "f36441aa876c4f6427bfb2d1f2d723b48e9d930b62662bf723ddfb8fc80f0140", + strip_prefix = "rules_jvm_external-4.1", + urls = ["https://github.com/bazelbuild/rules_jvm_external/archive/4.1.zip"], + ) + + if not native.existing_rule("rules_pkg"): + http_archive( + name = "rules_pkg", + urls = [ + "https://mirror.bazel.build/github.com/bazelbuild/rules_pkg/releases/download/0.5.1/rules_pkg-0.5.1.tar.gz", + "https://github.com/bazelbuild/rules_pkg/releases/download/0.5.1/rules_pkg-0.5.1.tar.gz", + ], + sha256 = "a89e203d3cf264e564fcb96b6e06dd70bc0557356eb48400ce4b5d97c2c3720d", + ) + + if not native.existing_rule("io_bazel_rules_kotlin"): + http_archive( + name = "io_bazel_rules_kotlin", + urls = ["https://github.com/bazelbuild/rules_kotlin/releases/download/v1.5.0-beta-4/rules_kotlin_release.tgz"], + sha256 = "6cbd4e5768bdfae1598662e40272729ec9ece8b7bded8f0d2c81c8ff96dc139d", + ) diff --git a/tools/go-generator/cmd/generator/_protobuf/python/docs/conf.py b/tools/go-generator/cmd/generator/_protobuf/python/docs/conf.py new file mode 100644 index 0000000..913f012 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/python/docs/conf.py @@ -0,0 +1,254 @@ +# -*- coding: utf-8 -*- +# Protocol Buffers - Google's data interchange format +# Copyright 2019 Google LLC. 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. + +# Configuration file for the Sphinx documentation builder. +# +# This file does only contain a selection of the most common options. For a +# full list see the documentation: +# http://www.sphinx-doc.org/en/master/config + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +import os +# import sys +# sys.path.insert(0, os.path.abspath('.')) +import google.protobuf + +# -- Project information ----------------------------------------------------- + +project = u"Protocol Buffers" +copyright = u"2008, Google LLC" +author = u"Google LLC" + +# The short X.Y version +version = u"" +# The full version, including alpha/beta/rc tags +release = google.protobuf.__version__ + + +# -- General configuration --------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autosummary", + "sphinx.ext.ifconfig", + "sphinx.ext.intersphinx", + "sphinx.ext.napoleon", +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = ".rst" + +# The master toctree document. +master_doc = "index" + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = [u"_build", "Thumbs.db", ".DS_Store"] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = None + + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = "alabaster" + +# Remove JavaScript. +html_js_files = [] + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +html_show_sourcelink = True + +# Custom sidebar templates, must be a dictionary that maps document names +# to template names. +# +# The default sidebars (for documents that don't match any pattern) are +# defined by theme itself. Builtin themes are using these templates by +# default: ``['localtoc.html', 'relations.html', 'sourcelink.html', +# 'searchbox.html']``. + +# Remove searchbox.html to avoid embedded JavaScript. +html_sidebars = { + "**": [ + "globaltoc.html", "localtoc.html", "relations.html", "sourcelink.html", + ], +} + + +# -- Options for HTMLHelp output --------------------------------------------- + +# Output file base name for HTML help builder. +htmlhelp_basename = "ProtocolBuffersdoc" + + +# -- Options for LaTeX output ------------------------------------------------ + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + master_doc, + "ProtocolBuffers.tex", + "Protocol Buffers Documentation", + "Google LLC", + "manual", + ) +] + + +# -- Options for manual page output ------------------------------------------ + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + master_doc, # source start file + "protocolbuffers", # name + "Protocol Buffers Documentation", # description + [author], # authors + 1, # manual section + ) +] + + +# -- Options for Texinfo output ---------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "ProtocolBuffers", + u"Protocol Buffers Documentation", + author, + "ProtocolBuffers", + "One line description of project.", + "Miscellaneous", + ) +] + + +# -- Options for Epub output ------------------------------------------------- + +# Bibliographic Dublin Core info. +epub_title = project + +# The unique identifier of the text. This can be a ISBN number +# or the project homepage. +# +# epub_identifier = '' + +# A unique identification for the text. +# +# epub_uid = '' + +# A list of files that should not be packed into the epub file. +epub_exclude_files = ["search.html"] + + +# -- Extension configuration ------------------------------------------------- + +# -- Options for autosummary extension --------------------------------------- +autosummary_generate = True + +# -- Options for intersphinx extension --------------------------------------- + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = {"https://docs.python.org/": None} + +# -- Config values ----------------------------------------------------------- +# The setup() function is needed to add configuration values to the Sphinx +# builder. We use this to show a banner when built on Read the Docs. +# https://www.sphinx-doc.org/en/master/usage/extensions/ifconfig.html + +def setup(app): + app.add_config_value( + "build_env", + # Read the Docs sets a READTHEDOCS environment during builds. + # https://docs.readthedocs.io/en/stable/builds.html#build-environment + "readthedocs" if os.getenv("READTHEDOCS") else "", + "env" + ) diff --git a/tools/go-generator/cmd/generator/_protobuf/python/docs/generate_docs.py b/tools/go-generator/cmd/generator/_protobuf/python/docs/generate_docs.py new file mode 100755 index 0000000..e024aaa --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/python/docs/generate_docs.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python +# 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. + +"""Script to generate a list of all modules to use in autosummary. + +This script creates a ReStructured Text file for each public module in the +protobuf Python package. The script also updates the table of contents in +``docs/index.rst`` to point to these module references. + +To build the docs with Sphinx: + +1. Install the needed packages (``sphinx``, ``sphinxcontrib-napoleon`` for + Google-style docstring support). I've created a conda environment file to + make this easier: + +.. code:: bash + + conda env create -f python/docs/environment.yml + +2. (Optional) Generate reference docs files and regenerate index: + +.. code:: bash + + cd python/docs + python generate_docs.py + +3. Run Sphinx. + +.. code:: bash + + make html +""" + +import pathlib +import re + + +DOCS_DIR = pathlib.Path(__file__).parent.resolve() +PYTHON_DIR = DOCS_DIR.parent +SOURCE_DIR = PYTHON_DIR / "google" / "protobuf" +SOURCE_POSIX = SOURCE_DIR.as_posix() + +# Modules which are always included: +INCLUDED_MODULES = ( + "google.protobuf.internal.containers", +) + +# Packages to ignore, including all modules (unless in INCLUDED_MODULES): +IGNORED_PACKAGES = ( + "compiler", + "docs", + "internal", + "pyext", + "util", +) + +# Ignored module stems in all packages (unless in INCLUDED_MODULES): +IGNORED_MODULES = ( + "any_test_pb2", + "api_pb2", + "unittest", + "source_context_pb2", + "test_messages_proto3_pb2", + "test_messages_proto2", +) + +TOC_REGEX = re.compile( + r"\.\. START REFTOC.*\.\. END REFTOC\.\n", + flags=re.DOTALL, +) +TOC_TEMPLATE = """.. START REFTOC, generated by generate_docs.py. +.. toctree:: + + {toctree} + +.. END REFTOC. +""" + +AUTOMODULE_TEMPLATE = """.. DO NOT EDIT, generated by generate_docs.py. + +.. ifconfig:: build_env == 'readthedocs' + + .. warning:: + + You are reading the documentation for the `latest committed changes + `_ of + the `Protocol Buffers package for Python + `_. + Some features may not yet be released. Read the documentation for the + latest released package at `googleapis.dev + `_. + +{module} +{underline} + +.. automodule:: {module} + :members: + :inherited-members: + :undoc-members: +""" + + +def find_modules(): + modules = [] + for module_path in SOURCE_DIR.glob("**/*.py"): + # Determine the (dotted) relative package and module names. + package_path = module_path.parent.relative_to(PYTHON_DIR) + if package_path == SOURCE_DIR: + package_name = "" + module_name = module_path.stem + else: + package_name = package_path.as_posix().replace("/", ".") + module_name = package_name + "." + module_path.stem + + # Filter: first, accept anything in the whitelist; then, reject anything + # at package level, then module name level. + if any(include == module_name for include in INCLUDED_MODULES): + pass + elif any(ignored in package_name for ignored in IGNORED_PACKAGES): + continue + elif any(ignored in module_path.stem for ignored in IGNORED_MODULES): + continue + + if module_path.name == "__init__.py": + modules.append(package_name) + else: + modules.append(module_name) + + return modules + + +def write_automodule(module): + contents = AUTOMODULE_TEMPLATE.format(module=module, underline="=" * len(module),) + automodule_path = DOCS_DIR.joinpath(*module.split(".")).with_suffix(".rst") + try: + automodule_path.parent.mkdir(parents=True) + except FileExistsError: + pass + with open(automodule_path, "w") as automodule_file: + automodule_file.write(contents) + + +def replace_toc(modules): + toctree = [module.replace(".", "/") for module in modules] + with open(DOCS_DIR / "index.rst", "r") as index_file: + index_contents = index_file.read() + toc = TOC_TEMPLATE.format( + toctree="\n ".join(toctree) + ) + index_contents = re.sub(TOC_REGEX, toc, index_contents) + with open(DOCS_DIR / "index.rst", "w") as index_file: + index_file.write(index_contents) + + +def main(): + modules = list(sorted(find_modules())) + for module in modules: + print("Generating reference for {}".format(module)) + write_automodule(module) + print("Generating index.rst") + replace_toc(modules) + +if __name__ == "__main__": + main() diff --git a/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/internal/factory_test2.proto b/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/internal/factory_test2.proto new file mode 100644 index 0000000..5fcbc5a --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/internal/factory_test2.proto @@ -0,0 +1,104 @@ +// 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: matthewtoia@google.com (Matt Toia) + +syntax = "proto2"; + +package google.protobuf.python.internal; + +import "google/protobuf/internal/factory_test1.proto"; + + +enum Factory2Enum { + FACTORY_2_VALUE_0 = 0; + FACTORY_2_VALUE_1 = 1; +} + +message Factory2Message { + required int32 mandatory = 1; + optional Factory2Enum factory_2_enum = 2; + enum NestedFactory2Enum { + NESTED_FACTORY_2_VALUE_0 = 0; + NESTED_FACTORY_2_VALUE_1 = 1; + } + optional NestedFactory2Enum nested_factory_2_enum = 3; + message NestedFactory2Message { + optional string value = 1; + } + optional NestedFactory2Message nested_factory_2_message = 4; + optional Factory1Message factory_1_message = 5; + optional Factory1Enum factory_1_enum = 6; + optional Factory1Message.NestedFactory1Enum nested_factory_1_enum = 7; + optional Factory1Message.NestedFactory1Message nested_factory_1_message = 8; + optional Factory2Message circular_message = 9; + optional string scalar_value = 10; + repeated string list_value = 11; + repeated group Grouped = 12 { + optional string part_1 = 13; + optional string part_2 = 14; + } + optional LoopMessage loop = 15; + optional int32 int_with_default = 16 [default = 1776]; + optional double double_with_default = 17 [default = 9.99]; + optional string string_with_default = 18 [default = "hello world"]; + optional bool bool_with_default = 19 [default = false]; + optional Factory2Enum enum_with_default = 20 [default = FACTORY_2_VALUE_1]; + optional bytes bytes_with_default = 21 [default = "a\373\000c"]; + + + extend Factory1Message { + optional string one_more_field = 1001; + } + + oneof oneof_field { + int32 oneof_int = 22; + string oneof_string = 23; + } +} + +message LoopMessage { + optional Factory2Message loop = 1; +} + +message MessageWithNestedEnumOnly { + enum NestedEnum { + NESTED_MESSAGE_ENUM_0 = 0; + } +} + +extend Factory1Message { + optional string another_field = 1002; +} + +message MessageWithOption { + option no_standard_descriptor_accessor = true; + optional int32 field1 = 1; +} diff --git a/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/internal/import_test_package/__init__.py b/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/internal/import_test_package/__init__.py new file mode 100644 index 0000000..5121dd0 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/internal/import_test_package/__init__.py @@ -0,0 +1,33 @@ +# 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. + +"""Sample module importing a nested proto from itself.""" + +from google.protobuf.internal.import_test_package import outer_pb2 as myproto diff --git a/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/internal/json_format_test.py b/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/internal/json_format_test.py new file mode 100644 index 0000000..092dfdb --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/internal/json_format_test.py @@ -0,0 +1,1276 @@ +# 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. + +"""Test for google.protobuf.json_format.""" + +__author__ = 'jieluo@google.com (Jie Luo)' + +import json +import math +import struct + +import unittest + +from google.protobuf import any_pb2 +from google.protobuf import duration_pb2 +from google.protobuf import field_mask_pb2 +from google.protobuf import struct_pb2 +from google.protobuf import timestamp_pb2 +from google.protobuf import wrappers_pb2 +from google.protobuf import any_test_pb2 +from google.protobuf import unittest_mset_pb2 +from google.protobuf import unittest_pb2 +from google.protobuf.internal import test_proto3_optional_pb2 +from google.protobuf import descriptor_pool +from google.protobuf import json_format +from google.protobuf.util import json_format_pb2 +from google.protobuf.util import json_format_proto3_pb2 + + +class JsonFormatBase(unittest.TestCase): + + def FillAllFields(self, message): + message.int32_value = 20 + message.int64_value = -20 + message.uint32_value = 3120987654 + message.uint64_value = 12345678900 + message.float_value = float('-inf') + message.double_value = 3.1415 + message.bool_value = True + message.string_value = 'foo' + message.bytes_value = b'bar' + message.message_value.value = 10 + message.enum_value = json_format_proto3_pb2.BAR + # Repeated + message.repeated_int32_value.append(0x7FFFFFFF) + message.repeated_int32_value.append(-2147483648) + message.repeated_int64_value.append(9007199254740992) + message.repeated_int64_value.append(-9007199254740992) + message.repeated_uint32_value.append(0xFFFFFFF) + message.repeated_uint32_value.append(0x7FFFFFF) + message.repeated_uint64_value.append(9007199254740992) + message.repeated_uint64_value.append(9007199254740991) + message.repeated_float_value.append(0) + + message.repeated_double_value.append(1E-15) + message.repeated_double_value.append(float('inf')) + message.repeated_bool_value.append(True) + message.repeated_bool_value.append(False) + message.repeated_string_value.append('Few symbols!#$,;') + message.repeated_string_value.append('bar') + message.repeated_bytes_value.append(b'foo') + message.repeated_bytes_value.append(b'bar') + message.repeated_message_value.add().value = 10 + message.repeated_message_value.add().value = 11 + message.repeated_enum_value.append(json_format_proto3_pb2.FOO) + message.repeated_enum_value.append(json_format_proto3_pb2.BAR) + self.message = message + + def CheckParseBack(self, message, parsed_message): + json_format.Parse(json_format.MessageToJson(message), + parsed_message) + self.assertEqual(message, parsed_message) + + def CheckError(self, text, error_message): + message = json_format_proto3_pb2.TestMessage() + self.assertRaisesRegex( + json_format.ParseError, + error_message, + json_format.Parse, text, message) + + +class JsonFormatTest(JsonFormatBase): + + def testEmptyMessageToJson(self): + message = json_format_proto3_pb2.TestMessage() + self.assertEqual(json_format.MessageToJson(message), + '{}') + parsed_message = json_format_proto3_pb2.TestMessage() + self.CheckParseBack(message, parsed_message) + + def testPartialMessageToJson(self): + message = json_format_proto3_pb2.TestMessage( + string_value='test', + repeated_int32_value=[89, 4]) + self.assertEqual(json.loads(json_format.MessageToJson(message)), + json.loads('{"stringValue": "test", ' + '"repeatedInt32Value": [89, 4]}')) + parsed_message = json_format_proto3_pb2.TestMessage() + self.CheckParseBack(message, parsed_message) + + def testAllFieldsToJson(self): + message = json_format_proto3_pb2.TestMessage() + text = ('{"int32Value": 20, ' + '"int64Value": "-20", ' + '"uint32Value": 3120987654,' + '"uint64Value": "12345678900",' + '"floatValue": "-Infinity",' + '"doubleValue": 3.1415,' + '"boolValue": true,' + '"stringValue": "foo",' + '"bytesValue": "YmFy",' + '"messageValue": {"value": 10},' + '"enumValue": "BAR",' + '"repeatedInt32Value": [2147483647, -2147483648],' + '"repeatedInt64Value": ["9007199254740992", "-9007199254740992"],' + '"repeatedUint32Value": [268435455, 134217727],' + '"repeatedUint64Value": ["9007199254740992", "9007199254740991"],' + '"repeatedFloatValue": [0],' + '"repeatedDoubleValue": [1e-15, "Infinity"],' + '"repeatedBoolValue": [true, false],' + '"repeatedStringValue": ["Few symbols!#$,;", "bar"],' + '"repeatedBytesValue": ["Zm9v", "YmFy"],' + '"repeatedMessageValue": [{"value": 10}, {"value": 11}],' + '"repeatedEnumValue": ["FOO", "BAR"]' + '}') + self.FillAllFields(message) + self.assertEqual( + json.loads(json_format.MessageToJson(message)), + json.loads(text)) + parsed_message = json_format_proto3_pb2.TestMessage() + json_format.Parse(text, parsed_message) + self.assertEqual(message, parsed_message) + + def testUnknownEnumToJsonAndBack(self): + text = '{\n "enumValue": 999\n}' + message = json_format_proto3_pb2.TestMessage() + message.enum_value = 999 + self.assertEqual(json_format.MessageToJson(message), + text) + parsed_message = json_format_proto3_pb2.TestMessage() + json_format.Parse(text, parsed_message) + self.assertEqual(message, parsed_message) + + def testExtensionToJsonAndBack(self): + message = unittest_mset_pb2.TestMessageSetContainer() + ext1 = unittest_mset_pb2.TestMessageSetExtension1.message_set_extension + ext2 = unittest_mset_pb2.TestMessageSetExtension2.message_set_extension + message.message_set.Extensions[ext1].i = 23 + message.message_set.Extensions[ext2].str = 'foo' + message_text = json_format.MessageToJson( + message + ) + parsed_message = unittest_mset_pb2.TestMessageSetContainer() + json_format.Parse(message_text, parsed_message) + self.assertEqual(message, parsed_message) + + def testExtensionErrors(self): + self.CheckError('{"[extensionField]": {}}', + 'Message type proto3.TestMessage does not have extensions') + + def testExtensionToDictAndBack(self): + message = unittest_mset_pb2.TestMessageSetContainer() + ext1 = unittest_mset_pb2.TestMessageSetExtension1.message_set_extension + ext2 = unittest_mset_pb2.TestMessageSetExtension2.message_set_extension + message.message_set.Extensions[ext1].i = 23 + message.message_set.Extensions[ext2].str = 'foo' + message_dict = json_format.MessageToDict( + message + ) + parsed_message = unittest_mset_pb2.TestMessageSetContainer() + json_format.ParseDict(message_dict, parsed_message) + self.assertEqual(message, parsed_message) + + def testExtensionToDictAndBackWithScalar(self): + message = unittest_pb2.TestAllExtensions() + ext1 = unittest_pb2.TestNestedExtension.test + message.Extensions[ext1] = 'data' + message_dict = json_format.MessageToDict( + message + ) + parsed_message = unittest_pb2.TestAllExtensions() + json_format.ParseDict(message_dict, parsed_message) + self.assertEqual(message, parsed_message) + + def testJsonParseDictToAnyDoesNotAlterInput(self): + orig_dict = { + 'int32Value': 20, + '@type': 'type.googleapis.com/proto3.TestMessage' + } + copied_dict = json.loads(json.dumps(orig_dict)) + parsed_message = any_pb2.Any() + json_format.ParseDict(copied_dict, parsed_message) + self.assertEqual(copied_dict, orig_dict) + + def testExtensionSerializationDictMatchesProto3Spec(self): + """See go/proto3-json-spec for spec. + """ + message = unittest_mset_pb2.TestMessageSetContainer() + ext1 = unittest_mset_pb2.TestMessageSetExtension1.message_set_extension + ext2 = unittest_mset_pb2.TestMessageSetExtension2.message_set_extension + message.message_set.Extensions[ext1].i = 23 + message.message_set.Extensions[ext2].str = 'foo' + message_dict = json_format.MessageToDict( + message + ) + golden_dict = { + 'messageSet': { + '[protobuf_unittest.' + 'TestMessageSetExtension1.message_set_extension]': { + 'i': 23, + }, + '[protobuf_unittest.' + 'TestMessageSetExtension2.message_set_extension]': { + 'str': u'foo', + }, + }, + } + self.assertEqual(golden_dict, message_dict) + parsed_msg = unittest_mset_pb2.TestMessageSetContainer() + json_format.ParseDict(golden_dict, parsed_msg) + self.assertEqual(message, parsed_msg) + + def testExtensionSerializationDictMatchesProto3SpecMore(self): + """See go/proto3-json-spec for spec. + """ + message = json_format_pb2.TestMessageWithExtension() + ext = json_format_pb2.TestExtension.ext + message.Extensions[ext].value = 'stuff' + message_dict = json_format.MessageToDict( + message + ) + expected_dict = { + '[protobuf_unittest.TestExtension.ext]': { + 'value': u'stuff', + }, + } + self.assertEqual(expected_dict, message_dict) + + def testExtensionSerializationJsonMatchesProto3Spec(self): + """See go/proto3-json-spec for spec. + """ + message = unittest_mset_pb2.TestMessageSetContainer() + ext1 = unittest_mset_pb2.TestMessageSetExtension1.message_set_extension + ext2 = unittest_mset_pb2.TestMessageSetExtension2.message_set_extension + message.message_set.Extensions[ext1].i = 23 + message.message_set.Extensions[ext2].str = 'foo' + message_text = json_format.MessageToJson( + message + ) + ext1_text = ('protobuf_unittest.TestMessageSetExtension1.' + 'message_set_extension') + ext2_text = ('protobuf_unittest.TestMessageSetExtension2.' + 'message_set_extension') + golden_text = ('{"messageSet": {' + ' "[%s]": {' + ' "i": 23' + ' },' + ' "[%s]": {' + ' "str": "foo"' + ' }' + '}}') % (ext1_text, ext2_text) + self.assertEqual(json.loads(golden_text), json.loads(message_text)) + + def testJsonEscapeString(self): + message = json_format_proto3_pb2.TestMessage() + message.string_value = '&\n<\"\r>\b\t\f\\\001/' + message.string_value += (b'\xe2\x80\xa8\xe2\x80\xa9').decode('utf-8') + self.assertEqual( + json_format.MessageToJson(message), + '{\n "stringValue": ' + '"&\\n<\\\"\\r>\\b\\t\\f\\\\\\u0001/\\u2028\\u2029"\n}') + parsed_message = json_format_proto3_pb2.TestMessage() + self.CheckParseBack(message, parsed_message) + text = u'{"int32Value": "\u0031"}' + json_format.Parse(text, message) + self.assertEqual(message.int32_value, 1) + + def testAlwaysSeriliaze(self): + message = json_format_proto3_pb2.TestMessage( + string_value='foo') + self.assertEqual( + json.loads(json_format.MessageToJson(message, True)), + json.loads('{' + '"repeatedStringValue": [],' + '"stringValue": "foo",' + '"repeatedBoolValue": [],' + '"repeatedUint32Value": [],' + '"repeatedInt32Value": [],' + '"enumValue": "FOO",' + '"int32Value": 0,' + '"floatValue": 0,' + '"int64Value": "0",' + '"uint32Value": 0,' + '"repeatedBytesValue": [],' + '"repeatedUint64Value": [],' + '"repeatedDoubleValue": [],' + '"bytesValue": "",' + '"boolValue": false,' + '"repeatedEnumValue": [],' + '"uint64Value": "0",' + '"doubleValue": 0,' + '"repeatedFloatValue": [],' + '"repeatedInt64Value": [],' + '"repeatedMessageValue": []}')) + parsed_message = json_format_proto3_pb2.TestMessage() + self.CheckParseBack(message, parsed_message) + + def testProto3Optional(self): + message = test_proto3_optional_pb2.TestProto3Optional() + self.assertEqual( + json.loads( + json_format.MessageToJson( + message, including_default_value_fields=True)), + json.loads('{}')) + message.optional_int32 = 0 + self.assertEqual( + json.loads( + json_format.MessageToJson( + message, including_default_value_fields=True)), + json.loads('{"optionalInt32": 0}')) + + def testIntegersRepresentedAsFloat(self): + message = json_format_proto3_pb2.TestMessage() + json_format.Parse('{"int32Value": -2.147483648e9}', message) + self.assertEqual(message.int32_value, -2147483648) + json_format.Parse('{"int32Value": 1e5}', message) + self.assertEqual(message.int32_value, 100000) + json_format.Parse('{"int32Value": 1.0}', message) + self.assertEqual(message.int32_value, 1) + + def testMapFields(self): + message = json_format_proto3_pb2.TestNestedMap() + self.assertEqual( + json.loads(json_format.MessageToJson(message, True)), + json.loads('{' + '"boolMap": {},' + '"int32Map": {},' + '"int64Map": {},' + '"uint32Map": {},' + '"uint64Map": {},' + '"stringMap": {},' + '"mapMap": {}' + '}')) + message.bool_map[True] = 1 + message.bool_map[False] = 2 + message.int32_map[1] = 2 + message.int32_map[2] = 3 + message.int64_map[1] = 2 + message.int64_map[2] = 3 + message.uint32_map[1] = 2 + message.uint32_map[2] = 3 + message.uint64_map[1] = 2 + message.uint64_map[2] = 3 + message.string_map['1'] = 2 + message.string_map['null'] = 3 + message.map_map['1'].bool_map[True] = 3 + self.assertEqual( + json.loads(json_format.MessageToJson(message, False)), + json.loads('{' + '"boolMap": {"false": 2, "true": 1},' + '"int32Map": {"1": 2, "2": 3},' + '"int64Map": {"1": 2, "2": 3},' + '"uint32Map": {"1": 2, "2": 3},' + '"uint64Map": {"1": 2, "2": 3},' + '"stringMap": {"1": 2, "null": 3},' + '"mapMap": {"1": {"boolMap": {"true": 3}}}' + '}')) + parsed_message = json_format_proto3_pb2.TestNestedMap() + self.CheckParseBack(message, parsed_message) + + def testOneofFields(self): + message = json_format_proto3_pb2.TestOneof() + # Always print does not affect oneof fields. + self.assertEqual( + json_format.MessageToJson(message, True), + '{}') + message.oneof_int32_value = 0 + self.assertEqual( + json_format.MessageToJson(message, True), + '{\n' + ' "oneofInt32Value": 0\n' + '}') + parsed_message = json_format_proto3_pb2.TestOneof() + self.CheckParseBack(message, parsed_message) + + def testSurrogates(self): + # Test correct surrogate handling. + message = json_format_proto3_pb2.TestMessage() + json_format.Parse('{"stringValue": "\\uD83D\\uDE01"}', message) + self.assertEqual(message.string_value, + b'\xF0\x9F\x98\x81'.decode('utf-8', 'strict')) + + # Error case: unpaired high surrogate. + self.CheckError( + '{"stringValue": "\\uD83D"}', + r'Invalid \\uXXXX escape|Unpaired.*surrogate') + + # Unpaired low surrogate. + self.CheckError( + '{"stringValue": "\\uDE01"}', + r'Invalid \\uXXXX escape|Unpaired.*surrogate') + + def testTimestampMessage(self): + message = json_format_proto3_pb2.TestTimestamp() + message.value.seconds = 0 + message.value.nanos = 0 + message.repeated_value.add().seconds = 20 + message.repeated_value[0].nanos = 1 + message.repeated_value.add().seconds = 0 + message.repeated_value[1].nanos = 10000 + message.repeated_value.add().seconds = 100000000 + message.repeated_value[2].nanos = 0 + # Maximum time + message.repeated_value.add().seconds = 253402300799 + message.repeated_value[3].nanos = 999999999 + # Minimum time + message.repeated_value.add().seconds = -62135596800 + message.repeated_value[4].nanos = 0 + self.assertEqual( + json.loads(json_format.MessageToJson(message, True)), + json.loads('{' + '"value": "1970-01-01T00:00:00Z",' + '"repeatedValue": [' + ' "1970-01-01T00:00:20.000000001Z",' + ' "1970-01-01T00:00:00.000010Z",' + ' "1973-03-03T09:46:40Z",' + ' "9999-12-31T23:59:59.999999999Z",' + ' "0001-01-01T00:00:00Z"' + ']' + '}')) + parsed_message = json_format_proto3_pb2.TestTimestamp() + self.CheckParseBack(message, parsed_message) + text = (r'{"value": "1970-01-01T00:00:00.01+08:00",' + r'"repeatedValue":[' + r' "1970-01-01T00:00:00.01+08:30",' + r' "1970-01-01T00:00:00.01-01:23"]}') + json_format.Parse(text, parsed_message) + self.assertEqual(parsed_message.value.seconds, -8 * 3600) + self.assertEqual(parsed_message.value.nanos, 10000000) + self.assertEqual(parsed_message.repeated_value[0].seconds, -8.5 * 3600) + self.assertEqual(parsed_message.repeated_value[1].seconds, 3600 + 23 * 60) + + def testDurationMessage(self): + message = json_format_proto3_pb2.TestDuration() + message.value.seconds = 1 + message.repeated_value.add().seconds = 0 + message.repeated_value[0].nanos = 10 + message.repeated_value.add().seconds = -1 + message.repeated_value[1].nanos = -1000 + message.repeated_value.add().seconds = 10 + message.repeated_value[2].nanos = 11000000 + message.repeated_value.add().seconds = -315576000000 + message.repeated_value.add().seconds = 315576000000 + self.assertEqual( + json.loads(json_format.MessageToJson(message, True)), + json.loads('{' + '"value": "1s",' + '"repeatedValue": [' + ' "0.000000010s",' + ' "-1.000001s",' + ' "10.011s",' + ' "-315576000000s",' + ' "315576000000s"' + ']' + '}')) + parsed_message = json_format_proto3_pb2.TestDuration() + self.CheckParseBack(message, parsed_message) + + def testFieldMaskMessage(self): + message = json_format_proto3_pb2.TestFieldMask() + message.value.paths.append('foo.bar') + message.value.paths.append('bar') + self.assertEqual( + json_format.MessageToJson(message, True), + '{\n' + ' "value": "foo.bar,bar"\n' + '}') + parsed_message = json_format_proto3_pb2.TestFieldMask() + self.CheckParseBack(message, parsed_message) + + message.value.Clear() + self.assertEqual( + json_format.MessageToJson(message, True), + '{\n' + ' "value": ""\n' + '}') + self.CheckParseBack(message, parsed_message) + + def testWrapperMessage(self): + message = json_format_proto3_pb2.TestWrapper() + message.bool_value.value = False + message.int32_value.value = 0 + message.string_value.value = '' + message.bytes_value.value = b'' + message.repeated_bool_value.add().value = True + message.repeated_bool_value.add().value = False + message.repeated_int32_value.add() + self.assertEqual( + json.loads(json_format.MessageToJson(message, True)), + json.loads('{\n' + ' "int32Value": 0,' + ' "boolValue": false,' + ' "stringValue": "",' + ' "bytesValue": "",' + ' "repeatedBoolValue": [true, false],' + ' "repeatedInt32Value": [0],' + ' "repeatedUint32Value": [],' + ' "repeatedFloatValue": [],' + ' "repeatedDoubleValue": [],' + ' "repeatedBytesValue": [],' + ' "repeatedInt64Value": [],' + ' "repeatedUint64Value": [],' + ' "repeatedStringValue": []' + '}')) + parsed_message = json_format_proto3_pb2.TestWrapper() + self.CheckParseBack(message, parsed_message) + + def testStructMessage(self): + message = json_format_proto3_pb2.TestStruct() + message.value['name'] = 'Jim' + message.value['age'] = 10 + message.value['attend'] = True + message.value['email'] = None + message.value.get_or_create_struct('address')['city'] = 'SFO' + message.value['address']['house_number'] = 1024 + message.value.get_or_create_struct('empty_struct') + message.value.get_or_create_list('empty_list') + struct_list = message.value.get_or_create_list('list') + struct_list.extend([6, 'seven', True, False, None]) + struct_list.add_struct()['subkey2'] = 9 + message.repeated_value.add()['age'] = 11 + message.repeated_value.add() + self.assertEqual( + json.loads(json_format.MessageToJson(message, False)), + json.loads( + '{' + ' "value": {' + ' "address": {' + ' "city": "SFO", ' + ' "house_number": 1024' + ' }, ' + ' "empty_struct": {}, ' + ' "empty_list": [], ' + ' "age": 10, ' + ' "name": "Jim", ' + ' "attend": true, ' + ' "email": null, ' + ' "list": [6, "seven", true, false, null, {"subkey2": 9}]' + ' },' + ' "repeatedValue": [{"age": 11}, {}]' + '}')) + parsed_message = json_format_proto3_pb2.TestStruct() + self.CheckParseBack(message, parsed_message) + # check for regression; this used to raise + parsed_message.value['empty_struct'] + parsed_message.value['empty_list'] + + def testValueMessage(self): + message = json_format_proto3_pb2.TestValue() + message.value.string_value = 'hello' + message.repeated_value.add().number_value = 11.1 + message.repeated_value.add().bool_value = False + message.repeated_value.add().null_value = 0 + self.assertEqual( + json.loads(json_format.MessageToJson(message, False)), + json.loads( + '{' + ' "value": "hello",' + ' "repeatedValue": [11.1, false, null]' + '}')) + parsed_message = json_format_proto3_pb2.TestValue() + self.CheckParseBack(message, parsed_message) + # Can't parse back if the Value message is not set. + message.repeated_value.add() + self.assertEqual( + json.loads(json_format.MessageToJson(message, False)), + json.loads( + '{' + ' "value": "hello",' + ' "repeatedValue": [11.1, false, null, null]' + '}')) + message.Clear() + json_format.Parse('{"value": null}', message) + self.assertEqual(message.value.WhichOneof('kind'), 'null_value') + + def testListValueMessage(self): + message = json_format_proto3_pb2.TestListValue() + message.value.values.add().number_value = 11.1 + message.value.values.add().null_value = 0 + message.value.values.add().bool_value = True + message.value.values.add().string_value = 'hello' + message.value.values.add().struct_value['name'] = 'Jim' + message.repeated_value.add().values.add().number_value = 1 + message.repeated_value.add() + self.assertEqual( + json.loads(json_format.MessageToJson(message, False)), + json.loads( + '{"value": [11.1, null, true, "hello", {"name": "Jim"}]\n,' + '"repeatedValue": [[1], []]}')) + parsed_message = json_format_proto3_pb2.TestListValue() + self.CheckParseBack(message, parsed_message) + + def testNullValue(self): + message = json_format_proto3_pb2.TestOneof() + message.oneof_null_value = 0 + self.assertEqual(json_format.MessageToJson(message), + '{\n "oneofNullValue": null\n}') + parsed_message = json_format_proto3_pb2.TestOneof() + self.CheckParseBack(message, parsed_message) + # Check old format is also accepted + new_message = json_format_proto3_pb2.TestOneof() + json_format.Parse('{\n "oneofNullValue": "NULL_VALUE"\n}', + new_message) + self.assertEqual(json_format.MessageToJson(new_message), + '{\n "oneofNullValue": null\n}') + + def testAnyMessage(self): + message = json_format_proto3_pb2.TestAny() + value1 = json_format_proto3_pb2.MessageType() + value2 = json_format_proto3_pb2.MessageType() + value1.value = 1234 + value2.value = 5678 + message.value.Pack(value1) + message.repeated_value.add().Pack(value1) + message.repeated_value.add().Pack(value2) + message.repeated_value.add() + self.assertEqual( + json.loads(json_format.MessageToJson(message, True)), + json.loads( + '{\n' + ' "repeatedValue": [ {\n' + ' "@type": "type.googleapis.com/proto3.MessageType",\n' + ' "value": 1234\n' + ' }, {\n' + ' "@type": "type.googleapis.com/proto3.MessageType",\n' + ' "value": 5678\n' + ' },\n' + ' {}],\n' + ' "value": {\n' + ' "@type": "type.googleapis.com/proto3.MessageType",\n' + ' "value": 1234\n' + ' }\n' + '}\n')) + parsed_message = json_format_proto3_pb2.TestAny() + self.CheckParseBack(message, parsed_message) + # Must print @type first + test_message = json_format_proto3_pb2.TestMessage( + bool_value=True, + int32_value=20, + int64_value=-20, + uint32_value=20, + uint64_value=20, + double_value=3.14, + string_value='foo') + message.Clear() + message.value.Pack(test_message) + self.assertEqual( + json_format.MessageToJson(message, False)[0:68], + '{\n' + ' "value": {\n' + ' "@type": "type.googleapis.com/proto3.TestMessage"') + + def testAnyMessageDescriptorPoolMissingType(self): + packed_message = unittest_pb2.OneString() + packed_message.data = 'string' + message = any_test_pb2.TestAny() + message.any_value.Pack(packed_message) + empty_pool = descriptor_pool.DescriptorPool() + with self.assertRaises(TypeError) as cm: + json_format.MessageToJson(message, True, descriptor_pool=empty_pool) + self.assertEqual( + 'Can not find message descriptor by type_url:' + ' type.googleapis.com/protobuf_unittest.OneString.', + str(cm.exception)) + + def testWellKnownInAnyMessage(self): + message = any_pb2.Any() + int32_value = wrappers_pb2.Int32Value() + int32_value.value = 1234 + message.Pack(int32_value) + self.assertEqual( + json.loads(json_format.MessageToJson(message, True)), + json.loads( + '{\n' + ' "@type": \"type.googleapis.com/google.protobuf.Int32Value\",\n' + ' "value": 1234\n' + '}\n')) + parsed_message = any_pb2.Any() + self.CheckParseBack(message, parsed_message) + + timestamp = timestamp_pb2.Timestamp() + message.Pack(timestamp) + self.assertEqual( + json.loads(json_format.MessageToJson(message, True)), + json.loads( + '{\n' + ' "@type": "type.googleapis.com/google.protobuf.Timestamp",\n' + ' "value": "1970-01-01T00:00:00Z"\n' + '}\n')) + self.CheckParseBack(message, parsed_message) + + duration = duration_pb2.Duration() + duration.seconds = 1 + message.Pack(duration) + self.assertEqual( + json.loads(json_format.MessageToJson(message, True)), + json.loads( + '{\n' + ' "@type": "type.googleapis.com/google.protobuf.Duration",\n' + ' "value": "1s"\n' + '}\n')) + self.CheckParseBack(message, parsed_message) + + field_mask = field_mask_pb2.FieldMask() + field_mask.paths.append('foo.bar') + field_mask.paths.append('bar') + message.Pack(field_mask) + self.assertEqual( + json.loads(json_format.MessageToJson(message, True)), + json.loads( + '{\n' + ' "@type": "type.googleapis.com/google.protobuf.FieldMask",\n' + ' "value": "foo.bar,bar"\n' + '}\n')) + self.CheckParseBack(message, parsed_message) + + struct_message = struct_pb2.Struct() + struct_message['name'] = 'Jim' + message.Pack(struct_message) + self.assertEqual( + json.loads(json_format.MessageToJson(message, True)), + json.loads( + '{\n' + ' "@type": "type.googleapis.com/google.protobuf.Struct",\n' + ' "value": {"name": "Jim"}\n' + '}\n')) + self.CheckParseBack(message, parsed_message) + + nested_any = any_pb2.Any() + int32_value.value = 5678 + nested_any.Pack(int32_value) + message.Pack(nested_any) + self.assertEqual( + json.loads(json_format.MessageToJson(message, True)), + json.loads( + '{\n' + ' "@type": "type.googleapis.com/google.protobuf.Any",\n' + ' "value": {\n' + ' "@type": "type.googleapis.com/google.protobuf.Int32Value",\n' + ' "value": 5678\n' + ' }\n' + '}\n')) + self.CheckParseBack(message, parsed_message) + + def testParseNull(self): + message = json_format_proto3_pb2.TestMessage() + parsed_message = json_format_proto3_pb2.TestMessage() + self.FillAllFields(parsed_message) + json_format.Parse('{"int32Value": null, ' + '"int64Value": null, ' + '"uint32Value": null,' + '"uint64Value": null,' + '"floatValue": null,' + '"doubleValue": null,' + '"boolValue": null,' + '"stringValue": null,' + '"bytesValue": null,' + '"messageValue": null,' + '"enumValue": null,' + '"repeatedInt32Value": null,' + '"repeatedInt64Value": null,' + '"repeatedUint32Value": null,' + '"repeatedUint64Value": null,' + '"repeatedFloatValue": null,' + '"repeatedDoubleValue": null,' + '"repeatedBoolValue": null,' + '"repeatedStringValue": null,' + '"repeatedBytesValue": null,' + '"repeatedMessageValue": null,' + '"repeatedEnumValue": null' + '}', + parsed_message) + self.assertEqual(message, parsed_message) + # Null and {} should have different behavior for sub message. + self.assertFalse(parsed_message.HasField('message_value')) + json_format.Parse('{"messageValue": {}}', parsed_message) + self.assertTrue(parsed_message.HasField('message_value')) + # Null is not allowed to be used as an element in repeated field. + self.assertRaisesRegex( + json_format.ParseError, + 'Failed to parse repeatedInt32Value field: ' + 'null is not allowed to be used as an element in a repeated field.', + json_format.Parse, + '{"repeatedInt32Value":[1, null]}', + parsed_message) + self.CheckError('{"repeatedMessageValue":[null]}', + 'Failed to parse repeatedMessageValue field: null is not' + ' allowed to be used as an element in a repeated field.') + + def testNanFloat(self): + message = json_format_proto3_pb2.TestMessage() + message.float_value = float('nan') + text = '{\n "floatValue": "NaN"\n}' + self.assertEqual(json_format.MessageToJson(message), text) + parsed_message = json_format_proto3_pb2.TestMessage() + json_format.Parse(text, parsed_message) + self.assertTrue(math.isnan(parsed_message.float_value)) + + def testParseDoubleToFloat(self): + message = json_format_proto3_pb2.TestMessage() + text = ('{"repeatedDoubleValue": [3.4028235e+39, 1.4028235e-39]\n}') + json_format.Parse(text, message) + self.assertEqual(message.repeated_double_value[0], 3.4028235e+39) + self.assertEqual(message.repeated_double_value[1], 1.4028235e-39) + text = ('{"repeatedFloatValue": [3.4028235e+39, 1.4028235e-39]\n}') + self.CheckError(text, + 'Failed to parse repeatedFloatValue field: ' + 'Float value too large.') + + def testFloatPrecision(self): + message = json_format_proto3_pb2.TestMessage() + message.float_value = 1.123456789 + # Set to 8 valid digits. + text = '{\n "floatValue": 1.1234568\n}' + self.assertEqual( + json_format.MessageToJson(message, float_precision=8), text) + # Set to 7 valid digits. + text = '{\n "floatValue": 1.123457\n}' + self.assertEqual( + json_format.MessageToJson(message, float_precision=7), text) + + # Default float_precision will automatic print shortest float. + message.float_value = 1.1000000011 + text = '{\n "floatValue": 1.1\n}' + self.assertEqual( + json_format.MessageToJson(message), text) + message.float_value = 1.00000075e-36 + text = '{\n "floatValue": 1.00000075e-36\n}' + self.assertEqual( + json_format.MessageToJson(message), text) + message.float_value = 12345678912345e+11 + text = '{\n "floatValue": 1.234568e+24\n}' + self.assertEqual( + json_format.MessageToJson(message), text) + + # Test a bunch of data and check json encode/decode do not + # lose precision + value_list = [0x00, 0xD8, 0x6E, 0x00] + msg2 = json_format_proto3_pb2.TestMessage() + for a in range(0, 256): + value_list[3] = a + for b in range(0, 256): + value_list[0] = b + byte_array = bytearray(value_list) + message.float_value = struct.unpack('.", + json_format.ParseDict, + {'value': UnknownClass()}, + message) + + def testMessageToDict(self): + message = json_format_proto3_pb2.TestMessage() + message.int32_value = 12345 + expected = {'int32Value': 12345} + self.assertEqual(expected, + json_format.MessageToDict(message)) + + def testJsonName(self): + message = json_format_proto3_pb2.TestCustomJsonName() + message.value = 12345 + self.assertEqual('{\n "@value": 12345\n}', + json_format.MessageToJson(message)) + parsed_message = json_format_proto3_pb2.TestCustomJsonName() + self.CheckParseBack(message, parsed_message) + + def testSortKeys(self): + # Testing sort_keys is not perfectly working, as by random luck we could + # get the output sorted. We just use a selection of names. + message = json_format_proto3_pb2.TestMessage(bool_value=True, + int32_value=1, + int64_value=3, + uint32_value=4, + string_value='bla') + self.assertEqual( + json_format.MessageToJson(message, sort_keys=True), + # We use json.dumps() instead of a hardcoded string due to differences + # between Python 2 and Python 3. + json.dumps({'boolValue': True, 'int32Value': 1, 'int64Value': '3', + 'uint32Value': 4, 'stringValue': 'bla'}, + indent=2, sort_keys=True)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/internal/service_reflection_test.py b/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/internal/service_reflection_test.py new file mode 100644 index 0000000..8e72213 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/internal/service_reflection_test.py @@ -0,0 +1,139 @@ +# 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. + +"""Tests for google.protobuf.internal.service_reflection.""" + +__author__ = 'petar@google.com (Petar Petrov)' + + +import unittest + +from google.protobuf import unittest_pb2 +from google.protobuf import service_reflection +from google.protobuf import service + + +class FooUnitTest(unittest.TestCase): + + def testService(self): + class MockRpcChannel(service.RpcChannel): + def CallMethod(self, method, controller, request, response, callback): + self.method = method + self.controller = controller + self.request = request + callback(response) + + class MockRpcController(service.RpcController): + def SetFailed(self, msg): + self.failure_message = msg + + self.callback_response = None + + class MyService(unittest_pb2.TestService): + pass + + self.callback_response = None + + def MyCallback(response): + self.callback_response = response + + rpc_controller = MockRpcController() + channel = MockRpcChannel() + srvc = MyService() + srvc.Foo(rpc_controller, unittest_pb2.FooRequest(), MyCallback) + self.assertEqual('Method Foo not implemented.', + rpc_controller.failure_message) + self.assertEqual(None, self.callback_response) + + rpc_controller.failure_message = None + + service_descriptor = unittest_pb2.TestService.GetDescriptor() + srvc.CallMethod(service_descriptor.methods[1], rpc_controller, + unittest_pb2.BarRequest(), MyCallback) + self.assertTrue(srvc.GetRequestClass(service_descriptor.methods[1]) is + unittest_pb2.BarRequest) + self.assertTrue(srvc.GetResponseClass(service_descriptor.methods[1]) is + unittest_pb2.BarResponse) + self.assertEqual('Method Bar not implemented.', + rpc_controller.failure_message) + self.assertEqual(None, self.callback_response) + + class MyServiceImpl(unittest_pb2.TestService): + def Foo(self, rpc_controller, request, done): + self.foo_called = True + def Bar(self, rpc_controller, request, done): + self.bar_called = True + + srvc = MyServiceImpl() + rpc_controller.failure_message = None + srvc.Foo(rpc_controller, unittest_pb2.FooRequest(), MyCallback) + self.assertEqual(None, rpc_controller.failure_message) + self.assertEqual(True, srvc.foo_called) + + rpc_controller.failure_message = None + srvc.CallMethod(service_descriptor.methods[1], rpc_controller, + unittest_pb2.BarRequest(), MyCallback) + self.assertEqual(None, rpc_controller.failure_message) + self.assertEqual(True, srvc.bar_called) + + def testServiceStub(self): + class MockRpcChannel(service.RpcChannel): + def CallMethod(self, method, controller, request, + response_class, callback): + self.method = method + self.controller = controller + self.request = request + callback(response_class()) + + self.callback_response = None + + def MyCallback(response): + self.callback_response = response + + channel = MockRpcChannel() + stub = unittest_pb2.TestService_Stub(channel) + rpc_controller = 'controller' + request = 'request' + + # GetDescriptor now static, still works as instance method for compatibility + self.assertEqual(unittest_pb2.TestService_Stub.GetDescriptor(), + stub.GetDescriptor()) + + # Invoke method. + stub.Foo(rpc_controller, request, MyCallback) + + self.assertIsInstance(self.callback_response, unittest_pb2.FooResponse) + self.assertEqual(request, channel.request) + self.assertEqual(rpc_controller, channel.controller) + self.assertEqual(stub.GetDescriptor().methods[0], channel.method) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/internal/symbol_database_test.py b/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/internal/symbol_database_test.py new file mode 100644 index 0000000..4fdc4ee --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/internal/symbol_database_test.py @@ -0,0 +1,133 @@ +# 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. + +"""Tests for google.protobuf.symbol_database.""" + +import unittest + +from google.protobuf import unittest_pb2 +from google.protobuf import descriptor +from google.protobuf import descriptor_pool +from google.protobuf import symbol_database + + +class SymbolDatabaseTest(unittest.TestCase): + + def _Database(self): + if descriptor._USE_C_DESCRIPTORS: + # The C++ implementation does not allow mixing descriptors from + # different pools. + db = symbol_database.SymbolDatabase(pool=descriptor_pool.Default()) + else: + db = symbol_database.SymbolDatabase() + # Register representative types from unittest_pb2. + db.RegisterFileDescriptor(unittest_pb2.DESCRIPTOR) + db.RegisterMessage(unittest_pb2.TestAllTypes) + db.RegisterMessage(unittest_pb2.TestAllTypes.NestedMessage) + db.RegisterMessage(unittest_pb2.TestAllTypes.OptionalGroup) + db.RegisterMessage(unittest_pb2.TestAllTypes.RepeatedGroup) + db.RegisterEnumDescriptor(unittest_pb2.ForeignEnum.DESCRIPTOR) + db.RegisterEnumDescriptor(unittest_pb2.TestAllTypes.NestedEnum.DESCRIPTOR) + db.RegisterServiceDescriptor(unittest_pb2._TESTSERVICE) + return db + + def testGetPrototype(self): + instance = self._Database().GetPrototype( + unittest_pb2.TestAllTypes.DESCRIPTOR) + self.assertTrue(instance is unittest_pb2.TestAllTypes) + + def testGetMessages(self): + messages = self._Database().GetMessages( + ['google/protobuf/unittest.proto']) + self.assertTrue( + unittest_pb2.TestAllTypes is + messages['protobuf_unittest.TestAllTypes']) + + def testGetSymbol(self): + self.assertEqual( + unittest_pb2.TestAllTypes, self._Database().GetSymbol( + 'protobuf_unittest.TestAllTypes')) + self.assertEqual( + unittest_pb2.TestAllTypes.NestedMessage, self._Database().GetSymbol( + 'protobuf_unittest.TestAllTypes.NestedMessage')) + self.assertEqual( + unittest_pb2.TestAllTypes.OptionalGroup, self._Database().GetSymbol( + 'protobuf_unittest.TestAllTypes.OptionalGroup')) + self.assertEqual( + unittest_pb2.TestAllTypes.RepeatedGroup, self._Database().GetSymbol( + 'protobuf_unittest.TestAllTypes.RepeatedGroup')) + + def testEnums(self): + # Check registration of types in the pool. + self.assertEqual( + 'protobuf_unittest.ForeignEnum', + self._Database().pool.FindEnumTypeByName( + 'protobuf_unittest.ForeignEnum').full_name) + self.assertEqual( + 'protobuf_unittest.TestAllTypes.NestedEnum', + self._Database().pool.FindEnumTypeByName( + 'protobuf_unittest.TestAllTypes.NestedEnum').full_name) + + def testFindMessageTypeByName(self): + self.assertEqual( + 'protobuf_unittest.TestAllTypes', + self._Database().pool.FindMessageTypeByName( + 'protobuf_unittest.TestAllTypes').full_name) + self.assertEqual( + 'protobuf_unittest.TestAllTypes.NestedMessage', + self._Database().pool.FindMessageTypeByName( + 'protobuf_unittest.TestAllTypes.NestedMessage').full_name) + + def testFindServiceByName(self): + self.assertEqual( + 'protobuf_unittest.TestService', + self._Database().pool.FindServiceByName( + 'protobuf_unittest.TestService').full_name) + + def testFindFileContainingSymbol(self): + # Lookup based on either enum or message. + self.assertEqual( + 'google/protobuf/unittest.proto', + self._Database().pool.FindFileContainingSymbol( + 'protobuf_unittest.TestAllTypes.NestedEnum').name) + self.assertEqual( + 'google/protobuf/unittest.proto', + self._Database().pool.FindFileContainingSymbol( + 'protobuf_unittest.TestAllTypes').name) + + def testFindFileByName(self): + self.assertEqual( + 'google/protobuf/unittest.proto', + self._Database().pool.FindFileByName( + 'google/protobuf/unittest.proto').name) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/cpp_message.py b/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/cpp_message.py new file mode 100644 index 0000000..fc8eb32 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/cpp_message.py @@ -0,0 +1,65 @@ +# 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. + +"""Protocol message implementation hooks for C++ implementation. + +Contains helper functions used to create protocol message classes from +Descriptor objects at runtime backed by the protocol buffer C++ API. +""" + +__author__ = 'tibell@google.com (Johan Tibell)' + +from google.protobuf.pyext import _message + + +class GeneratedProtocolMessageType(_message.MessageMeta): + + """Metaclass for protocol message classes created at runtime from Descriptors. + + The protocol compiler currently uses this metaclass to create protocol + message classes at runtime. Clients can also manually create their own + classes at runtime, as in this example: + + mydescriptor = Descriptor(.....) + factory = symbol_database.Default() + factory.pool.AddDescriptor(mydescriptor) + MyProtoClass = factory.GetPrototype(mydescriptor) + myproto_instance = MyProtoClass() + myproto.foo_field = 23 + ... + + The above example will not work for nested types. If you wish to include them, + use reflection.MakeClass() instead of manually instantiating the class in + order to create the appropriate class structure. + """ + + # Must be consistent with the protocol-compiler code in + # proto2/compiler/internal/generator.*. + _DESCRIPTOR_KEY = 'DESCRIPTOR' diff --git a/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/descriptor_database.h b/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/descriptor_database.h new file mode 100644 index 0000000..3bc99e7 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/descriptor_database.h @@ -0,0 +1,82 @@ +// 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_PYTHON_CPP_DESCRIPTOR_DATABASE_H__ +#define GOOGLE_PROTOBUF_PYTHON_CPP_DESCRIPTOR_DATABASE_H__ + +#define PY_SSIZE_T_CLEAN +#include + +#include + +namespace google { +namespace protobuf { +namespace python { + +class PyDescriptorDatabase : public DescriptorDatabase { + public: + explicit PyDescriptorDatabase(PyObject* py_database); + ~PyDescriptorDatabase(); + + // Implement the abstract interface. All these functions fill the output + // with a copy of FileDescriptorProto. + + // Find a file by file name. + bool FindFileByName(const std::string& filename, FileDescriptorProto* output); + + // Find the file that declares the given fully-qualified symbol name. + bool FindFileContainingSymbol(const std::string& symbol_name, + FileDescriptorProto* output); + + // Find the file which defines an extension extending the given message type + // with the given field number. + // Containing_type must be a fully-qualified type name. + // Python objects are not required to implement this method. + bool FindFileContainingExtension(const std::string& containing_type, + int field_number, + FileDescriptorProto* output); + + // Finds the tag numbers used by all known extensions of + // containing_type, and appends them to output in an undefined + // order. + // Python objects are not required to implement this method. + bool FindAllExtensionNumbers(const std::string& containing_type, + std::vector* output); + + private: + // The python object that implements the database. The reference is owned. + PyObject* py_database_; +}; + +} // namespace python +} // namespace protobuf +} // namespace google + +#endif // GOOGLE_PROTOBUF_PYTHON_CPP_DESCRIPTOR_DATABASE_H__ diff --git a/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/descriptor_pool.cc b/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/descriptor_pool.cc new file mode 100644 index 0000000..f6bdb6e --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/descriptor_pool.cc @@ -0,0 +1,812 @@ +// 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. + +// Implements the DescriptorPool, which collects all descriptors. + +#include + +#define PY_SSIZE_T_CLEAN +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#define PyString_AsStringAndSize(ob, charpp, sizep) \ + (PyUnicode_Check(ob) ? ((*(charpp) = const_cast( \ + PyUnicode_AsUTF8AndSize(ob, (sizep)))) == NULL \ + ? -1 \ + : 0) \ + : PyBytes_AsStringAndSize(ob, (charpp), (sizep))) + +namespace google { +namespace protobuf { +namespace python { + +// A map to cache Python Pools per C++ pointer. +// Pointers are not owned here, and belong to the PyDescriptorPool. +static std::unordered_map* + descriptor_pool_map; + +namespace cdescriptor_pool { + +// Collects errors that occur during proto file building to allow them to be +// propagated in the python exception instead of only living in ERROR logs. +class BuildFileErrorCollector : public DescriptorPool::ErrorCollector { + public: + BuildFileErrorCollector() : error_message(""), had_errors_(false) {} + + void AddError(const std::string& filename, const std::string& element_name, + const Message* descriptor, ErrorLocation location, + const std::string& message) override { + // Replicates the logging behavior that happens in the C++ implementation + // when an error collector is not passed in. + if (!had_errors_) { + error_message += + ("Invalid proto descriptor for file \"" + filename + "\":\n"); + had_errors_ = true; + } + // As this only happens on failure and will result in the program not + // running at all, no effort is made to optimize this string manipulation. + error_message += (" " + element_name + ": " + message + "\n"); + } + + void Clear() { + had_errors_ = false; + error_message = ""; + } + + std::string error_message; + + private: + bool had_errors_; +}; + +// Create a Python DescriptorPool object, but does not fill the "pool" +// attribute. +static PyDescriptorPool* _CreateDescriptorPool() { + PyDescriptorPool* cpool = PyObject_GC_New( + PyDescriptorPool, &PyDescriptorPool_Type); + if (cpool == NULL) { + return NULL; + } + + cpool->error_collector = nullptr; + cpool->underlay = NULL; + cpool->database = NULL; + cpool->is_owned = false; + cpool->is_mutable = false; + + cpool->descriptor_options = new std::unordered_map(); + + cpool->py_message_factory = message_factory::NewMessageFactory( + &PyMessageFactory_Type, cpool); + if (cpool->py_message_factory == NULL) { + Py_DECREF(cpool); + return NULL; + } + + PyObject_GC_Track(cpool); + + return cpool; +} + +// Create a Python DescriptorPool, using the given pool as an underlay: +// new messages will be added to a custom pool, not to the underlay. +// +// Ownership of the underlay is not transferred, its pointer should +// stay alive. +static PyDescriptorPool* PyDescriptorPool_NewWithUnderlay( + const DescriptorPool* underlay) { + PyDescriptorPool* cpool = _CreateDescriptorPool(); + if (cpool == NULL) { + return NULL; + } + cpool->pool = new DescriptorPool(underlay); + cpool->is_owned = true; + cpool->is_mutable = true; + cpool->underlay = underlay; + + if (!descriptor_pool_map->insert( + std::make_pair(cpool->pool, cpool)).second) { + // Should never happen -- would indicate an internal error / bug. + PyErr_SetString(PyExc_ValueError, "DescriptorPool already registered"); + return NULL; + } + + return cpool; +} + +static PyDescriptorPool* PyDescriptorPool_NewWithDatabase( + DescriptorDatabase* database) { + PyDescriptorPool* cpool = _CreateDescriptorPool(); + if (cpool == NULL) { + return NULL; + } + if (database != NULL) { + cpool->error_collector = new BuildFileErrorCollector(); + cpool->pool = new DescriptorPool(database, cpool->error_collector); + cpool->is_mutable = false; + cpool->database = database; + } else { + cpool->pool = new DescriptorPool(); + cpool->is_mutable = true; + } + cpool->is_owned = true; + + if (!descriptor_pool_map->insert(std::make_pair(cpool->pool, cpool)).second) { + // Should never happen -- would indicate an internal error / bug. + PyErr_SetString(PyExc_ValueError, "DescriptorPool already registered"); + return NULL; + } + + return cpool; +} + +// The public DescriptorPool constructor. +static PyObject* New(PyTypeObject* type, + PyObject* args, PyObject* kwargs) { + static const char* kwlist[] = {"descriptor_db", 0}; + PyObject* py_database = NULL; + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", + const_cast(kwlist), &py_database)) { + return NULL; + } + DescriptorDatabase* database = NULL; + if (py_database && py_database != Py_None) { + database = new PyDescriptorDatabase(py_database); + } + return reinterpret_cast( + PyDescriptorPool_NewWithDatabase(database)); +} + +static void Dealloc(PyObject* pself) { + PyDescriptorPool* self = reinterpret_cast(pself); + descriptor_pool_map->erase(self->pool); + Py_CLEAR(self->py_message_factory); + for (std::unordered_map::iterator it = + self->descriptor_options->begin(); + it != self->descriptor_options->end(); ++it) { + Py_DECREF(it->second); + } + delete self->descriptor_options; + delete self->database; + if (self->is_owned) { + delete self->pool; + } + delete self->error_collector; + Py_TYPE(self)->tp_free(pself); +} + +static int GcTraverse(PyObject* pself, visitproc visit, void* arg) { + PyDescriptorPool* self = reinterpret_cast(pself); + Py_VISIT(self->py_message_factory); + return 0; +} + +static int GcClear(PyObject* pself) { + PyDescriptorPool* self = reinterpret_cast(pself); + Py_CLEAR(self->py_message_factory); + return 0; +} + +PyObject* SetErrorFromCollector(DescriptorPool::ErrorCollector* self, + const char* name, const char* error_type) { + BuildFileErrorCollector* error_collector = + reinterpret_cast(self); + if (error_collector && !error_collector->error_message.empty()) { + PyErr_Format(PyExc_KeyError, "Couldn't build file for %s %.200s\n%s", + error_type, name, error_collector->error_message.c_str()); + error_collector->Clear(); + return NULL; + } + PyErr_Format(PyExc_KeyError, "Couldn't find %s %.200s", error_type, name); + return NULL; +} + +static PyObject* FindMessageByName(PyObject* self, PyObject* arg) { + Py_ssize_t name_size; + char* name; + if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) { + return NULL; + } + + const Descriptor* message_descriptor = + reinterpret_cast(self)->pool->FindMessageTypeByName( + StringParam(name, name_size)); + + if (message_descriptor == NULL) { + return SetErrorFromCollector( + reinterpret_cast(self)->error_collector, name, + "message"); + } + + + return PyMessageDescriptor_FromDescriptor(message_descriptor); +} + + + + +static PyObject* FindFileByName(PyObject* self, PyObject* arg) { + Py_ssize_t name_size; + char* name; + if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) { + return NULL; + } + + PyDescriptorPool* py_pool = reinterpret_cast(self); + const FileDescriptor* file_descriptor = + py_pool->pool->FindFileByName(StringParam(name, name_size)); + + if (file_descriptor == NULL) { + return SetErrorFromCollector(py_pool->error_collector, name, "file"); + } + return PyFileDescriptor_FromDescriptor(file_descriptor); +} + +PyObject* FindFieldByName(PyDescriptorPool* self, PyObject* arg) { + Py_ssize_t name_size; + char* name; + if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) { + return NULL; + } + + const FieldDescriptor* field_descriptor = + self->pool->FindFieldByName(StringParam(name, name_size)); + if (field_descriptor == NULL) { + return SetErrorFromCollector(self->error_collector, name, "field"); + } + + + 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; + if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) { + return NULL; + } + + const FieldDescriptor* field_descriptor = + self->pool->FindExtensionByName(StringParam(name, name_size)); + if (field_descriptor == NULL) { + return SetErrorFromCollector(self->error_collector, name, + "extension field"); + } + + + 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; + if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) { + return NULL; + } + + const EnumDescriptor* enum_descriptor = + self->pool->FindEnumTypeByName(StringParam(name, name_size)); + if (enum_descriptor == NULL) { + return SetErrorFromCollector(self->error_collector, name, "enum"); + } + + + 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; + if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) { + return NULL; + } + + const OneofDescriptor* oneof_descriptor = + self->pool->FindOneofByName(StringParam(name, name_size)); + if (oneof_descriptor == NULL) { + return SetErrorFromCollector(self->error_collector, name, "oneof"); + } + + + return PyOneofDescriptor_FromDescriptor(oneof_descriptor); +} + +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) { + return NULL; + } + + const ServiceDescriptor* service_descriptor = + reinterpret_cast(self)->pool->FindServiceByName( + StringParam(name, name_size)); + if (service_descriptor == NULL) { + return SetErrorFromCollector( + reinterpret_cast(self)->error_collector, name, + "service"); + } + + + return PyServiceDescriptor_FromDescriptor(service_descriptor); +} + +static PyObject* FindMethodByName(PyObject* self, PyObject* arg) { + Py_ssize_t name_size; + char* name; + if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) { + return NULL; + } + + const MethodDescriptor* method_descriptor = + reinterpret_cast(self)->pool->FindMethodByName( + StringParam(name, name_size)); + if (method_descriptor == NULL) { + return SetErrorFromCollector( + reinterpret_cast(self)->error_collector, name, + "method"); + } + + + return PyMethodDescriptor_FromDescriptor(method_descriptor); +} + +static PyObject* FindFileContainingSymbol(PyObject* self, PyObject* arg) { + Py_ssize_t name_size; + char* name; + if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) { + return NULL; + } + + const FileDescriptor* file_descriptor = + reinterpret_cast(self)->pool->FindFileContainingSymbol( + StringParam(name, name_size)); + if (file_descriptor == NULL) { + return SetErrorFromCollector( + reinterpret_cast(self)->error_collector, name, + "symbol"); + } + + + return PyFileDescriptor_FromDescriptor(file_descriptor); +} + +static PyObject* FindExtensionByNumber(PyObject* self, PyObject* args) { + PyObject* message_descriptor; + int number; + if (!PyArg_ParseTuple(args, "Oi", &message_descriptor, &number)) { + return NULL; + } + const Descriptor* descriptor = PyMessageDescriptor_AsDescriptor( + message_descriptor); + if (descriptor == NULL) { + return NULL; + } + + const FieldDescriptor* extension_descriptor = + reinterpret_cast(self)->pool->FindExtensionByNumber( + descriptor, number); + if (extension_descriptor == NULL) { + BuildFileErrorCollector* error_collector = + reinterpret_cast( + reinterpret_cast(self)->error_collector); + if (error_collector && !error_collector->error_message.empty()) { + PyErr_Format(PyExc_KeyError, "Couldn't build file for Extension %.d\n%s", + number, error_collector->error_message.c_str()); + error_collector->Clear(); + return NULL; + } + PyErr_Format(PyExc_KeyError, "Couldn't find Extension %d", number); + return NULL; + } + + + return PyFieldDescriptor_FromDescriptor(extension_descriptor); +} + +static PyObject* FindAllExtensions(PyObject* self, PyObject* arg) { + const Descriptor* descriptor = PyMessageDescriptor_AsDescriptor(arg); + if (descriptor == NULL) { + return NULL; + } + + std::vector extensions; + reinterpret_cast(self)->pool->FindAllExtensions( + descriptor, &extensions); + + ScopedPyObjectPtr result(PyList_New(extensions.size())); + if (result == NULL) { + return NULL; + } + for (int i = 0; i < extensions.size(); i++) { + PyObject* extension = PyFieldDescriptor_FromDescriptor(extensions[i]); + if (extension == NULL) { + return NULL; + } + PyList_SET_ITEM(result.get(), i, extension); // Steals the reference. + } + return result.release(); +} + +// These functions should not exist -- the only valid way to create +// descriptors is to call Add() or AddSerializedFile(). +// But these AddDescriptor() functions were created in Python and some people +// call them, so we support them for now for compatibility. +// However we do check that the existing descriptor already exists in the pool, +// which appears to always be true for existing calls -- but then why do people +// call a function that will just be a no-op? +// TODO(amauryfa): Need to investigate further. + +static PyObject* AddFileDescriptor(PyObject* self, PyObject* descriptor) { + const FileDescriptor* file_descriptor = + PyFileDescriptor_AsDescriptor(descriptor); + if (!file_descriptor) { + return NULL; + } + if (file_descriptor != + 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()); + return NULL; + } + Py_RETURN_NONE; +} + +static PyObject* AddDescriptor(PyObject* self, PyObject* descriptor) { + const Descriptor* message_descriptor = + PyMessageDescriptor_AsDescriptor(descriptor); + if (!message_descriptor) { + return NULL; + } + if (message_descriptor != + 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()); + return NULL; + } + Py_RETURN_NONE; +} + +static PyObject* AddEnumDescriptor(PyObject* self, PyObject* descriptor) { + const EnumDescriptor* enum_descriptor = + PyEnumDescriptor_AsDescriptor(descriptor); + if (!enum_descriptor) { + return NULL; + } + if (enum_descriptor != + 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()); + return NULL; + } + Py_RETURN_NONE; +} + +static PyObject* AddExtensionDescriptor(PyObject* self, PyObject* descriptor) { + const FieldDescriptor* extension_descriptor = + PyFieldDescriptor_AsDescriptor(descriptor); + if (!extension_descriptor) { + return NULL; + } + if (extension_descriptor != + 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()); + return NULL; + } + Py_RETURN_NONE; +} + +static PyObject* AddServiceDescriptor(PyObject* self, PyObject* descriptor) { + const ServiceDescriptor* service_descriptor = + PyServiceDescriptor_AsDescriptor(descriptor); + if (!service_descriptor) { + return NULL; + } + if (service_descriptor != + 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()); + return NULL; + } + Py_RETURN_NONE; +} + +// The code below loads new Descriptors from a serialized FileDescriptorProto. +static PyObject* AddSerializedFile(PyObject* pself, PyObject* serialized_pb) { + PyDescriptorPool* self = reinterpret_cast(pself); + char* message_type; + Py_ssize_t message_len; + + if (self->database != NULL) { + PyErr_SetString( + PyExc_ValueError, + "Cannot call Add on a DescriptorPool that uses a DescriptorDatabase. " + "Add your file to the underlying database."); + return NULL; + } + if (!self->is_mutable) { + PyErr_SetString( + PyExc_ValueError, + "This DescriptorPool is not mutable and cannot add new definitions."); + return nullptr; + } + + if (PyBytes_AsStringAndSize(serialized_pb, &message_type, &message_len) < 0) { + return NULL; + } + + FileDescriptorProto file_proto; + if (!file_proto.ParseFromArray(message_type, message_len)) { + PyErr_SetString(PyExc_TypeError, "Couldn't parse file content!"); + return NULL; + } + + // If the file was already part of a C++ library, all its descriptors are in + // the underlying pool. No need to do anything else. + const FileDescriptor* generated_file = NULL; + if (self->underlay) { + generated_file = self->underlay->FindFileByName(file_proto.name()); + } + if (generated_file != NULL) { + return PyFileDescriptor_FromDescriptorWithSerializedPb( + generated_file, serialized_pb); + } + + BuildFileErrorCollector error_collector; + const FileDescriptor* descriptor = + // Pool is mutable, we can remove the "const". + const_cast(self->pool) + ->BuildFileCollectingErrors(file_proto, &error_collector); + if (descriptor == NULL) { + PyErr_Format(PyExc_TypeError, + "Couldn't build proto file into descriptor pool!\n%s", + error_collector.error_message.c_str()); + return NULL; + } + + + return PyFileDescriptor_FromDescriptorWithSerializedPb( + descriptor, serialized_pb); +} + +static PyObject* Add(PyObject* self, PyObject* file_descriptor_proto) { + ScopedPyObjectPtr serialized_pb( + PyObject_CallMethod(file_descriptor_proto, "SerializeToString", NULL)); + if (serialized_pb == NULL) { + return NULL; + } + return AddSerializedFile(self, serialized_pb.get()); +} + +static PyMethodDef Methods[] = { + { "Add", Add, METH_O, + "Adds the FileDescriptorProto and its types to this pool." }, + { "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", AddFileDescriptor, METH_O, + "No-op. Add() must have been called before." }, + { "AddDescriptor", AddDescriptor, METH_O, + "No-op. Add() must have been called before." }, + { "AddEnumDescriptor", AddEnumDescriptor, METH_O, + "No-op. Add() must have been called before." }, + { "AddExtensionDescriptor", AddExtensionDescriptor, METH_O, + "No-op. Add() must have been called before." }, + { "AddServiceDescriptor", AddServiceDescriptor, METH_O, + "No-op. Add() must have been called before." }, + + { "FindFileByName", FindFileByName, METH_O, + "Searches for a file descriptor by its .proto name." }, + { "FindMessageTypeByName", FindMessageByName, METH_O, + "Searches for a message descriptor by full name." }, + { "FindFieldByName", FindFieldByNameMethod, METH_O, + "Searches for a field descriptor by full name." }, + { "FindExtensionByName", FindExtensionByNameMethod, METH_O, + "Searches for extension descriptor by full name." }, + { "FindEnumTypeByName", FindEnumTypeByNameMethod, METH_O, + "Searches for enum type descriptor by full name." }, + { "FindOneofByName", FindOneofByNameMethod, METH_O, + "Searches for oneof descriptor by full name." }, + { "FindServiceByName", FindServiceByName, METH_O, + "Searches for service descriptor by full name." }, + { "FindMethodByName", FindMethodByName, METH_O, + "Searches for method descriptor by full name." }, + + { "FindFileContainingSymbol", FindFileContainingSymbol, METH_O, + "Gets the FileDescriptor containing the specified symbol." }, + { "FindExtensionByNumber", FindExtensionByNumber, METH_VARARGS, + "Gets the extension descriptor for the given number." }, + { "FindAllExtensions", FindAllExtensions, METH_O, + "Gets all known extensions of the given message descriptor." }, + {NULL} +}; + +} // namespace cdescriptor_pool + +PyTypeObject PyDescriptorPool_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME + ".DescriptorPool", // tp_name + sizeof(PyDescriptorPool), // tp_basicsize + 0, // tp_itemsize + cdescriptor_pool::Dealloc, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, // tp_flags + "A Descriptor Pool", // tp_doc + cdescriptor_pool::GcTraverse, // tp_traverse + cdescriptor_pool::GcClear, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + cdescriptor_pool::Methods, // tp_methods + 0, // tp_members + 0, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + cdescriptor_pool::New, // tp_new + PyObject_GC_Del, // tp_free +}; + +// This is the DescriptorPool which contains all the definitions from the +// generated _pb2.py modules. +static PyDescriptorPool* python_generated_pool = NULL; + +bool InitDescriptorPool() { + if (PyType_Ready(&PyDescriptorPool_Type) < 0) + return false; + + // The Pool of messages declared in Python libraries. + // generated_pool() contains all messages already linked in C++ libraries, and + // is used as underlay. + descriptor_pool_map = + new std::unordered_map; + python_generated_pool = cdescriptor_pool::PyDescriptorPool_NewWithUnderlay( + DescriptorPool::generated_pool()); + if (python_generated_pool == NULL) { + delete descriptor_pool_map; + return false; + } + + // Register this pool to be found for C++-generated descriptors. + descriptor_pool_map->insert( + std::make_pair(DescriptorPool::generated_pool(), + python_generated_pool)); + + return true; +} + +// The default DescriptorPool used everywhere in this module. +// Today it's the python_generated_pool. +// TODO(amauryfa): Remove all usages of this function: the pool should be +// derived from the context. +PyDescriptorPool* GetDefaultDescriptorPool() { + return python_generated_pool; +} + +PyDescriptorPool* GetDescriptorPool_FromPool(const DescriptorPool* pool) { + // Fast path for standard descriptors. + if (pool == python_generated_pool->pool || + pool == DescriptorPool::generated_pool()) { + return python_generated_pool; + } + std::unordered_map::iterator it = + descriptor_pool_map->find(pool); + if (it == descriptor_pool_map->end()) { + PyErr_SetString(PyExc_KeyError, "Unknown descriptor pool"); + return NULL; + } + return it->second; +} + +PyObject* PyDescriptorPool_FromPool(const DescriptorPool* pool) { + PyDescriptorPool* existing_pool = GetDescriptorPool_FromPool(pool); + if (existing_pool != nullptr) { + Py_INCREF(existing_pool); + return reinterpret_cast(existing_pool); + } else { + PyErr_Clear(); + } + + PyDescriptorPool* cpool = cdescriptor_pool::_CreateDescriptorPool(); + if (cpool == nullptr) { + return nullptr; + } + cpool->pool = const_cast(pool); + cpool->is_owned = false; + cpool->is_mutable = false; + cpool->underlay = nullptr; + + if (!descriptor_pool_map->insert(std::make_pair(cpool->pool, cpool)).second) { + // Should never happen -- We already checked the existence above. + PyErr_SetString(PyExc_ValueError, "DescriptorPool already registered"); + return nullptr; + } + + return reinterpret_cast(cpool); +} + +} // namespace python +} // namespace protobuf +} // namespace google diff --git a/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/message_factory.h b/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/message_factory.h new file mode 100644 index 0000000..7dfe425 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/message_factory.h @@ -0,0 +1,104 @@ +// 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_PYTHON_CPP_MESSAGE_FACTORY_H__ +#define GOOGLE_PROTOBUF_PYTHON_CPP_MESSAGE_FACTORY_H__ + +#define PY_SSIZE_T_CLEAN +#include + +#include +#include +#include + +namespace google { +namespace protobuf { +class MessageFactory; + +namespace python { + +// The (meta) type of all Messages classes. +struct CMessageClass; + +struct PyMessageFactory { + PyObject_HEAD + + // DynamicMessageFactory used to create C++ instances of messages. + // This object cache the descriptors that were used, so the DescriptorPool + // needs to get rid of it before it can delete itself. + // + // Note: A C++ MessageFactory is different from the PyMessageFactory. + // The C++ one creates messages, when the Python one creates classes. + MessageFactory* message_factory; + + // Owned reference to a Python DescriptorPool. + // This reference must stay until the message_factory is destructed. + PyDescriptorPool* pool; + + // Make our own mapping to retrieve Python classes from C++ descriptors. + // + // Descriptor pointers stored here are owned by the DescriptorPool above. + // Python references to classes are owned by this PyDescriptorPool. + typedef std::unordered_map + ClassesByMessageMap; + ClassesByMessageMap* classes_by_descriptor; +}; + +extern PyTypeObject PyMessageFactory_Type; + +namespace message_factory { + +// Creates a new MessageFactory instance. +PyMessageFactory* NewMessageFactory(PyTypeObject* type, PyDescriptorPool* pool); + +// Registers a new Python class for the given message descriptor. +// On error, returns -1 with a Python exception set. +int RegisterMessageClass(PyMessageFactory* self, + const Descriptor* message_descriptor, + CMessageClass* message_class); +// Retrieves the Python class registered with the given message descriptor, or +// fail with a TypeError. Returns a *borrowed* reference. +CMessageClass* GetMessageClass(PyMessageFactory* self, + const Descriptor* message_descriptor); +// Retrieves the Python class registered with the given message descriptor. +// The class is created if not done yet. Returns a *new* reference. +CMessageClass* GetOrCreateMessageClass(PyMessageFactory* self, + const Descriptor* message_descriptor); +} // namespace message_factory + +// Initialize objects used by this module. +// On error, returns false with a Python exception set. +bool InitMessageFactory(); + +} // namespace python +} // namespace protobuf +} // namespace google + +#endif // GOOGLE_PROTOBUF_PYTHON_CPP_MESSAGE_FACTORY_H__ diff --git a/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/repeated_composite_container.cc b/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/repeated_composite_container.cc new file mode 100644 index 0000000..2e8ff4b --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/repeated_composite_container.cc @@ -0,0 +1,601 @@ +// 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: anuraag@google.com (Anuraag Agrawal) +// Author: tibell@google.com (Johan Tibell) + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace google { +namespace protobuf { +namespace python { + +namespace repeated_composite_container { + +// --------------------------------------------------------------------- +// len() + +static Py_ssize_t Length(PyObject* pself) { + RepeatedCompositeContainer* self = + reinterpret_cast(pself); + + Message* message = self->parent->message; + return message->GetReflection()->FieldSize(*message, + self->parent_field_descriptor); +} + +// --------------------------------------------------------------------- +// add() + +PyObject* Add(RepeatedCompositeContainer* self, PyObject* args, + PyObject* kwargs) { + if (cmessage::AssureWritable(self->parent) == -1) return nullptr; + Message* message = self->parent->message; + + Message* sub_message = + message->GetReflection()->AddMessage( + message, + self->parent_field_descriptor, + self->child_message_class->py_message_factory->message_factory); + CMessage* cmsg = self->parent->BuildSubMessageFromPointer( + self->parent_field_descriptor, sub_message, self->child_message_class); + + if (cmessage::InitAttributes(cmsg, args, kwargs) < 0) { + message->GetReflection()->RemoveLast( + message, self->parent_field_descriptor); + Py_DECREF(cmsg); + return nullptr; + } + + return cmsg->AsPyObject(); +} + +static PyObject* AddMethod(PyObject* self, PyObject* args, PyObject* kwargs) { + return Add(reinterpret_cast(self), args, kwargs); +} + +// --------------------------------------------------------------------- +// append() + +static PyObject* AddMessage(RepeatedCompositeContainer* self, PyObject* value) { + cmessage::AssureWritable(self->parent); + PyObject* py_cmsg; + Message* message = self->parent->message; + const Reflection* reflection = message->GetReflection(); + py_cmsg = Add(self, nullptr, nullptr); + if (py_cmsg == nullptr) return nullptr; + CMessage* cmsg = reinterpret_cast(py_cmsg); + if (ScopedPyObjectPtr(cmessage::MergeFrom(cmsg, value)) == nullptr) { + reflection->RemoveLast( + message, self->parent_field_descriptor); + Py_DECREF(cmsg); + return nullptr; + } + return py_cmsg; +} + +static PyObject* AppendMethod(PyObject* pself, PyObject* value) { + RepeatedCompositeContainer* self = + reinterpret_cast(pself); + ScopedPyObjectPtr py_cmsg(AddMessage(self, value)); + if (py_cmsg == nullptr) { + return nullptr; + } + + Py_RETURN_NONE; +} + +// --------------------------------------------------------------------- +// insert() +static PyObject* Insert(PyObject* pself, PyObject* args) { + RepeatedCompositeContainer* self = + reinterpret_cast(pself); + + Py_ssize_t index; + PyObject* value; + if (!PyArg_ParseTuple(args, "nO", &index, &value)) { + return nullptr; + } + + ScopedPyObjectPtr py_cmsg(AddMessage(self, value)); + if (py_cmsg == nullptr) { + return nullptr; + } + + // Swap the element to right position. + Message* message = self->parent->message; + const Reflection* reflection = message->GetReflection(); + const FieldDescriptor* field_descriptor = self->parent_field_descriptor; + Py_ssize_t length = reflection->FieldSize(*message, field_descriptor) - 1; + Py_ssize_t end_index = index; + if (end_index < 0) end_index += length; + if (end_index < 0) end_index = 0; + for (Py_ssize_t i = length; i > end_index; i --) { + reflection->SwapElements(message, field_descriptor, i, i - 1); + } + + Py_RETURN_NONE; +} + +// --------------------------------------------------------------------- +// extend() + +PyObject* Extend(RepeatedCompositeContainer* self, PyObject* value) { + cmessage::AssureWritable(self->parent); + ScopedPyObjectPtr iter(PyObject_GetIter(value)); + if (iter == nullptr) { + PyErr_SetString(PyExc_TypeError, "Value must be iterable"); + return nullptr; + } + ScopedPyObjectPtr next; + while ((next.reset(PyIter_Next(iter.get()))) != nullptr) { + if (!PyObject_TypeCheck(next.get(), CMessage_Type)) { + PyErr_SetString(PyExc_TypeError, "Not a cmessage"); + return nullptr; + } + ScopedPyObjectPtr new_message(Add(self, nullptr, nullptr)); + if (new_message == nullptr) { + return nullptr; + } + CMessage* new_cmessage = reinterpret_cast(new_message.get()); + if (ScopedPyObjectPtr(cmessage::MergeFrom(new_cmessage, next.get())) == + nullptr) { + return nullptr; + } + } + if (PyErr_Occurred()) { + return nullptr; + } + Py_RETURN_NONE; +} + +static PyObject* ExtendMethod(PyObject* self, PyObject* value) { + return Extend(reinterpret_cast(self), value); +} + +PyObject* MergeFrom(RepeatedCompositeContainer* self, PyObject* other) { + return Extend(self, other); +} + +static PyObject* MergeFromMethod(PyObject* self, PyObject* other) { + return MergeFrom(reinterpret_cast(self), other); +} + +// This function does not check the bounds. +static PyObject* GetItem(RepeatedCompositeContainer* self, Py_ssize_t index, + Py_ssize_t length = -1) { + if (length == -1) { + Message* message = self->parent->message; + const Reflection* reflection = message->GetReflection(); + length = reflection->FieldSize(*message, self->parent_field_descriptor); + } + if (index < 0 || index >= length) { + PyErr_Format(PyExc_IndexError, "list index (%zd) out of range", index); + return nullptr; + } + Message* message = self->parent->message; + Message* sub_message = message->GetReflection()->MutableRepeatedMessage( + message, self->parent_field_descriptor, index); + return self->parent + ->BuildSubMessageFromPointer(self->parent_field_descriptor, sub_message, + self->child_message_class) + ->AsPyObject(); +} + +PyObject* Subscript(RepeatedCompositeContainer* self, PyObject* item) { + Message* message = self->parent->message; + const Reflection* reflection = message->GetReflection(); + Py_ssize_t length = + reflection->FieldSize(*message, self->parent_field_descriptor); + + if (PyIndex_Check(item)) { + Py_ssize_t index; + index = PyNumber_AsSsize_t(item, PyExc_IndexError); + if (index == -1 && PyErr_Occurred()) return nullptr; + if (index < 0) index += length; + return GetItem(self, index, length); + } else if (PySlice_Check(item)) { + Py_ssize_t from, to, step, slicelength, cur, i; + PyObject* result; + + if (PySlice_GetIndicesEx(item, length, &from, &to, &step, &slicelength) == + -1) { + return nullptr; + } + + if (slicelength <= 0) { + return PyList_New(0); + } else { + result = PyList_New(slicelength); + if (!result) return nullptr; + + for (cur = from, i = 0; i < slicelength; cur += step, i++) { + PyList_SET_ITEM(result, i, GetItem(self, cur, length)); + } + + return result; + } + } else { + PyErr_Format(PyExc_TypeError, "indices must be integers, not %.200s", + item->ob_type->tp_name); + return nullptr; + } +} + +static PyObject* SubscriptMethod(PyObject* self, PyObject* slice) { + return Subscript(reinterpret_cast(self), slice); +} + +int AssignSubscript(RepeatedCompositeContainer* self, + PyObject* slice, + PyObject* value) { + if (value != nullptr) { + PyErr_SetString(PyExc_TypeError, "does not support assignment"); + return -1; + } + + return cmessage::DeleteRepeatedField(self->parent, + self->parent_field_descriptor, slice); +} + +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); + Py_ssize_t len = Length(reinterpret_cast(self)); + + for (Py_ssize_t i = 0; i < len; i++) { + ScopedPyObjectPtr item(GetItem(self, i, len)); + if (item == nullptr) { + return nullptr; + } + int result = PyObject_RichCompareBool(item.get(), value, Py_EQ); + if (result < 0) { + return nullptr; + } + if (result) { + ScopedPyObjectPtr py_index(PyLong_FromSsize_t(i)); + if (AssignSubscript(self, py_index.get(), nullptr) < 0) { + return nullptr; + } + Py_RETURN_NONE; + } + } + PyErr_SetString(PyExc_ValueError, "Item to delete not in list"); + return nullptr; +} + +static PyObject* RichCompare(PyObject* pself, PyObject* other, int opid) { + RepeatedCompositeContainer* self = + reinterpret_cast(pself); + + if (!PyObject_TypeCheck(other, &RepeatedCompositeContainer_Type)) { + PyErr_SetString(PyExc_TypeError, + "Can only compare repeated composite fields " + "against other repeated composite fields."); + return nullptr; + } + if (opid == Py_EQ || opid == Py_NE) { + // TODO(anuraag): Don't make new lists just for this... + ScopedPyObjectPtr full_slice(PySlice_New(nullptr, nullptr, nullptr)); + if (full_slice == nullptr) { + return nullptr; + } + ScopedPyObjectPtr list(Subscript(self, full_slice.get())); + if (list == nullptr) { + return nullptr; + } + ScopedPyObjectPtr other_list( + Subscript(reinterpret_cast(other), + full_slice.get())); + if (other_list == nullptr) { + return nullptr; + } + return PyObject_RichCompare(list.get(), other_list.get(), opid); + } else { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } +} + +static PyObject* ToStr(PyObject* pself) { + ScopedPyObjectPtr full_slice(PySlice_New(nullptr, nullptr, nullptr)); + if (full_slice == nullptr) { + return nullptr; + } + ScopedPyObjectPtr list(Subscript( + reinterpret_cast(pself), full_slice.get())); + if (list == nullptr) { + return nullptr; + } + return PyObject_Repr(list.get()); +} + +// --------------------------------------------------------------------- +// sort() + +static void ReorderAttached(RepeatedCompositeContainer* self, + PyObject* child_list) { + Message* message = self->parent->message; + const Reflection* reflection = message->GetReflection(); + const FieldDescriptor* descriptor = self->parent_field_descriptor; + const Py_ssize_t length = Length(reinterpret_cast(self)); + + // We need to rearrange things to match python's sort order. Because there + // was already an O(n*log(n)) step in python and a bunch of reflection, we + // expect an O(n**2) step in C++ won't hurt too much. + for (Py_ssize_t i = 0; i < length; ++i) { + Message* child_message = + reinterpret_cast(PyList_GET_ITEM(child_list, i))->message; + for (Py_ssize_t j = i; j < length; ++j) { + if (child_message == + &reflection->GetRepeatedMessage(*message, descriptor, j)) { + reflection->SwapElements(message, descriptor, i, j); + break; + } + } + } +} + +// Returns 0 if successful; returns -1 and sets an exception if +// unsuccessful. +static int SortPythonMessages(RepeatedCompositeContainer* self, + PyObject* args, + PyObject* kwds) { + ScopedPyObjectPtr child_list( + PySequence_List(reinterpret_cast(self))); + if (child_list == nullptr) { + return -1; + } + ScopedPyObjectPtr m(PyObject_GetAttrString(child_list.get(), "sort")); + if (m == nullptr) return -1; + if (ScopedPyObjectPtr(PyObject_Call(m.get(), args, kwds)) == nullptr) + return -1; + ReorderAttached(self, child_list.get()); + return 0; +} + +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 != nullptr) { + PyObject* sort_func = PyDict_GetItemString(kwds, "sort_function"); + if (sort_func != nullptr) { + // Must set before deleting as sort_func is a borrowed reference + // and kwds might be the only thing keeping it alive. + PyDict_SetItemString(kwds, "cmp", sort_func); + PyDict_DelItemString(kwds, "sort_function"); + } + } + + if (SortPythonMessages(self, args, kwds) < 0) { + return nullptr; + } + Py_RETURN_NONE; +} + +// --------------------------------------------------------------------- +// reverse() + +// Returns 0 if successful; returns -1 and sets an exception if +// unsuccessful. +static int ReversePythonMessages(RepeatedCompositeContainer* self) { + ScopedPyObjectPtr child_list( + PySequence_List(reinterpret_cast(self))); + if (child_list == nullptr) { + return -1; + } + if (ScopedPyObjectPtr( + PyObject_CallMethod(child_list.get(), "reverse", nullptr)) == nullptr) + return -1; + ReorderAttached(self, child_list.get()); + return 0; +} + +static PyObject* Reverse(PyObject* pself) { + RepeatedCompositeContainer* self = + reinterpret_cast(pself); + + if (ReversePythonMessages(self) < 0) { + return nullptr; + } + Py_RETURN_NONE; +} + +// --------------------------------------------------------------------- + +static PyObject* Item(PyObject* pself, Py_ssize_t index) { + RepeatedCompositeContainer* self = + reinterpret_cast(pself); + return GetItem(self, index); +} + +static PyObject* Pop(PyObject* pself, PyObject* args) { + RepeatedCompositeContainer* self = + reinterpret_cast(pself); + + Py_ssize_t index = -1; + if (!PyArg_ParseTuple(args, "|n", &index)) { + return nullptr; + } + Py_ssize_t length = Length(pself); + if (index < 0) index += length; + PyObject* item = GetItem(self, index, length); + if (item == nullptr) { + return nullptr; + } + ScopedPyObjectPtr py_index(PyLong_FromSsize_t(index)); + if (AssignSubscript(self, py_index.get(), nullptr) < 0) { + return nullptr; + } + return item; +} + +PyObject* DeepCopy(PyObject* pself, PyObject* arg) { + return reinterpret_cast(pself)->DeepCopy(); +} + +// The private constructor of RepeatedCompositeContainer objects. +RepeatedCompositeContainer *NewContainer( + CMessage* parent, + const FieldDescriptor* parent_field_descriptor, + CMessageClass* child_message_class) { + if (!CheckFieldBelongsToMessage(parent_field_descriptor, parent->message)) { + return nullptr; + } + + RepeatedCompositeContainer* self = + reinterpret_cast( + PyType_GenericAlloc(&RepeatedCompositeContainer_Type, 0)); + if (self == nullptr) { + return nullptr; + } + + Py_INCREF(parent); + self->parent = parent; + self->parent_field_descriptor = parent_field_descriptor; + Py_INCREF(child_message_class); + self->child_message_class = child_message_class; + return self; +} + +static void Dealloc(PyObject* pself) { + RepeatedCompositeContainer* self = + reinterpret_cast(pself); + self->RemoveFromParentCache(); + Py_CLEAR(self->child_message_class); + Py_TYPE(self)->tp_free(pself); +} + +static PySequenceMethods SqMethods = { + Length, /* sq_length */ + nullptr, /* sq_concat */ + nullptr, /* sq_repeat */ + Item /* sq_item */ +}; + +static PyMappingMethods MpMethods = { + Length, /* mp_length */ + SubscriptMethod, /* mp_subscript */ + AssignSubscriptMethod, /* mp_ass_subscript */ +}; + +static PyMethodDef Methods[] = { + {"__deepcopy__", DeepCopy, METH_VARARGS, "Makes a deep copy of the class."}, + {"add", reinterpret_cast(AddMethod), + METH_VARARGS | METH_KEYWORDS, "Adds an object to the repeated container."}, + {"append", AppendMethod, METH_O, + "Appends a message to the end of the repeated container."}, + {"insert", Insert, METH_VARARGS, + "Inserts a message before the specified index."}, + {"extend", ExtendMethod, METH_O, "Adds objects to the repeated container."}, + {"pop", Pop, METH_VARARGS, + "Removes an object from the repeated container and returns it."}, + {"remove", Remove, METH_O, + "Removes an object from the repeated container."}, + {"sort", reinterpret_cast(Sort), METH_VARARGS | METH_KEYWORDS, + "Sorts the repeated container."}, + {"reverse", reinterpret_cast(Reverse), METH_NOARGS, + "Reverses elements order of the repeated container."}, + {"MergeFrom", MergeFromMethod, METH_O, + "Adds objects to the repeated container."}, + {nullptr, nullptr}}; + +} // namespace repeated_composite_container + +PyTypeObject RepeatedCompositeContainer_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME + ".RepeatedCompositeContainer", // tp_name + sizeof(RepeatedCompositeContainer), // tp_basicsize + 0, // tp_itemsize + repeated_composite_container::Dealloc, // tp_dealloc +#if PY_VERSION_HEX >= 0x03080000 + 0, // tp_vectorcall_offset +#else + nullptr, // tp_print +#endif + nullptr, // tp_getattr + nullptr, // tp_setattr + nullptr, // tp_compare + repeated_composite_container::ToStr, // tp_repr + nullptr, // tp_as_number + &repeated_composite_container::SqMethods, // tp_as_sequence + &repeated_composite_container::MpMethods, // tp_as_mapping + PyObject_HashNotImplemented, // tp_hash + nullptr, // tp_call + nullptr, // tp_str + nullptr, // tp_getattro + nullptr, // tp_setattro + nullptr, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "A Repeated scalar container", // tp_doc + nullptr, // tp_traverse + nullptr, // tp_clear + repeated_composite_container::RichCompare, // tp_richcompare + 0, // tp_weaklistoffset + nullptr, // tp_iter + nullptr, // tp_iternext + repeated_composite_container::Methods, // tp_methods + nullptr, // tp_members + nullptr, // tp_getset + nullptr, // tp_base + nullptr, // tp_dict + nullptr, // tp_descr_get + nullptr, // tp_descr_set + 0, // tp_dictoffset + nullptr, // tp_init +}; + +} // namespace python +} // namespace protobuf +} // namespace google diff --git a/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/scoped_pyobject_ptr.h b/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/scoped_pyobject_ptr.h new file mode 100644 index 0000000..985df2c --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/python/google/protobuf/pyext/scoped_pyobject_ptr.h @@ -0,0 +1,101 @@ +// 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: tibell@google.com (Johan Tibell) + +#ifndef GOOGLE_PROTOBUF_PYTHON_CPP_SCOPED_PYOBJECT_PTR_H__ +#define GOOGLE_PROTOBUF_PYTHON_CPP_SCOPED_PYOBJECT_PTR_H__ + +#include + +#define PY_SSIZE_T_CLEAN +#include +namespace google { +namespace protobuf { +namespace python { + +// Owns a python object and decrements the reference count on destruction. +// This class is not threadsafe. +template +class ScopedPythonPtr { + public: + // Takes the ownership of the specified object to ScopedPythonPtr. + // The reference count of the specified py_object is not incremented. + explicit ScopedPythonPtr(PyObjectStruct* py_object = NULL) + : ptr_(py_object) {} + + // If a PyObject is owned, decrement its reference count. + ~ScopedPythonPtr() { Py_XDECREF(ptr_); } + + // Deletes the current owned object, if any. + // Then takes ownership of a new object without incrementing the reference + // count. + // This function must be called with a reference that you own. + // this->reset(this->get()) is wrong! + // this->reset(this->release()) is OK. + PyObjectStruct* reset(PyObjectStruct* p = NULL) { + Py_XDECREF(ptr_); + ptr_ = p; + return ptr_; + } + + // Releases ownership of the object without decrementing the reference count. + // The caller now owns the returned reference. + PyObjectStruct* release() { + PyObject* p = ptr_; + ptr_ = NULL; + return p; + } + + PyObjectStruct* get() const { return ptr_; } + + PyObject* as_pyobject() const { return reinterpret_cast(ptr_); } + + // Increments the reference count of the current object. + // Should not be called when no object is held. + void inc() const { Py_INCREF(ptr_); } + + // True when a ScopedPyObjectPtr and a raw pointer refer to the same object. + // Comparison operators are non reflexive. + bool operator==(const PyObjectStruct* p) const { return ptr_ == p; } + bool operator!=(const PyObjectStruct* p) const { return ptr_ != p; } + + private: + PyObjectStruct* ptr_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ScopedPythonPtr); +}; + +typedef ScopedPythonPtr ScopedPyObjectPtr; + +} // namespace python +} // namespace protobuf +} // namespace google +#endif // GOOGLE_PROTOBUF_PYTHON_CPP_SCOPED_PYOBJECT_PTR_H__ diff --git a/tools/go-generator/cmd/generator/_protobuf/python/protobuf_distutils/protobuf_distutils/generate_py_protobufs.py b/tools/go-generator/cmd/generator/_protobuf/python/protobuf_distutils/protobuf_distutils/generate_py_protobufs.py new file mode 100644 index 0000000..88b8d45 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/python/protobuf_distutils/protobuf_distutils/generate_py_protobufs.py @@ -0,0 +1,147 @@ +# 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. + +"""Implements the generate_py_protobufs command.""" + +__author__ = 'dlj@google.com (David L. Jones)' + +import glob +import sys +import os +import distutils.spawn as spawn +from distutils.cmd import Command +from distutils.errors import DistutilsOptionError, DistutilsExecError + +class generate_py_protobufs(Command): + """Generates Python sources for .proto files.""" + + description = 'Generate Python sources for .proto files' + user_options = [ + ('extra-proto-paths=', None, + 'Additional paths to resolve imports in .proto files.'), + + ('protoc=', None, + 'Path to a specific `protoc` command to use.'), + ] + boolean_options = ['recurse'] + + def initialize_options(self): + """Sets the defaults for the command options.""" + self.source_dir = None + self.proto_root_path = None + self.extra_proto_paths = [] + self.output_dir = '.' + self.proto_files = None + self.recurse = True + self.protoc = None + + def finalize_options(self): + """Sets the final values for the command options. + + Defaults were set in `initialize_options`, but could have been changed + by command-line options or by other commands. + """ + self.ensure_dirname('source_dir') + self.ensure_string_list('extra_proto_paths') + + if self.output_dir is None: + self.output_dir = '.' + self.ensure_dirname('output_dir') + + # SUBTLE: if 'source_dir' is a subdirectory of any entry in + # 'extra_proto_paths', then in general, the shortest --proto_path prefix + # (and the longest relative .proto filenames) must be used for + # correctness. For example, consider: + # + # source_dir = 'a/b/c' + # extra_proto_paths = ['a/b', 'x/y'] + # + # In this case, we must ensure that a/b/c/d/foo.proto resolves + # canonically as c/d/foo.proto, not just d/foo.proto. Otherwise, this + # import: + # + # import "c/d/foo.proto"; + # + # would result in different FileDescriptor.name keys from "d/foo.proto". + # That will cause all the definitions in the file to be flagged as + # duplicates, with an error similar to: + # + # c/d/foo.proto: "packagename.MessageName" is already defined in file "d/foo.proto" + # + # For paths in self.proto_files, we transform them to be relative to + # self.proto_root_path, which may be different from self.source_dir. + # + # Although the order of --proto_paths is significant, shadowed filenames + # are errors: if 'a/b/c.proto' resolves to different files under two + # different --proto_path arguments, then the path is rejected as an + # error. (Implementation note: this is enforced in protoc's + # DiskSourceTree class.) + + if self.proto_root_path is None: + self.proto_root_path = os.path.normpath(self.source_dir) + for root_candidate in self.extra_proto_paths: + root_candidate = os.path.normpath(root_candidate) + if self.proto_root_path.startswith(root_candidate): + self.proto_root_path = root_candidate + if self.proto_root_path != self.source_dir: + self.announce('using computed proto_root_path: ' + self.proto_root_path, level=2) + + if not self.source_dir.startswith(self.proto_root_path): + raise DistutilsOptionError('source_dir ' + self.source_dir + + ' is not under proto_root_path ' + self.proto_root_path) + + if self.proto_files is None: + files = glob.glob(os.path.join(self.source_dir, '*.proto')) + if self.recurse: + files.extend(glob.glob(os.path.join(self.source_dir, '**', '*.proto'), recursive=True)) + self.proto_files = [f.partition(self.proto_root_path + os.path.sep)[-1] for f in files] + if not self.proto_files: + raise DistutilsOptionError('no .proto files were found under ' + self.source_dir) + + self.ensure_string_list('proto_files') + + if self.protoc is None: + self.protoc = os.getenv('PROTOC') + if self.protoc is None: + self.protoc = spawn.find_executable('protoc') + + def run(self): + # All proto file paths were adjusted in finalize_options to be relative + # to self.proto_root_path. + proto_paths = ['--proto_path=' + self.proto_root_path] + proto_paths.extend(['--proto_path=' + x for x in self.extra_proto_paths]) + + # Run protoc. It was already resolved, so don't try to resolve + # through PATH. + spawn.spawn( + [self.protoc, + '--python_out=' + self.output_dir, + ] + proto_paths + self.proto_files, + search_path=0) diff --git a/tools/go-generator/cmd/generator/_protobuf/python/setup.py b/tools/go-generator/cmd/generator/_protobuf/python/setup.py new file mode 100755 index 0000000..4a2c71c --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/python/setup.py @@ -0,0 +1,327 @@ +#! /usr/bin/env python +# +# See README for usage instructions. +from distutils import util +import fnmatch +import glob +import os +import pkg_resources +import re +import subprocess +import sys +import sysconfig +import platform + +# We must use setuptools, not distutils, because we need to use the +# namespace_packages option for the "google" package. +from setuptools import setup, Extension, find_packages + +from distutils.command.build_ext import build_ext as _build_ext +from distutils.command.build_py import build_py as _build_py +from distutils.command.clean import clean as _clean +from distutils.spawn import find_executable + +# Find the Protocol Compiler. +if 'PROTOC' in os.environ and os.path.exists(os.environ['PROTOC']): + protoc = os.environ['PROTOC'] +elif os.path.exists("../src/protoc"): + protoc = "../src/protoc" +elif os.path.exists("../src/protoc.exe"): + protoc = "../src/protoc.exe" +elif os.path.exists("../vsprojects/Debug/protoc.exe"): + protoc = "../vsprojects/Debug/protoc.exe" +elif os.path.exists("../vsprojects/Release/protoc.exe"): + protoc = "../vsprojects/Release/protoc.exe" +else: + protoc = find_executable("protoc") + + +def GetVersion(): + """Gets the version from google/protobuf/__init__.py + + Do not import google.protobuf.__init__ directly, because an installed + protobuf library may be loaded instead.""" + + with open(os.path.join('google', 'protobuf', '__init__.py')) as version_file: + exec(version_file.read(), globals()) + global __version__ + return __version__ + + +def generate_proto(source, require = True): + """Invokes the Protocol Compiler to generate a _pb2.py from the given + .proto file. Does nothing if the output already exists and is newer than + the input.""" + + if not require and not os.path.exists(source): + return + + output = source.replace(".proto", "_pb2.py").replace("../src/", "") + + if (not os.path.exists(output) or + (os.path.exists(source) and + os.path.getmtime(source) > os.path.getmtime(output))): + print("Generating %s..." % output) + + if not os.path.exists(source): + sys.stderr.write("Can't find required file: %s\n" % source) + sys.exit(-1) + + if protoc is None: + sys.stderr.write( + "protoc is not installed nor found in ../src. Please compile it " + "or install the binary package.\n") + sys.exit(-1) + + protoc_command = [ protoc, "-I../src", "-I.", "--python_out=.", source ] + if subprocess.call(protoc_command) != 0: + sys.exit(-1) + +def GenerateUnittestProtos(): + generate_proto("../src/google/protobuf/any_test.proto", False) + generate_proto("../src/google/protobuf/map_proto2_unittest.proto", False) + generate_proto("../src/google/protobuf/map_unittest.proto", False) + generate_proto("../src/google/protobuf/test_messages_proto3.proto", False) + generate_proto("../src/google/protobuf/test_messages_proto2.proto", False) + generate_proto("../src/google/protobuf/unittest_arena.proto", False) + generate_proto("../src/google/protobuf/unittest.proto", False) + generate_proto("../src/google/protobuf/unittest_custom_options.proto", False) + generate_proto("../src/google/protobuf/unittest_import.proto", False) + generate_proto("../src/google/protobuf/unittest_import_public.proto", False) + generate_proto("../src/google/protobuf/unittest_mset.proto", False) + generate_proto("../src/google/protobuf/unittest_mset_wire_format.proto", False) + generate_proto("../src/google/protobuf/unittest_no_generic_services.proto", False) + generate_proto("../src/google/protobuf/unittest_proto3_arena.proto", False) + generate_proto("../src/google/protobuf/util/json_format.proto", False) + generate_proto("../src/google/protobuf/util/json_format_proto3.proto", False) + generate_proto("google/protobuf/internal/any_test.proto", False) + generate_proto("google/protobuf/internal/descriptor_pool_test1.proto", False) + generate_proto("google/protobuf/internal/descriptor_pool_test2.proto", False) + generate_proto("google/protobuf/internal/factory_test1.proto", False) + generate_proto("google/protobuf/internal/factory_test2.proto", False) + generate_proto("google/protobuf/internal/file_options_test.proto", False) + generate_proto("google/protobuf/internal/import_test_package/inner.proto", False) + generate_proto("google/protobuf/internal/import_test_package/outer.proto", False) + generate_proto("google/protobuf/internal/missing_enum_values.proto", False) + generate_proto("google/protobuf/internal/message_set_extensions.proto", False) + generate_proto("google/protobuf/internal/more_extensions.proto", False) + generate_proto("google/protobuf/internal/more_extensions_dynamic.proto", False) + generate_proto("google/protobuf/internal/more_messages.proto", False) + generate_proto("google/protobuf/internal/no_package.proto", False) + generate_proto("google/protobuf/internal/packed_field_test.proto", False) + generate_proto("google/protobuf/internal/test_bad_identifiers.proto", False) + generate_proto("google/protobuf/internal/test_proto3_optional.proto", False) + generate_proto("google/protobuf/pyext/python.proto", False) + + +class clean(_clean): + def run(self): + # Delete generated files in the code tree. + for (dirpath, dirnames, filenames) in os.walk("."): + for filename in filenames: + filepath = os.path.join(dirpath, filename) + if filepath.endswith("_pb2.py") or filepath.endswith(".pyc") or \ + filepath.endswith(".so") or filepath.endswith(".o"): + os.remove(filepath) + # _clean is an old-style class, so super() doesn't work. + _clean.run(self) + +class build_py(_build_py): + def run(self): + # Generate necessary .proto file if it doesn't exist. + generate_proto("../src/google/protobuf/descriptor.proto") + generate_proto("../src/google/protobuf/compiler/plugin.proto") + generate_proto("../src/google/protobuf/any.proto") + generate_proto("../src/google/protobuf/api.proto") + generate_proto("../src/google/protobuf/duration.proto") + generate_proto("../src/google/protobuf/empty.proto") + generate_proto("../src/google/protobuf/field_mask.proto") + generate_proto("../src/google/protobuf/source_context.proto") + generate_proto("../src/google/protobuf/struct.proto") + generate_proto("../src/google/protobuf/timestamp.proto") + generate_proto("../src/google/protobuf/type.proto") + generate_proto("../src/google/protobuf/wrappers.proto") + GenerateUnittestProtos() + + # _build_py is an old-style class, so super() doesn't work. + _build_py.run(self) + + def find_package_modules(self, package, package_dir): + exclude = ( + "*test*", + "google/protobuf/internal/*_pb2.py", + "google/protobuf/internal/_parameterized.py", + "google/protobuf/pyext/python_pb2.py", + ) + modules = _build_py.find_package_modules(self, package, package_dir) + return [(pkg, mod, fil) for (pkg, mod, fil) in modules + if not any(fnmatch.fnmatchcase(fil, pat=pat) for pat in exclude)] + + +class build_ext(_build_ext): + + def get_ext_filename(self, ext_name): + # since python3.5, python extensions' shared libraries use a suffix that + # corresponds to the value of sysconfig.get_config_var('EXT_SUFFIX') and + # contains info about the architecture the library targets. E.g. on x64 + # linux the suffix is ".cpython-XYZ-x86_64-linux-gnu.so" When + # crosscompiling python wheels, we need to be able to override this + # suffix so that the resulting file name matches the target architecture + # and we end up with a well-formed wheel. + filename = _build_ext.get_ext_filename(self, ext_name) + orig_ext_suffix = sysconfig.get_config_var("EXT_SUFFIX") + new_ext_suffix = os.getenv("PROTOCOL_BUFFERS_OVERRIDE_EXT_SUFFIX") + if new_ext_suffix and filename.endswith(orig_ext_suffix): + filename = filename[:-len(orig_ext_suffix)] + new_ext_suffix + return filename + +class test_conformance(_build_py): + target = 'test_python' + def run(self): + # Python 2.6 dodges these extra failures. + os.environ["CONFORMANCE_PYTHON_EXTRA_FAILURES"] = ( + "--failure_list failure_list_python-post26.txt") + cmd = 'cd ../conformance && make %s' % (test_conformance.target) + status = subprocess.check_call(cmd, shell=True) + + +def get_option_from_sys_argv(option_str): + if option_str in sys.argv: + sys.argv.remove(option_str) + return True + return False + + +if __name__ == '__main__': + ext_module_list = [] + warnings_as_errors = '--warnings_as_errors' + if get_option_from_sys_argv('--cpp_implementation'): + # Link libprotobuf.a and libprotobuf-lite.a statically with the + # extension. Note that those libraries have to be compiled with + # -fPIC for this to work. + compile_static_ext = get_option_from_sys_argv('--compile_static_extension') + libraries = ['protobuf'] + extra_objects = None + if compile_static_ext: + libraries = None + extra_objects = ['../src/.libs/libprotobuf.a', + '../src/.libs/libprotobuf-lite.a'] + test_conformance.target = 'test_python_cpp' + + extra_compile_args = [] + + message_extra_link_args = None + api_implementation_link_args = None + if "darwin" in sys.platform: + if sys.version_info[0] == 2: + message_init_symbol = 'init_message' + api_implementation_init_symbol = 'init_api_implementation' + else: + message_init_symbol = 'PyInit__message' + api_implementation_init_symbol = 'PyInit__api_implementation' + message_extra_link_args = ['-Wl,-exported_symbol,_%s' % message_init_symbol] + api_implementation_link_args = ['-Wl,-exported_symbol,_%s' % api_implementation_init_symbol] + + if sys.platform != 'win32': + extra_compile_args.append('-Wno-write-strings') + extra_compile_args.append('-Wno-invalid-offsetof') + extra_compile_args.append('-Wno-sign-compare') + extra_compile_args.append('-Wno-unused-variable') + extra_compile_args.append('-std=c++11') + + if sys.platform == 'darwin': + extra_compile_args.append("-Wno-shorten-64-to-32"); + extra_compile_args.append("-Wno-deprecated-register"); + + # https://developer.apple.com/documentation/xcode_release_notes/xcode_10_release_notes + # C++ projects must now migrate to libc++ and are recommended to set a + # deployment target of macOS 10.9 or later, or iOS 7 or later. + if sys.platform == 'darwin': + mac_target = str(sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')) + if mac_target and (pkg_resources.parse_version(mac_target) < + pkg_resources.parse_version('10.9.0')): + os.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.9' + os.environ['_PYTHON_HOST_PLATFORM'] = re.sub( + r'macosx-[0-9]+\.[0-9]+-(.+)', r'macosx-10.9-\1', + util.get_platform()) + + # https://github.com/Theano/Theano/issues/4926 + if sys.platform == 'win32': + extra_compile_args.append('-D_hypot=hypot') + + # https://github.com/tpaviot/pythonocc-core/issues/48 + if sys.platform == 'win32' and '64 bit' in sys.version: + extra_compile_args.append('-DMS_WIN64') + + # MSVS default is dymanic + if (sys.platform == 'win32'): + extra_compile_args.append('/MT') + + if "clang" in os.popen('$CC --version 2> /dev/null').read(): + extra_compile_args.append('-Wno-shorten-64-to-32') + + if warnings_as_errors in sys.argv: + extra_compile_args.append('-Werror') + sys.argv.remove(warnings_as_errors) + + # C++ implementation extension + ext_module_list.extend([ + Extension( + "google.protobuf.pyext._message", + glob.glob('google/protobuf/pyext/*.cc'), + include_dirs=[".", "../src"], + libraries=libraries, + extra_objects=extra_objects, + extra_link_args=message_extra_link_args, + library_dirs=['../src/.libs'], + extra_compile_args=extra_compile_args, + ), + Extension( + "google.protobuf.internal._api_implementation", + glob.glob('google/protobuf/internal/api_implementation.cc'), + extra_compile_args=extra_compile_args + ['-DPYTHON_PROTO2_CPP_IMPL_V2'], + extra_link_args=api_implementation_link_args, + ), + ]) + os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION'] = 'cpp' + + # Keep this list of dependencies in sync with tox.ini. + install_requires = [] + + setup( + name='protobuf', + version=GetVersion(), + description='Protocol Buffers', + download_url='https://github.com/protocolbuffers/protobuf/releases', + long_description="Protocol Buffers are Google's data interchange format", + url='https://developers.google.com/protocol-buffers/', + maintainer='protobuf@googlegroups.com', + maintainer_email='protobuf@googlegroups.com', + license='BSD-3-Clause', + classifiers=[ + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.5", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + ], + namespace_packages=['google'], + packages=find_packages( + exclude=[ + 'import_test_package', + 'protobuf_distutils', + ],), + test_suite='google.protobuf.internal', + cmdclass={ + 'clean': clean, + 'build_py': build_py, + 'build_ext': build_ext, + 'test_conformance': test_conformance, + }, + install_requires=install_requires, + ext_modules=ext_module_list, + python_requires=">=3.5", + ) diff --git a/tools/go-generator/cmd/generator/_protobuf/python/stubout.py b/tools/go-generator/cmd/generator/_protobuf/python/stubout.py new file mode 100755 index 0000000..ba39104 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/python/stubout.py @@ -0,0 +1,143 @@ +#!/usr/bin/python2.4 +# +# Copyright 2008 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This file is used for testing. The original is at: +# http://code.google.com/p/pymox/ + +import inspect + + +class StubOutForTesting: + """Sample Usage: + You want os.path.exists() to always return true during testing. + + stubs = StubOutForTesting() + stubs.Set(os.path, 'exists', lambda x: 1) + ... + stubs.UnsetAll() + + The above changes os.path.exists into a lambda that returns 1. Once + the ... part of the code finishes, the UnsetAll() looks up the old value + of os.path.exists and restores it. + + """ + def __init__(self): + self.cache = [] + self.stubs = [] + + def __del__(self): + self.SmartUnsetAll() + self.UnsetAll() + + def SmartSet(self, obj, attr_name, new_attr): + """Replace obj.attr_name with new_attr. This method is smart and works + at the module, class, and instance level while preserving proper + inheritance. It will not stub out C types however unless that has been + explicitly allowed by the type. + + This method supports the case where attr_name is a staticmethod or a + classmethod of obj. + + Notes: + - If obj is an instance, then it is its class that will actually be + stubbed. Note that the method Set() does not do that: if obj is + an instance, it (and not its class) will be stubbed. + - The stubbing is using the builtin getattr and setattr. So, the __get__ + and __set__ will be called when stubbing (TODO: A better idea would + probably be to manipulate obj.__dict__ instead of getattr() and + setattr()). + + Raises AttributeError if the attribute cannot be found. + """ + if (inspect.ismodule(obj) or + (not inspect.isclass(obj) and obj.__dict__.has_key(attr_name))): + orig_obj = obj + orig_attr = getattr(obj, attr_name) + + else: + if not inspect.isclass(obj): + mro = list(inspect.getmro(obj.__class__)) + else: + mro = list(inspect.getmro(obj)) + + mro.reverse() + + orig_attr = None + + for cls in mro: + try: + orig_obj = cls + orig_attr = getattr(obj, attr_name) + except AttributeError: + continue + + if orig_attr is None: + raise AttributeError("Attribute not found.") + + # Calling getattr() on a staticmethod transforms it to a 'normal' function. + # We need to ensure that we put it back as a staticmethod. + old_attribute = obj.__dict__.get(attr_name) + if old_attribute is not None and isinstance(old_attribute, staticmethod): + orig_attr = staticmethod(orig_attr) + + self.stubs.append((orig_obj, attr_name, orig_attr)) + setattr(orig_obj, attr_name, new_attr) + + def SmartUnsetAll(self): + """Reverses all the SmartSet() calls, restoring things to their original + definition. Its okay to call SmartUnsetAll() repeatedly, as later calls + have no effect if no SmartSet() calls have been made. + + """ + self.stubs.reverse() + + for args in self.stubs: + setattr(*args) + + self.stubs = [] + + def Set(self, parent, child_name, new_child): + """Replace child_name's old definition with new_child, in the context + of the given parent. The parent could be a module when the child is a + function at module scope. Or the parent could be a class when a class' + method is being replaced. The named child is set to new_child, while + the prior definition is saved away for later, when UnsetAll() is called. + + This method supports the case where child_name is a staticmethod or a + classmethod of parent. + """ + old_child = getattr(parent, child_name) + + old_attribute = parent.__dict__.get(child_name) + if old_attribute is not None and isinstance(old_attribute, staticmethod): + old_child = staticmethod(old_child) + + self.cache.append((parent, old_child, child_name)) + setattr(parent, child_name, new_child) + + def UnsetAll(self): + """Reverses all the Set() calls, restoring things to their original + definition. Its okay to call UnsetAll() repeatedly, as later calls have + no effect if no Set() calls have been made. + + """ + # Undo calls to Set() in reverse order, in case Set() was called on the + # same arguments repeatedly (want the original call to be last one undone) + self.cache.reverse() + + for (parent, old_child, child_name) in self.cache: + setattr(parent, child_name, old_child) + self.cache = [] diff --git a/tools/go-generator/cmd/generator/_protobuf/python/tox.ini b/tools/go-generator/cmd/generator/_protobuf/python/tox.ini new file mode 100644 index 0000000..7142b86 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/python/tox.ini @@ -0,0 +1,21 @@ +[tox] +envlist = + py{35,36,37,38,39,310}-{cpp,python} + +[testenv] +usedevelop=true +passenv = + CC KOKORO_BUILD_ID KOKORO_BUILD_NUMBER +setenv = + cpp: LD_LIBRARY_PATH={toxinidir}/../src/.libs + cpp: DYLD_LIBRARY_PATH={toxinidir}/../src/.libs + cpp: PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=cpp + python: PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python +commands = + python setup.py -q build_py + python: python setup.py -q build + py{35,36,37,38,39,310}-cpp: python setup.py -q build --cpp_implementation --warnings_as_errors --compile_static_extension + python: python setup.py -q test -q + cpp: python setup.py -q test -q --cpp_implementation + python: python setup.py -q test_conformance + cpp: python setup.py -q test_conformance --cpp_implementation diff --git a/tools/go-generator/cmd/generator/_protobuf/ruby/compatibility_tests/v3.0.0/README.md b/tools/go-generator/cmd/generator/_protobuf/ruby/compatibility_tests/v3.0.0/README.md new file mode 100644 index 0000000..06d981c --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/ruby/compatibility_tests/v3.0.0/README.md @@ -0,0 +1,5 @@ +# Protobuf Ruby Compatibility Tests + +This directory contains a snapshot of protobuf ruby 3.0.0 unittest code and +test scripts used to verifies whether the latest version of protobuf is +still compatible with 3.0.0 generated code. diff --git a/tools/go-generator/cmd/generator/_protobuf/ruby/compatibility_tests/v3.0.0/tests/basic.rb b/tools/go-generator/cmd/generator/_protobuf/ruby/compatibility_tests/v3.0.0/tests/basic.rb new file mode 100755 index 0000000..7228144 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/ruby/compatibility_tests/v3.0.0/tests/basic.rb @@ -0,0 +1,1276 @@ +#!/usr/bin/ruby + +require 'google/protobuf' +require 'test/unit' + +# ------------- generated code -------------- + +module BasicTest + pool = Google::Protobuf::DescriptorPool.new + pool.build do + add_message "Foo" do + optional :bar, :message, 1, "Bar" + repeated :baz, :message, 2, "Baz" + end + + add_message "Bar" do + optional :msg, :string, 1 + end + + add_message "Baz" do + optional :msg, :string, 1 + end + + add_message "TestMessage" do + optional :optional_int32, :int32, 1 + optional :optional_int64, :int64, 2 + optional :optional_uint32, :uint32, 3 + optional :optional_uint64, :uint64, 4 + optional :optional_bool, :bool, 5 + optional :optional_float, :float, 6 + optional :optional_double, :double, 7 + optional :optional_string, :string, 8 + optional :optional_bytes, :bytes, 9 + optional :optional_msg, :message, 10, "TestMessage2" + optional :optional_enum, :enum, 11, "TestEnum" + + repeated :repeated_int32, :int32, 12 + repeated :repeated_int64, :int64, 13 + repeated :repeated_uint32, :uint32, 14 + repeated :repeated_uint64, :uint64, 15 + repeated :repeated_bool, :bool, 16 + repeated :repeated_float, :float, 17 + repeated :repeated_double, :double, 18 + repeated :repeated_string, :string, 19 + repeated :repeated_bytes, :bytes, 20 + repeated :repeated_msg, :message, 21, "TestMessage2" + repeated :repeated_enum, :enum, 22, "TestEnum" + end + add_message "TestMessage2" do + optional :foo, :int32, 1 + end + + add_message "Recursive1" do + optional :foo, :message, 1, "Recursive2" + end + add_message "Recursive2" do + optional :foo, :message, 1, "Recursive1" + end + + add_enum "TestEnum" do + value :Default, 0 + value :A, 1 + value :B, 2 + value :C, 3 + end + + add_message "BadFieldNames" do + optional :dup, :int32, 1 + optional :class, :int32, 2 + end + + add_message "MapMessage" do + map :map_string_int32, :string, :int32, 1 + map :map_string_msg, :string, :message, 2, "TestMessage2" + end + add_message "MapMessageWireEquiv" do + repeated :map_string_int32, :message, 1, "MapMessageWireEquiv_entry1" + repeated :map_string_msg, :message, 2, "MapMessageWireEquiv_entry2" + end + add_message "MapMessageWireEquiv_entry1" do + optional :key, :string, 1 + optional :value, :int32, 2 + end + add_message "MapMessageWireEquiv_entry2" do + optional :key, :string, 1 + optional :value, :message, 2, "TestMessage2" + end + + add_message "OneofMessage" do + oneof :my_oneof do + optional :a, :string, 1 + optional :b, :int32, 2 + optional :c, :message, 3, "TestMessage2" + optional :d, :enum, 4, "TestEnum" + end + end + end + + Foo = pool.lookup("Foo").msgclass + Bar = pool.lookup("Bar").msgclass + Baz = pool.lookup("Baz").msgclass + TestMessage = pool.lookup("TestMessage").msgclass + TestMessage2 = pool.lookup("TestMessage2").msgclass + Recursive1 = pool.lookup("Recursive1").msgclass + Recursive2 = pool.lookup("Recursive2").msgclass + TestEnum = pool.lookup("TestEnum").enummodule + BadFieldNames = pool.lookup("BadFieldNames").msgclass + MapMessage = pool.lookup("MapMessage").msgclass + MapMessageWireEquiv = pool.lookup("MapMessageWireEquiv").msgclass + MapMessageWireEquiv_entry1 = + pool.lookup("MapMessageWireEquiv_entry1").msgclass + MapMessageWireEquiv_entry2 = + pool.lookup("MapMessageWireEquiv_entry2").msgclass + OneofMessage = pool.lookup("OneofMessage").msgclass + +# ------------ test cases --------------- + + class MessageContainerTest < Test::Unit::TestCase + + def test_defaults + m = TestMessage.new + assert m.optional_int32 == 0 + assert m.optional_int64 == 0 + assert m.optional_uint32 == 0 + assert m.optional_uint64 == 0 + assert m.optional_bool == false + assert m.optional_float == 0.0 + assert m.optional_double == 0.0 + assert m.optional_string == "" + assert m.optional_bytes == "" + assert m.optional_msg == nil + assert m.optional_enum == :Default + end + + def test_setters + m = TestMessage.new + m.optional_int32 = -42 + assert m.optional_int32 == -42 + m.optional_int64 = -0x1_0000_0000 + assert m.optional_int64 == -0x1_0000_0000 + m.optional_uint32 = 0x9000_0000 + assert m.optional_uint32 == 0x9000_0000 + m.optional_uint64 = 0x9000_0000_0000_0000 + assert m.optional_uint64 == 0x9000_0000_0000_0000 + m.optional_bool = true + assert m.optional_bool == true + m.optional_float = 0.5 + assert m.optional_float == 0.5 + m.optional_double = 0.5 + m.optional_string = "hello" + assert m.optional_string == "hello" + m.optional_bytes = "world".encode!('ASCII-8BIT') + assert m.optional_bytes == "world" + m.optional_msg = TestMessage2.new(:foo => 42) + assert m.optional_msg == TestMessage2.new(:foo => 42) + m.optional_msg = nil + assert m.optional_msg == nil + end + + def test_ctor_args + m = TestMessage.new(:optional_int32 => -42, + :optional_msg => TestMessage2.new, + :optional_enum => :C, + :repeated_string => ["hello", "there", "world"]) + assert m.optional_int32 == -42 + assert m.optional_msg.class == TestMessage2 + assert m.repeated_string.length == 3 + assert m.optional_enum == :C + assert m.repeated_string[0] == "hello" + assert m.repeated_string[1] == "there" + assert m.repeated_string[2] == "world" + end + + def test_inspect + m = TestMessage.new(:optional_int32 => -42, + :optional_enum => :A, + :optional_msg => TestMessage2.new, + :repeated_string => ["hello", "there", "world"]) + expected = ', optional_enum: :A, repeated_int32: [], repeated_int64: [], repeated_uint32: [], repeated_uint64: [], repeated_bool: [], repeated_float: [], repeated_double: [], repeated_string: ["hello", "there", "world"], repeated_bytes: [], repeated_msg: [], repeated_enum: []>' + assert_equal expected, m.inspect + end + + def test_hash + m1 = TestMessage.new(:optional_int32 => 42) + m2 = TestMessage.new(:optional_int32 => 102) + assert m1.hash != 0 + assert m2.hash != 0 + # relying on the randomness here -- if hash function changes and we are + # unlucky enough to get a collision, then change the values above. + assert m1.hash != m2.hash + end + + def test_unknown_field_errors + e = assert_raise NoMethodError do + TestMessage.new.hello + end + assert_match(/hello/, e.message) + + e = assert_raise NoMethodError do + TestMessage.new.hello = "world" + end + assert_match(/hello/, e.message) + end + + def test_initialization_map_errors + e = assert_raise ArgumentError do + TestMessage.new(:hello => "world") + end + assert_match(/hello/, e.message) + + e = assert_raise ArgumentError do + MapMessage.new(:map_string_int32 => "hello") + end + assert_equal e.message, "Expected Hash object as initializer value for map field 'map_string_int32' (given String)." + + e = assert_raise ArgumentError do + TestMessage.new(:repeated_uint32 => "hello") + end + assert_equal e.message, "Expected array as initializer value for repeated field 'repeated_uint32' (given String)." + end + + def test_type_errors + m = TestMessage.new + + # Use rescue to allow subclasses of error + success = false + begin + m.optional_int32 = "hello" + rescue TypeError + success = true + end + assert(success) + + success = false + begin + m.optional_string = nil + rescue TypeError + success = true + end + assert(success) + + success = false + begin + m.optional_bool = 42 + rescue TypeError + success = true + end + assert(success) + + success = false + begin + m.optional_msg = TestMessage.new # expects TestMessage2 + rescue TypeError + success = true + end + assert(success) + + success = false + begin + m.repeated_int32 = [] # needs RepeatedField + rescue TypeError + success = true + end + assert(success) + + success = false + begin + m.repeated_msg.push TestMessage.new + rescue TypeError + success = true + end + assert(success) + end + + def test_string_encoding + m = TestMessage.new + + # Assigning a normal (ASCII or UTF8) string to a bytes field, or + # ASCII-8BIT to a string field will convert to the proper encoding. + m.optional_bytes = "Test string ASCII".encode!('ASCII') + assert m.optional_bytes.frozen? + assert_equal Encoding::ASCII_8BIT, m.optional_bytes.encoding + assert_equal "Test string ASCII", m.optional_bytes + + assert_raise Encoding::UndefinedConversionError do + m.optional_bytes = "Test string UTF-8 \u0100".encode!('UTF-8') + end + + assert_raise Encoding::UndefinedConversionError do + m.optional_string = ["FFFF"].pack('H*') + end + + # "Ordinary" use case. + m.optional_bytes = ["FFFF"].pack('H*') + m.optional_string = "\u0100" + + # strings are immutable so we can't do this, but serialize should catch it. + m.optional_string = "asdf".encode!('UTF-8') + assert_raise do + m.optional_string.encode!('ASCII-8BIT') + end + end + + def test_rptfield_int32 + l = Google::Protobuf::RepeatedField.new(:int32) + assert l.count == 0 + l = Google::Protobuf::RepeatedField.new(:int32, [1, 2, 3]) + assert l.count == 3 + assert_equal [1, 2, 3], l + assert_equal l, [1, 2, 3] + l.push 4 + assert l == [1, 2, 3, 4] + dst_list = [] + l.each { |val| dst_list.push val } + assert dst_list == [1, 2, 3, 4] + assert l.to_a == [1, 2, 3, 4] + assert l[0] == 1 + assert l[3] == 4 + l[0] = 5 + assert l == [5, 2, 3, 4] + + l2 = l.dup + assert l == l2 + assert l.object_id != l2.object_id + l2.push 6 + assert l.count == 4 + assert l2.count == 5 + + assert l.inspect == '[5, 2, 3, 4]' + + l.concat([7, 8, 9]) + assert l == [5, 2, 3, 4, 7, 8, 9] + assert l.pop == 9 + assert l == [5, 2, 3, 4, 7, 8] + + success = false + begin + m = TestMessage.new + l.push m + rescue TypeError + success = true + end + assert(success) + + m = TestMessage.new + m.repeated_int32 = l + assert m.repeated_int32 == [5, 2, 3, 4, 7, 8] + assert m.repeated_int32.object_id == l.object_id + l.push 42 + assert m.repeated_int32.pop == 42 + + l3 = l + l.dup + assert l3.count == l.count * 2 + l.count.times do |i| + assert l3[i] == l[i] + assert l3[l.count + i] == l[i] + end + + l.clear + assert l.count == 0 + l += [1, 2, 3, 4] + l.replace([5, 6, 7, 8]) + assert l == [5, 6, 7, 8] + + l4 = Google::Protobuf::RepeatedField.new(:int32) + l4[5] = 42 + assert l4 == [0, 0, 0, 0, 0, 42] + + l4 << 100 + assert l4 == [0, 0, 0, 0, 0, 42, 100] + l4 << 101 << 102 + assert l4 == [0, 0, 0, 0, 0, 42, 100, 101, 102] + end + + def test_parent_rptfield + #make sure we set the RepeatedField and can add to it + m = TestMessage.new + assert m.repeated_string == [] + m.repeated_string << 'ok' + m.repeated_string.push('ok2') + assert m.repeated_string == ['ok', 'ok2'] + m.repeated_string += ['ok3'] + assert m.repeated_string == ['ok', 'ok2', 'ok3'] + end + + def test_rptfield_msg + l = Google::Protobuf::RepeatedField.new(:message, TestMessage) + l.push TestMessage.new + assert l.count == 1 + + success = false + begin + l.push TestMessage2.new + rescue TypeError + success = true + end + assert(success) + + success = false + begin + l.push 42 + rescue TypeError + success = true + end + assert(success) + + l2 = l.dup + assert l2[0] == l[0] + assert l2[0].object_id == l[0].object_id + + l2 = Google::Protobuf.deep_copy(l) + assert l2[0] == l[0] + assert l2[0].object_id != l[0].object_id + + l3 = l + l2 + assert l3.count == 2 + assert l3[0] == l[0] + assert l3[1] == l2[0] + l3[0].optional_int32 = 1000 + assert l[0].optional_int32 == 1000 + + new_msg = TestMessage.new(:optional_int32 => 200) + l4 = l + [new_msg] + assert l4.count == 2 + new_msg.optional_int32 = 1000 + assert l4[1].optional_int32 == 1000 + end + + def test_rptfield_enum + l = Google::Protobuf::RepeatedField.new(:enum, TestEnum) + l.push :A + l.push :B + l.push :C + assert l.count == 3 + assert_raise RangeError do + l.push :D + end + assert l[0] == :A + + l.push 4 + assert l[3] == 4 + end + + def test_rptfield_initialize + assert_raise ArgumentError do + l = Google::Protobuf::RepeatedField.new + end + assert_raise ArgumentError do + l = Google::Protobuf::RepeatedField.new(:message) + end + assert_raise ArgumentError do + l = Google::Protobuf::RepeatedField.new([1, 2, 3]) + end + assert_raise ArgumentError do + l = Google::Protobuf::RepeatedField.new(:message, [TestMessage2.new]) + end + end + + def test_rptfield_array_ducktyping + l = Google::Protobuf::RepeatedField.new(:int32) + length_methods = %w(count length size) + length_methods.each do |lm| + assert l.send(lm) == 0 + end + # out of bounds returns a nil + assert l[0] == nil + assert l[1] == nil + assert l[-1] == nil + l.push 4 + length_methods.each do |lm| + assert l.send(lm) == 1 + end + assert l[0] == 4 + assert l[1] == nil + assert l[-1] == 4 + assert l[-2] == nil + + l.push 2 + length_methods.each do |lm| + assert l.send(lm) == 2 + end + assert l[0] == 4 + assert l[1] == 2 + assert l[2] == nil + assert l[-1] == 2 + assert l[-2] == 4 + assert l[-3] == nil + + #adding out of scope will backfill with empty objects + end + + def test_map_basic + # allowed key types: + # :int32, :int64, :uint32, :uint64, :bool, :string, :bytes. + + m = Google::Protobuf::Map.new(:string, :int32) + m["asdf"] = 1 + assert m["asdf"] == 1 + m["jkl;"] = 42 + assert m == { "jkl;" => 42, "asdf" => 1 } + assert m.has_key?("asdf") + assert !m.has_key?("qwerty") + assert m.length == 2 + + m2 = m.dup + assert m == m2 + assert m.hash != 0 + assert m.hash == m2.hash + + collected = {} + m.each { |k,v| collected[v] = k } + assert collected == { 42 => "jkl;", 1 => "asdf" } + + assert m.delete("asdf") == 1 + assert !m.has_key?("asdf") + assert m["asdf"] == nil + assert !m.has_key?("asdf") + + # We only assert on inspect value when there is one map entry because the + # order in which elements appear is unspecified (depends on the internal + # hash function). We don't want a brittle test. + assert m.inspect == "{\"jkl;\"=>42}" + + assert m.keys == ["jkl;"] + assert m.values == [42] + + m.clear + assert m.length == 0 + assert m == {} + + success = false + begin + m[1] = 1 + rescue TypeError + success = true + end + assert(success) + + assert_raise RangeError do + m["asdf"] = 0x1_0000_0000 + end + end + + def test_map_ctor + m = Google::Protobuf::Map.new(:string, :int32, + {"a" => 1, "b" => 2, "c" => 3}) + assert m == {"a" => 1, "c" => 3, "b" => 2} + end + + def test_map_keytypes + m = Google::Protobuf::Map.new(:int32, :int32) + m[1] = 42 + m[-1] = 42 + assert_raise RangeError do + m[0x8000_0000] = 1 + end + + success = false + begin + m["asdf"] = 1 + rescue TypeError + success = true + end + assert(success) + + m = Google::Protobuf::Map.new(:int64, :int32) + m[0x1000_0000_0000_0000] = 1 + assert_raise RangeError do + m[0x1_0000_0000_0000_0000] = 1 + end + + success = false + begin + m["asdf"] = 1 + rescue TypeError + success = true + end + assert(success) + + m = Google::Protobuf::Map.new(:uint32, :int32) + m[0x8000_0000] = 1 + assert_raise RangeError do + m[0x1_0000_0000] = 1 + end + assert_raise RangeError do + m[-1] = 1 + end + + m = Google::Protobuf::Map.new(:uint64, :int32) + m[0x8000_0000_0000_0000] = 1 + assert_raise RangeError do + m[0x1_0000_0000_0000_0000] = 1 + end + assert_raise RangeError do + m[-1] = 1 + end + + m = Google::Protobuf::Map.new(:bool, :int32) + m[true] = 1 + m[false] = 2 + + success = false + begin + m[1] = 1 + rescue TypeError + success = true + end + assert(success) + + success = false + begin + m["asdf"] = 1 + rescue TypeError + success = true + end + assert(success) + + m = Google::Protobuf::Map.new(:string, :int32) + m["asdf"] = 1 + success = false + begin + m[1] = 1 + rescue TypeError + success = true + end + assert(success) + assert_raise Encoding::UndefinedConversionError do + bytestring = ["FFFF"].pack("H*") + m[bytestring] = 1 + end + + m = Google::Protobuf::Map.new(:bytes, :int32) + bytestring = ["FFFF"].pack("H*") + m[bytestring] = 1 + # Allowed -- we will automatically convert to ASCII-8BIT. + m["asdf"] = 1 + success = false + begin + m[1] = 1 + rescue TypeError + success = true + end + assert(success) + end + + def test_map_msg_enum_valuetypes + m = Google::Protobuf::Map.new(:string, :message, TestMessage) + m["asdf"] = TestMessage.new + success = false + begin + m["jkl;"] = TestMessage2.new + rescue TypeError + success = true + end + assert(success) + + m = Google::Protobuf::Map.new( + :string, :message, TestMessage, + { "a" => TestMessage.new(:optional_int32 => 42), + "b" => TestMessage.new(:optional_int32 => 84) }) + assert m.length == 2 + assert m.values.map{|msg| msg.optional_int32}.sort == [42, 84] + + m = Google::Protobuf::Map.new(:string, :enum, TestEnum, + { "x" => :A, "y" => :B, "z" => :C }) + assert m.length == 3 + assert m["z"] == :C + m["z"] = 2 + assert m["z"] == :B + m["z"] = 4 + assert m["z"] == 4 + assert_raise RangeError do + m["z"] = :Z + end + assert_raise RangeError do + m["z"] = "z" + end + end + + def test_map_dup_deep_copy + m = Google::Protobuf::Map.new( + :string, :message, TestMessage, + { "a" => TestMessage.new(:optional_int32 => 42), + "b" => TestMessage.new(:optional_int32 => 84) }) + + m2 = m.dup + assert m == m2 + assert m.object_id != m2.object_id + assert m["a"].object_id == m2["a"].object_id + assert m["b"].object_id == m2["b"].object_id + + m2 = Google::Protobuf.deep_copy(m) + assert m == m2 + assert m.object_id != m2.object_id + assert m["a"].object_id != m2["a"].object_id + assert m["b"].object_id != m2["b"].object_id + end + + def test_map_field + m = MapMessage.new + assert m.map_string_int32 == {} + assert m.map_string_msg == {} + + m = MapMessage.new( + :map_string_int32 => {"a" => 1, "b" => 2}, + :map_string_msg => {"a" => TestMessage2.new(:foo => 1), + "b" => TestMessage2.new(:foo => 2)}) + assert m.map_string_int32.keys.sort == ["a", "b"] + assert m.map_string_int32["a"] == 1 + assert m.map_string_msg["b"].foo == 2 + + m.map_string_int32["c"] = 3 + assert m.map_string_int32["c"] == 3 + m.map_string_msg["c"] = TestMessage2.new(:foo => 3) + assert m.map_string_msg["c"] == TestMessage2.new(:foo => 3) + m.map_string_msg.delete("b") + m.map_string_msg.delete("c") + assert m.map_string_msg == { "a" => TestMessage2.new(:foo => 1) } + + success = false + begin + m.map_string_msg["e"] = TestMessage.new # wrong value type + rescue TypeError + success = true + end + assert(success) + # ensure nothing was added by the above + assert m.map_string_msg == { "a" => TestMessage2.new(:foo => 1) } + + m.map_string_int32 = Google::Protobuf::Map.new(:string, :int32) + success = false + begin + m.map_string_int32 = Google::Protobuf::Map.new(:string, :int64) + rescue TypeError + success = true + end + assert(success) + success = false + begin + m.map_string_int32 = {} + rescue TypeError + success = true + end + assert(success) + + success = false + begin + m = MapMessage.new(:map_string_int32 => { 1 => "I am not a number" }) + rescue TypeError + success = true + end + assert(success) + end + + def test_map_encode_decode + m = MapMessage.new( + :map_string_int32 => {"a" => 1, "b" => 2}, + :map_string_msg => {"a" => TestMessage2.new(:foo => 1), + "b" => TestMessage2.new(:foo => 2)}) + m2 = MapMessage.decode(MapMessage.encode(m)) + assert m == m2 + + m3 = MapMessageWireEquiv.decode(MapMessage.encode(m)) + assert m3.map_string_int32.length == 2 + + kv = {} + m3.map_string_int32.map { |msg| kv[msg.key] = msg.value } + assert kv == {"a" => 1, "b" => 2} + + kv = {} + m3.map_string_msg.map { |msg| kv[msg.key] = msg.value } + assert kv == {"a" => TestMessage2.new(:foo => 1), + "b" => TestMessage2.new(:foo => 2)} + end + + def test_oneof_descriptors + d = OneofMessage.descriptor + o = d.lookup_oneof("my_oneof") + assert o != nil + assert o.class == Google::Protobuf::OneofDescriptor + assert o.name == "my_oneof" + oneof_count = 0 + d.each_oneof{ |oneof| + oneof_count += 1 + assert oneof == o + } + assert oneof_count == 1 + assert o.count == 4 + field_names = o.map{|f| f.name}.sort + assert field_names == ["a", "b", "c", "d"] + end + + def test_oneof + d = OneofMessage.new + assert d.a == "" + assert d.b == 0 + assert d.c == nil + assert d.d == :Default + assert d.my_oneof == nil + + d.a = "hi" + assert d.a == "hi" + assert d.b == 0 + assert d.c == nil + assert d.d == :Default + assert d.my_oneof == :a + + d.b = 42 + assert d.a == "" + assert d.b == 42 + assert d.c == nil + assert d.d == :Default + assert d.my_oneof == :b + + d.c = TestMessage2.new(:foo => 100) + assert d.a == "" + assert d.b == 0 + assert d.c.foo == 100 + assert d.d == :Default + assert d.my_oneof == :c + + d.d = :C + assert d.a == "" + assert d.b == 0 + assert d.c == nil + assert d.d == :C + assert d.my_oneof == :d + + d2 = OneofMessage.decode(OneofMessage.encode(d)) + assert d2 == d + + encoded_field_a = OneofMessage.encode(OneofMessage.new(:a => "string")) + encoded_field_b = OneofMessage.encode(OneofMessage.new(:b => 1000)) + encoded_field_c = OneofMessage.encode( + OneofMessage.new(:c => TestMessage2.new(:foo => 1))) + encoded_field_d = OneofMessage.encode(OneofMessage.new(:d => :B)) + + d3 = OneofMessage.decode( + encoded_field_c + encoded_field_a + encoded_field_d) + assert d3.a == "" + assert d3.b == 0 + assert d3.c == nil + assert d3.d == :B + + d4 = OneofMessage.decode( + encoded_field_c + encoded_field_a + encoded_field_d + + encoded_field_c) + assert d4.a == "" + assert d4.b == 0 + assert d4.c.foo == 1 + assert d4.d == :Default + + d5 = OneofMessage.new(:a => "hello") + assert d5.a == "hello" + d5.a = nil + assert d5.a == "" + assert OneofMessage.encode(d5) == '' + assert d5.my_oneof == nil + end + + def test_enum_field + m = TestMessage.new + assert m.optional_enum == :Default + m.optional_enum = :A + assert m.optional_enum == :A + assert_raise RangeError do + m.optional_enum = :ASDF + end + m.optional_enum = 1 + assert m.optional_enum == :A + m.optional_enum = 100 + assert m.optional_enum == 100 + end + + def test_dup + m = TestMessage.new + m.optional_string = "hello" + m.optional_int32 = 42 + tm1 = TestMessage2.new(:foo => 100) + tm2 = TestMessage2.new(:foo => 200) + m.repeated_msg.push tm1 + assert m.repeated_msg[-1] == tm1 + m.repeated_msg.push tm2 + assert m.repeated_msg[-1] == tm2 + m2 = m.dup + assert m == m2 + m.optional_int32 += 1 + assert m != m2 + assert m.repeated_msg[0] == m2.repeated_msg[0] + assert m.repeated_msg[0].object_id == m2.repeated_msg[0].object_id + end + + def test_deep_copy + m = TestMessage.new(:optional_int32 => 42, + :repeated_msg => [TestMessage2.new(:foo => 100)]) + m2 = Google::Protobuf.deep_copy(m) + assert m == m2 + assert m.repeated_msg == m2.repeated_msg + assert m.repeated_msg.object_id != m2.repeated_msg.object_id + assert m.repeated_msg[0].object_id != m2.repeated_msg[0].object_id + end + + def test_eq + m = TestMessage.new(:optional_int32 => 42, + :repeated_int32 => [1, 2, 3]) + m2 = TestMessage.new(:optional_int32 => 43, + :repeated_int32 => [1, 2, 3]) + assert m != m2 + end + + def test_enum_lookup + assert TestEnum::A == 1 + assert TestEnum::B == 2 + assert TestEnum::C == 3 + + assert TestEnum::lookup(1) == :A + assert TestEnum::lookup(2) == :B + assert TestEnum::lookup(3) == :C + + assert TestEnum::resolve(:A) == 1 + assert TestEnum::resolve(:B) == 2 + assert TestEnum::resolve(:C) == 3 + end + + def test_parse_serialize + m = TestMessage.new(:optional_int32 => 42, + :optional_string => "hello world", + :optional_enum => :B, + :repeated_string => ["a", "b", "c"], + :repeated_int32 => [42, 43, 44], + :repeated_enum => [:A, :B, :C, 100], + :repeated_msg => [TestMessage2.new(:foo => 1), + TestMessage2.new(:foo => 2)]) + data = TestMessage.encode m + m2 = TestMessage.decode data + assert m == m2 + + data = Google::Protobuf.encode m + m2 = Google::Protobuf.decode(TestMessage, data) + assert m == m2 + end + + def test_encode_decode_helpers + m = TestMessage.new(:optional_string => 'foo', :repeated_string => ['bar1', 'bar2']) + assert_equal 'foo', m.optional_string + assert_equal ['bar1', 'bar2'], m.repeated_string + + json = m.to_json + m2 = TestMessage.decode_json(json) + assert_equal 'foo', m2.optional_string + assert_equal ['bar1', 'bar2'], m2.repeated_string + if RUBY_PLATFORM != "java" + assert m2.optional_string.frozen? + assert m2.repeated_string[0].frozen? + end + + proto = m.to_proto + m2 = TestMessage.decode(proto) + assert_equal 'foo', m2.optional_string + assert_equal ['bar1', 'bar2'], m2.repeated_string + end + + def test_protobuf_encode_decode_helpers + m = TestMessage.new(:optional_string => 'foo', :repeated_string => ['bar1', 'bar2']) + encoded_msg = Google::Protobuf.encode(m) + assert_equal m.to_proto, encoded_msg + + decoded_msg = Google::Protobuf.decode(TestMessage, encoded_msg) + assert_equal TestMessage.decode(m.to_proto), decoded_msg + end + + def test_protobuf_encode_decode_json_helpers + m = TestMessage.new(:optional_string => 'foo', :repeated_string => ['bar1', 'bar2']) + encoded_msg = Google::Protobuf.encode_json(m) + assert_equal m.to_json, encoded_msg + + decoded_msg = Google::Protobuf.decode_json(TestMessage, encoded_msg) + assert_equal TestMessage.decode_json(m.to_json), decoded_msg + end + + def test_to_h + m = TestMessage.new(:optional_bool => true, :optional_double => -10.100001, :optional_string => 'foo', :repeated_string => ['bar1', 'bar2']) + expected_result = { + :optional_bool=>true, + :optional_bytes=>"", + :optional_double=>-10.100001, + :optional_enum=>:Default, + :optional_float=>0.0, + :optional_int32=>0, + :optional_int64=>0, + :optional_msg=>nil, + :optional_string=>"foo", + :optional_uint32=>0, + :optional_uint64=>0, + :repeated_bool=>[], + :repeated_bytes=>[], + :repeated_double=>[], + :repeated_enum=>[], + :repeated_float=>[], + :repeated_int32=>[], + :repeated_int64=>[], + :repeated_msg=>[], + :repeated_string=>["bar1", "bar2"], + :repeated_uint32=>[], + :repeated_uint64=>[] + } + assert_equal expected_result, m.to_h + end + + + def test_def_errors + s = Google::Protobuf::DescriptorPool.new + success = false + begin + s.build do + # enum with no default (integer value 0) + add_enum "MyEnum" do + value :A, 1 + end + end + rescue TypeError + success = true + end + assert(success) + success = false + begin + s.build do + # message with required field (unsupported in proto3) + add_message "MyMessage" do + required :foo, :int32, 1 + end + end + rescue TypeError + success = true + end + assert(success) + end + + def test_corecursive + # just be sure that we can instantiate types with corecursive field-type + # references. + m = Recursive1.new(:foo => Recursive2.new(:foo => Recursive1.new)) + assert Recursive1.descriptor.lookup("foo").subtype == + Recursive2.descriptor + assert Recursive2.descriptor.lookup("foo").subtype == + Recursive1.descriptor + + serialized = Recursive1.encode(m) + m2 = Recursive1.decode(serialized) + assert m == m2 + end + + def test_serialize_cycle + m = Recursive1.new(:foo => Recursive2.new) + m.foo.foo = m + assert_raise RuntimeError do + serialized = Recursive1.encode(m) + end + end + + def test_bad_field_names + m = BadFieldNames.new(:dup => 1, :class => 2) + m2 = m.dup + assert m == m2 + assert m['dup'] == 1 + assert m['class'] == 2 + m['dup'] = 3 + assert m['dup'] == 3 + end + + def test_int_ranges + m = TestMessage.new + + m.optional_int32 = 0 + m.optional_int32 = -0x8000_0000 + m.optional_int32 = +0x7fff_ffff + m.optional_int32 = 1.0 + m.optional_int32 = -1.0 + m.optional_int32 = 2e9 + assert_raise RangeError do + m.optional_int32 = -0x8000_0001 + end + assert_raise RangeError do + m.optional_int32 = +0x8000_0000 + end + assert_raise RangeError do + m.optional_int32 = +0x1000_0000_0000_0000_0000_0000 # force Bignum + end + assert_raise RangeError do + m.optional_int32 = 1e12 + end + assert_raise RangeError do + m.optional_int32 = 1.5 + end + + m.optional_uint32 = 0 + m.optional_uint32 = +0xffff_ffff + m.optional_uint32 = 1.0 + m.optional_uint32 = 4e9 + assert_raise RangeError do + m.optional_uint32 = -1 + end + assert_raise RangeError do + m.optional_uint32 = -1.5 + end + assert_raise RangeError do + m.optional_uint32 = -1.5e12 + end + assert_raise RangeError do + m.optional_uint32 = -0x1000_0000_0000_0000 + end + assert_raise RangeError do + m.optional_uint32 = +0x1_0000_0000 + end + assert_raise RangeError do + m.optional_uint32 = +0x1000_0000_0000_0000_0000_0000 # force Bignum + end + assert_raise RangeError do + m.optional_uint32 = 1e12 + end + assert_raise RangeError do + m.optional_uint32 = 1.5 + end + + m.optional_int64 = 0 + m.optional_int64 = -0x8000_0000_0000_0000 + m.optional_int64 = +0x7fff_ffff_ffff_ffff + m.optional_int64 = 1.0 + m.optional_int64 = -1.0 + m.optional_int64 = 8e18 + m.optional_int64 = -8e18 + assert_raise RangeError do + m.optional_int64 = -0x8000_0000_0000_0001 + end + assert_raise RangeError do + m.optional_int64 = +0x8000_0000_0000_0000 + end + assert_raise RangeError do + m.optional_int64 = +0x1000_0000_0000_0000_0000_0000 # force Bignum + end + assert_raise RangeError do + m.optional_int64 = 1e50 + end + assert_raise RangeError do + m.optional_int64 = 1.5 + end + + m.optional_uint64 = 0 + m.optional_uint64 = +0xffff_ffff_ffff_ffff + m.optional_uint64 = 1.0 + m.optional_uint64 = 16e18 + assert_raise RangeError do + m.optional_uint64 = -1 + end + assert_raise RangeError do + m.optional_uint64 = -1.5 + end + assert_raise RangeError do + m.optional_uint64 = -1.5e12 + end + assert_raise RangeError do + m.optional_uint64 = -0x1_0000_0000_0000_0000 + end + assert_raise RangeError do + m.optional_uint64 = +0x1_0000_0000_0000_0000 + end + assert_raise RangeError do + m.optional_uint64 = +0x1000_0000_0000_0000_0000_0000 # force Bignum + end + assert_raise RangeError do + m.optional_uint64 = 1e50 + end + assert_raise RangeError do + m.optional_uint64 = 1.5 + end + end + + def test_stress_test + m = TestMessage.new + m.optional_int32 = 42 + m.optional_int64 = 0x100000000 + m.optional_string = "hello world" + 10.times do m.repeated_msg.push TestMessage2.new(:foo => 42) end + 10.times do m.repeated_string.push "hello world" end + + data = TestMessage.encode(m) + + l = 0 + 10_000.times do + m = TestMessage.decode(data) + data_new = TestMessage.encode(m) + assert data_new == data + data = data_new + end + end + + def test_reflection + m = TestMessage.new(:optional_int32 => 1234) + msgdef = m.class.descriptor + assert msgdef.class == Google::Protobuf::Descriptor + assert msgdef.any? {|field| field.name == "optional_int32"} + optional_int32 = msgdef.lookup "optional_int32" + assert optional_int32.class == Google::Protobuf::FieldDescriptor + assert optional_int32 != nil + assert optional_int32.name == "optional_int32" + assert optional_int32.type == :int32 + optional_int32.set(m, 5678) + assert m.optional_int32 == 5678 + m.optional_int32 = 1000 + assert optional_int32.get(m) == 1000 + + optional_msg = msgdef.lookup "optional_msg" + assert optional_msg.subtype == TestMessage2.descriptor + + optional_msg.set(m, optional_msg.subtype.msgclass.new) + + assert msgdef.msgclass == TestMessage + + optional_enum = msgdef.lookup "optional_enum" + assert optional_enum.subtype == TestEnum.descriptor + assert optional_enum.subtype.class == Google::Protobuf::EnumDescriptor + optional_enum.subtype.each do |k, v| + # set with integer, check resolution to symbolic name + optional_enum.set(m, v) + assert optional_enum.get(m) == k + end + end + + def test_json + # TODO: Fix JSON in JRuby version. + return if RUBY_PLATFORM == "java" + m = TestMessage.new(:optional_int32 => 1234, + :optional_int64 => -0x1_0000_0000, + :optional_uint32 => 0x8000_0000, + :optional_uint64 => 0xffff_ffff_ffff_ffff, + :optional_bool => true, + :optional_float => 1.0, + :optional_double => -1e100, + :optional_string => "Test string", + :optional_bytes => ["FFFFFFFF"].pack('H*'), + :optional_msg => TestMessage2.new(:foo => 42), + :repeated_int32 => [1, 2, 3, 4], + :repeated_string => ["a", "b", "c"], + :repeated_bool => [true, false, true, false], + :repeated_msg => [TestMessage2.new(:foo => 1), + TestMessage2.new(:foo => 2)]) + + json_text = TestMessage.encode_json(m) + m2 = TestMessage.decode_json(json_text) + assert m == m2 + + # Crash case from GitHub issue 283. + bar = Bar.new(msg: "bar") + baz1 = Baz.new(msg: "baz") + baz2 = Baz.new(msg: "quux") + Foo.encode_json(Foo.new) + Foo.encode_json(Foo.new(bar: bar)) + Foo.encode_json(Foo.new(bar: bar, baz: [baz1, baz2])) + end + + def test_json_maps + # TODO: Fix JSON in JRuby version. + return if RUBY_PLATFORM == "java" + m = MapMessage.new(:map_string_int32 => {"a" => 1}) + expected = '{"mapStringInt32":{"a":1},"mapStringMsg":{}}' + expected_preserve = '{"map_string_int32":{"a":1},"map_string_msg":{}}' + assert_equal expected, MapMessage.encode_json(m, :emit_defaults => true) + + json = MapMessage.encode_json(m, :preserve_proto_fieldnames => true, :emit_defaults => true) + assert_equal expected_preserve, json + + m2 = MapMessage.decode_json(MapMessage.encode_json(m)) + assert m == m2 + end + end +end diff --git a/tools/go-generator/cmd/generator/_protobuf/ruby/compatibility_tests/v3.0.0/tests/repeated_field_test.rb b/tools/go-generator/cmd/generator/_protobuf/ruby/compatibility_tests/v3.0.0/tests/repeated_field_test.rb new file mode 100755 index 0000000..4f70f52 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/ruby/compatibility_tests/v3.0.0/tests/repeated_field_test.rb @@ -0,0 +1,630 @@ +#!/usr/bin/ruby + +require 'google/protobuf' +require 'test/unit' + +class RepeatedFieldTest < Test::Unit::TestCase + + def test_acts_like_enumerator + m = TestMessage.new + (Enumerable.instance_methods - TestMessage.new.repeated_string.methods).each do |method_name| + assert m.repeated_string.respond_to?(method_name) == true, "does not respond to #{method_name}" + end + end + + def test_acts_like_an_array + m = TestMessage.new + arr_methods = ([].methods - TestMessage.new.repeated_string.methods) + # jRuby additions to the Array class that we can ignore + arr_methods -= [ :indices, :iter_for_each, :iter_for_each_index, + :iter_for_each_with_index, :dimensions, :copy_data, :copy_data_simple, + :nitems, :iter_for_reverse_each, :indexes, :append, :prepend] + arr_methods -= [:union, :difference, :filter!] + arr_methods -= [:intersection, :deconstruct] # ruby 2.7 methods we can ignore + arr_methods.each do |method_name| + assert m.repeated_string.respond_to?(method_name) == true, "does not respond to #{method_name}" + end + end + + def test_first + m = TestMessage.new + repeated_field_names(TestMessage).each do |field_name| + assert_nil m.send(field_name).first + end + fill_test_msg(m) + assert_equal -10, m.repeated_int32.first + assert_equal -1_000_000, m.repeated_int64.first + assert_equal 10, m.repeated_uint32.first + assert_equal 1_000_000, m.repeated_uint64.first + assert_equal true, m.repeated_bool.first + assert_equal -1.01, m.repeated_float.first.round(2) + assert_equal -1.0000000000001, m.repeated_double.first + assert_equal 'foo', m.repeated_string.first + assert_equal "bar".encode!('ASCII-8BIT'), m.repeated_bytes.first + assert_equal TestMessage2.new(:foo => 1), m.repeated_msg.first + assert_equal :A, m.repeated_enum.first + end + + + def test_last + m = TestMessage.new + repeated_field_names(TestMessage).each do |field_name| + assert_nil m.send(field_name).first + end + fill_test_msg(m) + assert_equal -11, m.repeated_int32.last + assert_equal -1_000_001, m.repeated_int64.last + assert_equal 11, m.repeated_uint32.last + assert_equal 1_000_001, m.repeated_uint64.last + assert_equal false, m.repeated_bool.last + assert_equal -1.02, m.repeated_float.last.round(2) + assert_equal -1.0000000000002, m.repeated_double.last + assert_equal 'bar', m.repeated_string.last + assert_equal "foo".encode!('ASCII-8BIT'), m.repeated_bytes.last + assert_equal TestMessage2.new(:foo => 2), m.repeated_msg.last + assert_equal :B, m.repeated_enum.last + end + + + def test_pop + m = TestMessage.new + repeated_field_names(TestMessage).each do |field_name| + assert_nil m.send(field_name).pop + end + fill_test_msg(m) + + assert_equal -11, m.repeated_int32.pop + assert_equal -10, m.repeated_int32.pop + assert_equal -1_000_001, m.repeated_int64.pop + assert_equal -1_000_000, m.repeated_int64.pop + assert_equal 11, m.repeated_uint32.pop + assert_equal 10, m.repeated_uint32.pop + assert_equal 1_000_001, m.repeated_uint64.pop + assert_equal 1_000_000, m.repeated_uint64.pop + assert_equal false, m.repeated_bool.pop + assert_equal true, m.repeated_bool.pop + assert_equal -1.02, m.repeated_float.pop.round(2) + assert_equal -1.01, m.repeated_float.pop.round(2) + assert_equal -1.0000000000002, m.repeated_double.pop + assert_equal -1.0000000000001, m.repeated_double.pop + assert_equal 'bar', m.repeated_string.pop + assert_equal 'foo', m.repeated_string.pop + assert_equal "foo".encode!('ASCII-8BIT'), m.repeated_bytes.pop + assert_equal "bar".encode!('ASCII-8BIT'), m.repeated_bytes.pop + assert_equal TestMessage2.new(:foo => 2), m.repeated_msg.pop + assert_equal TestMessage2.new(:foo => 1), m.repeated_msg.pop + assert_equal :B, m.repeated_enum.pop + assert_equal :A, m.repeated_enum.pop + repeated_field_names(TestMessage).each do |field_name| + assert_nil m.send(field_name).pop + end + + fill_test_msg(m) + assert_equal ['bar', 'foo'], m.repeated_string.pop(2) + assert_nil m.repeated_string.pop + end + + + def test_each + m = TestMessage.new + 5.times{|i| m.repeated_string << 'string' } + count = 0 + m.repeated_string.each do |val| + assert_equal 'string', val + count += 1 + end + assert_equal 5, count + result = m.repeated_string.each{|val| val + '_junk'} + assert_equal ['string'] * 5, result + end + + + def test_empty? + m = TestMessage.new + assert_equal true, m.repeated_string.empty? + m.repeated_string << 'foo' + assert_equal false, m.repeated_string.empty? + m.repeated_string << 'bar' + assert_equal false, m.repeated_string.empty? + end + + def test_array_accessor + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr[1] + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr[-2] + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr[20] + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr[1, 2] + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr[0..2] + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr[-1, 1] + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr[10, 12] + end + end + + def test_array_settor + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr[1] = 'junk' + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr[-2] = 'snappy' + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr[3] = '' + end + # slight deviation; we are strongly typed, and nil is not allowed + # for string types; + m.repeated_string[5] = 'spacious' + assert_equal ["foo", "snappy", "baz", "", "", "spacious"], m.repeated_string + + #make sure it sests the default types for other fields besides strings + %w(repeated_int32 repeated_int64 repeated_uint32 repeated_uint64).each do |field_name| + m.send(field_name)[3] = 10 + assert_equal [0,0,0,10], m.send(field_name) + end + m.repeated_float[3] = 10.1 + #wonky mri float handling + assert_equal [0,0,0], m.repeated_float.to_a[0..2] + assert_equal 10.1, m.repeated_float[3].round(1) + m.repeated_double[3] = 10.1 + assert_equal [0,0,0,10.1], m.repeated_double + m.repeated_bool[3] = true + assert_equal [false, false, false, true], m.repeated_bool + m.repeated_bytes[3] = "bar".encode!('ASCII-8BIT') + assert_equal ['', '', '', "bar".encode!('ASCII-8BIT')], m.repeated_bytes + m.repeated_msg[3] = TestMessage2.new(:foo => 1) + assert_equal [nil, nil, nil, TestMessage2.new(:foo => 1)], m.repeated_msg + m.repeated_enum[3] = :A + assert_equal [:Default, :Default, :Default, :A], m.repeated_enum + + # check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + # arr[20] = 'spacious' + # end + # TODO: accessor doesn't allow other ruby-like methods + # check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + # arr[1, 2] = 'fizz' + # end + # check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + # arr[0..2] = 'buzz' + # end + end + + def test_push + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.push('fizz') + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr << 'fizz' + end + #TODO: push should support multiple + # check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + # arr.push('fizz', 'buzz') + # end + end + + def test_clear + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.clear + end + end + + def test_concat + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + m.repeated_string.concat(['fizz', 'buzz']) + assert_equal %w(foo bar baz fizz buzz), m.repeated_string + #TODO: concat should return the orig array + # check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + # arr.concat(['fizz', 'buzz']) + # end + end + + def test_equal + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + assert_equal reference_arr, m.repeated_string + reference_arr << 'fizz' + assert_not_equal reference_arr, m.repeated_string + m.repeated_string << 'fizz' + assert_equal reference_arr, m.repeated_string + end + + def test_hash + # just a sanity check + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + assert m.repeated_string.hash.is_a?(Integer) + hash = m.repeated_string.hash + assert_equal hash, m.repeated_string.hash + m.repeated_string << 'j' + assert_not_equal hash, m.repeated_string.hash + end + + def test_plus + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr + ['fizz', 'buzz'] + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr += ['fizz', 'buzz'] + end + end + + def test_replace + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.replace(['fizz', 'buzz']) + end + end + + def test_to_a + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.to_a + end + end + + def test_to_ary + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.to_ary + end + end + + # emulate Array behavior + ########################## + + def test_collect! + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.collect!{|x| x + "!" } + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.collect!.with_index{|x, i| x[0...i] } + end + end + + def test_delete + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.delete('bar') + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.delete('nope') + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.delete('nope'){'within'} + end + end + + def test_delete_at + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.delete_at(2) + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.delete_at(10) + end + end + + def test_fill + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.fill("x") + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.fill("z", 2, 2) + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.fill("y", 0..1) + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.fill { |i| (i*i).to_s } + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.fill(-2) { |i| (i*i*i).to_s } + end + end + + def test_flatten! + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.flatten! + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.flatten!(1) + end + end + + def test_insert + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.insert(2, 'fizz') + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.insert(3, 'fizz', 'buzz', 'bazz') + end + end + + def test_inspect + m = TestMessage.new + assert_equal '[]', m.repeated_string.inspect + m.repeated_string << 'foo' + assert_equal m.repeated_string.to_a.inspect, m.repeated_string.inspect + m.repeated_string << 'bar' + assert_equal m.repeated_string.to_a.inspect, m.repeated_string.inspect + end + + def test_reverse! + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.reverse! + end + end + + def test_rotate! + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.rotate! + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.rotate!(2) + end + end + + def test_select! + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.select! { |v| v =~ /[aeiou]/ } + end + end + + def test_shift + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + + # should return an element + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.shift + end + # should return an array + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.shift(2) + end + # should return nil + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.shift + end + end + + def test_shuffle! + m = TestMessage.new + m.repeated_string += %w(foo bar baz) + orig_repeated_string = m.repeated_string.clone + result = m.repeated_string.shuffle! + assert_equal m.repeated_string, result + # NOTE: sometimes it doesn't change the order... + # assert_not_equal m.repeated_string.to_a, orig_repeated_string.to_a + end + + def test_slice! + m = TestMessage.new + reference_arr = %w(foo bar baz bar fizz buzz) + m.repeated_string += reference_arr.clone + + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.slice!(2) + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.slice!(1,2) + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.slice!(0..1) + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.slice!(10) + end + end + + def test_sort! + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.sort! + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.sort! { |x,y| y <=> x } + end + end + + def test_sort_by! + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.sort_by! + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.sort_by!(&:hash) + end + end + + def test_uniq! + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.uniq! + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.uniq!{|s| s[0] } + end + end + + def test_unshift + m = TestMessage.new + reference_arr = %w(foo bar baz) + m.repeated_string += reference_arr.clone + + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.unshift('1') + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.unshift('a', 'b') + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr.unshift('') + end + end + + + ##### HELPER METHODS + + def check_self_modifying_method(repeated_field, ref_array) + expected_result = yield(ref_array) + actual_result = yield(repeated_field) + if expected_result.is_a?(Enumerator) + assert_equal expected_result.to_a, actual_result.to_a + else + assert_equal expected_result, actual_result + end + assert_equal ref_array, repeated_field + end + + + def repeated_field_names(klass) + klass.descriptor.find_all{|f| f.label == :repeated}.map(&:name) + end + + + def fill_test_msg(test_msg) + test_msg.repeated_int32 += [-10, -11] + test_msg.repeated_int64 += [-1_000_000, -1_000_001] + test_msg.repeated_uint32 += [10, 11] + test_msg.repeated_uint64 += [1_000_000, 1_000_001] + test_msg.repeated_bool += [true, false] + test_msg.repeated_float += [-1.01, -1.02] + test_msg.repeated_double += [-1.0000000000001, -1.0000000000002] + test_msg.repeated_string += %w(foo bar) + test_msg.repeated_bytes += ["bar".encode!('ASCII-8BIT'), "foo".encode!('ASCII-8BIT')] + test_msg.repeated_msg << TestMessage2.new(:foo => 1) + test_msg.repeated_msg << TestMessage2.new(:foo => 2) + test_msg.repeated_enum << :A + test_msg.repeated_enum << :B + end + + + pool = Google::Protobuf::DescriptorPool.new + pool.build do + + add_message "TestMessage" do + optional :optional_int32, :int32, 1 + optional :optional_int64, :int64, 2 + optional :optional_uint32, :uint32, 3 + optional :optional_uint64, :uint64, 4 + optional :optional_bool, :bool, 5 + optional :optional_float, :float, 6 + optional :optional_double, :double, 7 + optional :optional_string, :string, 8 + optional :optional_bytes, :bytes, 9 + optional :optional_msg, :message, 10, "TestMessage2" + optional :optional_enum, :enum, 11, "TestEnum" + + repeated :repeated_int32, :int32, 12 + repeated :repeated_int64, :int64, 13 + repeated :repeated_uint32, :uint32, 14 + repeated :repeated_uint64, :uint64, 15 + repeated :repeated_bool, :bool, 16 + repeated :repeated_float, :float, 17 + repeated :repeated_double, :double, 18 + repeated :repeated_string, :string, 19 + repeated :repeated_bytes, :bytes, 20 + repeated :repeated_msg, :message, 21, "TestMessage2" + repeated :repeated_enum, :enum, 22, "TestEnum" + end + add_message "TestMessage2" do + optional :foo, :int32, 1 + end + + add_enum "TestEnum" do + value :Default, 0 + value :A, 1 + value :B, 2 + value :C, 3 + end + end + + TestMessage = pool.lookup("TestMessage").msgclass + TestMessage2 = pool.lookup("TestMessage2").msgclass + TestEnum = pool.lookup("TestEnum").enummodule + + +end diff --git a/tools/go-generator/cmd/generator/_protobuf/ruby/compatibility_tests/v3.0.0/tests/stress.rb b/tools/go-generator/cmd/generator/_protobuf/ruby/compatibility_tests/v3.0.0/tests/stress.rb new file mode 100755 index 0000000..082d5e2 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/ruby/compatibility_tests/v3.0.0/tests/stress.rb @@ -0,0 +1,38 @@ +#!/usr/bin/ruby + +require 'google/protobuf' +require 'test/unit' + +module StressTest + pool = Google::Protobuf::DescriptorPool.new + pool.build do + add_message "TestMessage" do + optional :a, :int32, 1 + repeated :b, :message, 2, "M" + end + add_message "M" do + optional :foo, :string, 1 + end + end + + TestMessage = pool.lookup("TestMessage").msgclass + M = pool.lookup("M").msgclass + + class StressTest < Test::Unit::TestCase + def get_msg + TestMessage.new(:a => 1000, + :b => [M.new(:foo => "hello"), + M.new(:foo => "world")]) + end + def test_stress + m = get_msg + data = TestMessage.encode(m) + 100_000.times do + mnew = TestMessage.decode(data) + mnew = mnew.dup + assert_equal mnew.inspect, m.inspect + assert TestMessage.encode(mnew) == data + end + end + end +end diff --git a/tools/go-generator/cmd/generator/_protobuf/ruby/ext/google/protobuf_c/message.h b/tools/go-generator/cmd/generator/_protobuf/ruby/ext/google/protobuf_c/message.h new file mode 100644 index 0000000..b409650 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/ruby/ext/google/protobuf_c/message.h @@ -0,0 +1,104 @@ +// 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 RUBY_PROTOBUF_MESSAGE_H_ +#define RUBY_PROTOBUF_MESSAGE_H_ + +#include + +#include "protobuf.h" +#include "ruby-upb.h" + +// Gets the underlying upb_Message* and upb_MessageDef for the given Ruby +// message wrapper. Requires that |value| is indeed a message object. +const upb_Message* Message_Get(VALUE value, const upb_MessageDef** m); + +// Like Message_Get(), but checks that the object is not frozen and returns a +// mutable pointer. +upb_Message* Message_GetMutable(VALUE value, const upb_MessageDef** m); + +// Returns the Arena object for this message. +VALUE Message_GetArena(VALUE value); + +// Converts |value| into a upb_Message value of the expected upb_MessageDef +// type, raising an error if this is not possible. Used when assigning |value| +// to a field of another message, which means the message must be of a +// particular type. +// +// This will perform automatic conversions in some cases (for example, Time -> +// Google::Protobuf::Timestamp). If any new message is created, it will be +// created on |arena|, and any existing message will have its arena fused with +// |arena|. +const upb_Message* Message_GetUpbMessage(VALUE value, const upb_MessageDef* m, + const char* name, upb_Arena* arena); + +// Gets or constructs a Ruby wrapper object for the given message. The wrapper +// object will reference |arena| and ensure that it outlives this object. +VALUE Message_GetRubyWrapper(upb_Message* msg, const upb_MessageDef* m, + VALUE arena); + +// Gets the given field from this message. +VALUE Message_getfield(VALUE _self, const upb_FieldDef* f); + +// Implements #inspect for this message, printing the text to |b|. +void Message_PrintMessage(StringBuilder* b, const upb_Message* msg, + const upb_MessageDef* m); + +// Returns a hash value for the given message. +uint64_t Message_Hash(const upb_Message* msg, const upb_MessageDef* m, + uint64_t seed); + +// Returns a deep copy of the given message. +upb_Message* Message_deep_copy(const upb_Message* msg, const upb_MessageDef* m, + upb_Arena* arena); + +// Returns true if these two messages are equal. +bool Message_Equal(const upb_Message* m1, const upb_Message* m2, + const upb_MessageDef* m); + +// Checks that this Ruby object is a message, and raises an exception if not. +void Message_CheckClass(VALUE klass); + +// Returns a new Hash object containing the contents of this message. +VALUE Scalar_CreateHash(upb_MessageValue val, TypeInfo type_info); + +// Creates a message class or enum module for this descriptor, respectively. +VALUE build_class_from_descriptor(VALUE descriptor); +VALUE build_module_from_enumdesc(VALUE _enumdesc); + +// Returns the Descriptor/EnumDescriptor for the given message class or enum +// module, respectively. Returns nil if this is not a message class or enum +// module. +VALUE MessageOrEnum_GetDescriptor(VALUE klass); + +// Call at startup to register all types in this module. +void Message_register(VALUE protobuf); + +#endif // RUBY_PROTOBUF_MESSAGE_H_ diff --git a/tools/go-generator/cmd/generator/_protobuf/ruby/lib/google/protobuf/repeated_field.rb b/tools/go-generator/cmd/generator/_protobuf/ruby/lib/google/protobuf/repeated_field.rb new file mode 100644 index 0000000..bc9699f --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/ruby/lib/google/protobuf/repeated_field.rb @@ -0,0 +1,188 @@ +# 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. + +require 'forwardable' + +# +# This class makes RepeatedField act (almost-) like a Ruby Array. +# It has convenience methods that extend the core C or Java based +# methods. +# +# This is a best-effort to mirror Array behavior. Two comments: +# 1) patches always welcome :) +# 2) if performance is an issue, feel free to rewrite the method +# in jruby and C. The source code has plenty of examples +# +# KNOWN ISSUES +# - #[]= doesn't allow less used approaches such as `arr[1, 2] = 'fizz'` +# - #concat should return the orig array +# - #push should accept multiple arguments and push them all at the same time +# +module Google + module Protobuf + class RepeatedField + extend Forwardable + + # methods defined in C or Java: + # + + # [], at + # []= + # concat + # clear + # dup, clone + # each + # push, << + # replace + # length, size + # == + # to_ary, to_a + # also all enumerable + # + # NOTE: using delegators rather than method_missing to make the + # relationship explicit instead of implicit + def_delegators :to_ary, + :&, :*, :-, :'<=>', + :assoc, :bsearch, :bsearch_index, :combination, :compact, :count, + :cycle, :dig, :drop, :drop_while, :eql?, :fetch, :find_index, :flatten, + :include?, :index, :inspect, :join, + :pack, :permutation, :product, :pretty_print, :pretty_print_cycle, + :rassoc, :repeated_combination, :repeated_permutation, :reverse, + :rindex, :rotate, :sample, :shuffle, :shelljoin, + :to_s, :transpose, :uniq, :| + + + def first(n=nil) + n ? self[0...n] : self[0] + end + + + def last(n=nil) + n ? self[(self.size-n-1)..-1] : self[-1] + end + + + def pop(n=nil) + if n + results = [] + n.times{ results << pop_one } + return results + else + return pop_one + end + end + + + def empty? + self.size == 0 + end + + # array aliases into enumerable + alias_method :each_index, :each_with_index + alias_method :slice, :[] + alias_method :values_at, :select + alias_method :map, :collect + + + class << self + def define_array_wrapper_method(method_name) + define_method(method_name) do |*args, &block| + arr = self.to_a + result = arr.send(method_name, *args) + self.replace(arr) + return result if result + return block ? block.call : result + end + end + private :define_array_wrapper_method + + + def define_array_wrapper_with_result_method(method_name) + define_method(method_name) do |*args, &block| + # result can be an Enumerator, Array, or nil + # Enumerator can sometimes be returned if a block is an optional argument and it is not passed in + # nil usually specifies that no change was made + result = self.to_a.send(method_name, *args, &block) + if result + new_arr = result.to_a + self.replace(new_arr) + if result.is_a?(Enumerator) + # generate a fresh enum; rewinding the exiting one, in Ruby 2.2, will + # reset the enum with the same length, but all the #next calls will + # return nil + result = new_arr.to_enum + # generate a wrapper enum so any changes which occur by a chained + # enum can be captured + ie = ProxyingEnumerator.new(self, result) + result = ie.to_enum + end + end + result + end + end + private :define_array_wrapper_with_result_method + end + + + %w(delete delete_at shift slice! unshift).each do |method_name| + define_array_wrapper_method(method_name) + end + + + %w(collect! compact! delete_if fill flatten! insert reverse! + rotate! select! shuffle! sort! sort_by! uniq!).each do |method_name| + define_array_wrapper_with_result_method(method_name) + end + alias_method :keep_if, :select! + alias_method :map!, :collect! + alias_method :reject!, :delete_if + + + # propagates changes made by user of enumerator back to the original repeated field. + # This only applies in cases where the calling function which created the enumerator, + # such as #sort!, modifies itself rather than a new array, such as #sort + class ProxyingEnumerator < Struct.new(:repeated_field, :external_enumerator) + def each(*args, &block) + results = [] + external_enumerator.each_with_index do |val, i| + result = yield(val) + results << result + #nil means no change occurred from yield; usually occurs when #to_a is called + if result + repeated_field[i] = result if result != val + end + end + results + end + end + + + end + end +end diff --git a/tools/go-generator/cmd/generator/_protobuf/ruby/lib/google/protobuf/well_known_types.rb b/tools/go-generator/cmd/generator/_protobuf/ruby/lib/google/protobuf/well_known_types.rb new file mode 100755 index 0000000..2d06ca2 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/ruby/lib/google/protobuf/well_known_types.rb @@ -0,0 +1,240 @@ +#!/usr/bin/ruby +# 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. + +require 'google/protobuf/any_pb' +require 'google/protobuf/duration_pb' +require 'google/protobuf/field_mask_pb' +require 'google/protobuf/struct_pb' +require 'google/protobuf/timestamp_pb' + +module Google + module Protobuf + + Any.class_eval do + def self.pack(msg, type_url_prefix='type.googleapis.com/') + any = self.new + any.pack(msg, type_url_prefix) + any + end + + def pack(msg, type_url_prefix='type.googleapis.com/') + if type_url_prefix.empty? or type_url_prefix[-1] != '/' then + self.type_url = "#{type_url_prefix}/#{msg.class.descriptor.name}" + else + self.type_url = "#{type_url_prefix}#{msg.class.descriptor.name}" + end + self.value = msg.to_proto + end + + def unpack(klass) + if self.is(klass) then + klass.decode(self.value) + else + nil + end + end + + def type_name + return self.type_url.split("/")[-1] + end + + def is(klass) + return self.type_name == klass.descriptor.name + end + end + + Timestamp.class_eval do + if RUBY_VERSION < "2.5" + def to_time + Time.at(self.to_f) + end + else + def to_time + Time.at(seconds, nanos, :nanosecond) + end + end + + def self.from_time(time) + new.from_time(time) + end + + def from_time(time) + self.seconds = time.to_i + self.nanos = time.nsec + self + end + + def to_i + self.seconds + end + + def to_f + self.seconds + (self.nanos.quo(1_000_000_000)) + end + end + + Duration.class_eval do + def to_f + self.seconds + (self.nanos.to_f / 1_000_000_000) + end + end + + class UnexpectedStructType < Google::Protobuf::Error; end + + Value.class_eval do + def to_ruby(recursive = false) + case self.kind + when :struct_value + if recursive + self.struct_value.to_h + else + self.struct_value + end + when :list_value + if recursive + self.list_value.to_a + else + self.list_value + end + when :null_value + nil + when :number_value + self.number_value + when :string_value + self.string_value + when :bool_value + self.bool_value + else + raise UnexpectedStructType + end + end + + def self.from_ruby(value) + self.new.from_ruby(value) + end + + def from_ruby(value) + case value + when NilClass + self.null_value = :NULL_VALUE + when Numeric + self.number_value = value + when String + self.string_value = value + when TrueClass + self.bool_value = true + when FalseClass + self.bool_value = false + when Struct + self.struct_value = value + when Hash + self.struct_value = Struct.from_hash(value) + when ListValue + self.list_value = value + when Array + self.list_value = ListValue.from_a(value) + else + raise UnexpectedStructType + end + + self + end + end + + Struct.class_eval do + def [](key) + self.fields[key].to_ruby + rescue NoMethodError + nil + end + + def []=(key, value) + unless key.is_a?(String) + raise UnexpectedStructType, "Struct keys must be strings." + end + self.fields[key] ||= Google::Protobuf::Value.new + self.fields[key].from_ruby(value) + end + + def to_h + ret = {} + self.fields.each { |key, val| ret[key] = val.to_ruby(true) } + ret + end + + def self.from_hash(hash) + ret = Struct.new + hash.each { |key, val| ret[key] = val } + ret + end + + def has_key?(key) + self.fields.has_key?(key) + end + end + + ListValue.class_eval do + include Enumerable + + def length + self.values.length + end + + def [](index) + self.values[index].to_ruby + end + + def []=(index, value) + self.values[index].from_ruby(value) + end + + def <<(value) + wrapper = Google::Protobuf::Value.new + wrapper.from_ruby(value) + self.values << wrapper + end + + def each + self.values.each { |x| yield(x.to_ruby) } + end + + def to_a + self.values.map { |x| x.to_ruby(true) } + end + + def self.from_a(arr) + ret = ListValue.new + arr.each { |val| ret << val } + ret + end + end + end +end diff --git a/tools/go-generator/cmd/generator/_protobuf/ruby/src/main/java/com/google/protobuf/jruby/RubyFieldDescriptor.java b/tools/go-generator/cmd/generator/_protobuf/ruby/src/main/java/com/google/protobuf/jruby/RubyFieldDescriptor.java new file mode 100644 index 0000000..e9594d8 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/ruby/src/main/java/com/google/protobuf/jruby/RubyFieldDescriptor.java @@ -0,0 +1,270 @@ +/* + * Protocol Buffers - Google's data interchange format + * Copyright 2014 Google Inc. All rights reserved. + * https://developers.google.com/protocol-buffers/ + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.google.protobuf.jruby; + +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Descriptors.FileDescriptor; +import org.jruby.*; +import org.jruby.anno.JRubyClass; +import org.jruby.anno.JRubyMethod; +import org.jruby.runtime.ObjectAllocator; +import org.jruby.runtime.ThreadContext; +import org.jruby.runtime.builtin.IRubyObject; + +@JRubyClass(name = "FieldDescriptor") +public class RubyFieldDescriptor extends RubyObject { + public static void createRubyFieldDescriptor(Ruby runtime) { + RubyModule mProtobuf = runtime.getClassFromPath("Google::Protobuf"); + RubyClass cFieldDescriptor = mProtobuf.defineClassUnder("FieldDescriptor", runtime.getObject(), new ObjectAllocator() { + @Override + public IRubyObject allocate(Ruby runtime, RubyClass klazz) { + return new RubyFieldDescriptor(runtime, klazz); + } + }); + cFieldDescriptor.defineAnnotatedMethods(RubyFieldDescriptor.class); + } + + public RubyFieldDescriptor(Ruby runtime, RubyClass klazz) { + super(runtime, klazz); + } + + /* + * call-seq: + * FieldDescriptor.default => default + * + * Returns this field's default, as a Ruby object, or nil if not yet set. + */ + // VALUE FieldDescriptor_default(VALUE _self) { + // DEFINE_SELF(FieldDescriptor, self, _self); + // return layout_get_default(self->fielddef); + // } + + /* + * call-seq: + * FieldDescriptor.label => label + * + * Returns this field's label (i.e., plurality), as a Ruby symbol. + * + * Valid field labels are: + * :optional, :repeated + */ + @JRubyMethod(name = "label") + public IRubyObject getLabel(ThreadContext context) { + if (label == null) { + calculateLabel(context); + } + return label; + } + + /* + * call-seq: + * FieldDescriptor.name => name + * + * Returns the name of this field as a Ruby String, or nil if it is not set. + */ + @JRubyMethod(name = "name") + public IRubyObject getName(ThreadContext context) { + return this.name; + } + + /* + * call-seq: + * FieldDescriptor.subtype => message_or_enum_descriptor + * + * Returns the message or enum descriptor corresponding to this field's type if + * it is a message or enum field, respectively, or nil otherwise. Cannot be + * called *until* the containing message type is added to a pool (and thus + * resolved). + */ + @JRubyMethod(name = "subtype") + public IRubyObject getSubtype(ThreadContext context) { + if (subtype == null) { + calculateSubtype(context); + } + return subtype; + } + + /* + * call-seq: + * FieldDescriptor.type => type + * + * Returns this field's type, as a Ruby symbol, or nil if not yet set. + * + * Valid field types are: + * :int32, :int64, :uint32, :uint64, :float, :double, :bool, :string, + * :bytes, :message. + */ + @JRubyMethod(name = "type") + public IRubyObject getType(ThreadContext context) { + return Utils.fieldTypeToRuby(context, descriptor.getType()); + } + + /* + * call-seq: + * FieldDescriptor.number => number + * + * Returns the tag number for this field. + */ + @JRubyMethod(name = "number") + public IRubyObject getNumber(ThreadContext context) { + return this.number; + } + + /* + * call-seq: + * FieldDescriptor.submsg_name => submsg_name + * + * Returns the name of the message or enum type corresponding to this field, if + * it is a message or enum field (respectively), or nil otherwise. This type + * name will be resolved within the context of the pool to which the containing + * message type is added. + */ + // VALUE FieldDescriptor_submsg_name(VALUE _self) { + // DEFINE_SELF(FieldDescriptor, self, _self); + // switch (upb_fielddef_type(self->fielddef)) { + // case UPB_TYPE_ENUM: + // return rb_str_new2( + // upb_enumdef_fullname(upb_fielddef_enumsubdef(self->fielddef))); + // case UPB_TYPE_MESSAGE: + // return rb_str_new2( + // upb_msgdef_fullname(upb_fielddef_msgsubdef(self->fielddef))); + // default: + // return Qnil; + // } + // } + /* + * call-seq: + * FieldDescriptor.submsg_name = submsg_name + * + * Sets the name of the message or enum type corresponding to this field, if it + * is a message or enum field (respectively). This type name will be resolved + * within the context of the pool to which the containing message type is added. + * Cannot be called on field that are not of message or enum type, or on fields + * that are part of a message type already added to a pool. + */ + // @JRubyMethod(name = "submsg_name=") + // public IRubyObject setSubmsgName(ThreadContext context, IRubyObject name) { + // this.builder.setTypeName("." + Utils.escapeIdentifier(name.asJavaString())); + // return context.runtime.getNil(); + // } + + /* + * call-seq: + * FieldDescriptor.clear(message) + * + * Clears the field from the message if it's set. + */ + @JRubyMethod(name = "clear") + public IRubyObject clearValue(ThreadContext context, IRubyObject message) { + return ((RubyMessage) message).clearField(context, descriptor); + } + + /* + * call-seq: + * FieldDescriptor.get(message) => value + * + * Returns the value set for this field on the given message. Raises an + * exception if message is of the wrong type. + */ + @JRubyMethod(name = "get") + public IRubyObject getValue(ThreadContext context, IRubyObject message) { + return ((RubyMessage) message).getField(context, descriptor); + } + + /* + * call-seq: + * FieldDescriptor.has?(message) => boolean + * + * Returns whether the value is set on the given message. Raises an + * exception when calling for fields that do not have presence. + */ + @JRubyMethod(name = "has?") + public IRubyObject has(ThreadContext context, IRubyObject message) { + return ((RubyMessage) message).hasField(context, descriptor); + } + + /* + * call-seq: + * FieldDescriptor.set(message, value) + * + * Sets the value corresponding to this field to the given value on the given + * message. Raises an exception if message is of the wrong type. Performs the + * ordinary type-checks for field setting. + */ + @JRubyMethod(name = "set") + public IRubyObject setValue(ThreadContext context, IRubyObject message, IRubyObject value) { + ((RubyMessage) message).setField(context, descriptor, value); + return context.nil; + } + + protected void setDescriptor(ThreadContext context, FieldDescriptor descriptor, RubyDescriptorPool pool) { + if (descriptor.isRequired() && descriptor.getFile().getSyntax() == FileDescriptor.Syntax.PROTO3) { + throw Utils.createTypeError(context, descriptor.getName() + " is labeled required but required fields are unsupported in proto3"); + } + this.descriptor = descriptor; + this.name = context.runtime.newString(descriptor.getName()); + this.pool = pool; + } + + private void calculateLabel(ThreadContext context) { + if (descriptor.isRepeated()) { + this.label = context.runtime.newSymbol("repeated"); + } else if (descriptor.isOptional()) { + this.label = context.runtime.newSymbol("optional"); + } else { + this.label = context.nil; + } + } + + private void calculateSubtype(ThreadContext context) { + FieldDescriptor.Type fdType = descriptor.getType(); + if (fdType == FieldDescriptor.Type.MESSAGE) { + RubyString messageName = context.runtime.newString(descriptor.getMessageType().getFullName()); + this.subtype = pool.lookup(context, messageName); + } else if (fdType == FieldDescriptor.Type.ENUM) { + RubyString enumName = context.runtime.newString(descriptor.getEnumType().getFullName()); + this.subtype = pool.lookup(context, enumName); + } else { + this.subtype = context.nil; + } + } + + private static final String DOT = "."; + + private FieldDescriptor descriptor; + private IRubyObject name; + private IRubyObject label; + private IRubyObject number; + private IRubyObject subtype; + private RubyDescriptorPool pool; +} diff --git a/tools/go-generator/cmd/generator/_protobuf/ruby/src/main/java/com/google/protobuf/jruby/RubyMap.java b/tools/go-generator/cmd/generator/_protobuf/ruby/src/main/java/com/google/protobuf/jruby/RubyMap.java new file mode 100644 index 0000000..f7379b1 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/ruby/src/main/java/com/google/protobuf/jruby/RubyMap.java @@ -0,0 +1,474 @@ +/* + * Protocol Buffers - Google's data interchange format + * Copyright 2014 Google Inc. All rights reserved. + * https://developers.google.com/protocol-buffers/ + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.google.protobuf.jruby; + +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.DynamicMessage; +import org.jruby.*; +import org.jruby.anno.JRubyClass; +import org.jruby.anno.JRubyMethod; +import org.jruby.runtime.Block; +import org.jruby.runtime.Helpers; +import org.jruby.runtime.ObjectAllocator; +import org.jruby.runtime.ThreadContext; +import org.jruby.runtime.builtin.IRubyObject; + +import java.nio.ByteBuffer; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@JRubyClass(name = "Map", include = "Enumerable") +public class RubyMap extends RubyObject { + public static void createRubyMap(Ruby runtime) { + RubyModule protobuf = runtime.getClassFromPath("Google::Protobuf"); + RubyClass cMap = protobuf.defineClassUnder("Map", runtime.getObject(), new ObjectAllocator() { + @Override + public IRubyObject allocate(Ruby ruby, RubyClass rubyClass) { + return new RubyMap(ruby, rubyClass); + } + }); + cMap.includeModule(runtime.getEnumerable()); + cMap.defineAnnotatedMethods(RubyMap.class); + } + + public RubyMap(Ruby ruby, RubyClass rubyClass) { + super(ruby, rubyClass); + } + + /* + * call-seq: + * Map.new(key_type, value_type, value_typeclass = nil, init_hashmap = {}) + * => new map + * + * Allocates a new Map container. This constructor may be called with 2, 3, or 4 + * arguments. The first two arguments are always present and are symbols (taking + * on the same values as field-type symbols in message descriptors) that + * indicate the type of the map key and value fields. + * + * The supported key types are: :int32, :int64, :uint32, :uint64, :fixed32, + * :fixed64, :sfixed32, :sfixed64, :sint32, :sint64, :bool, :string, :bytes. + * + * The supported value types are: :int32, :int64, :uint32, :uint64, :fixed32, + * :fixed64, :sfixed32, :sfixed64, :sint32, :sint64, :bool, :string, :bytes, + * :enum, :message. + * + * The third argument, value_typeclass, must be present if value_type is :enum + * or :message. As in RepeatedField#new, this argument must be a message class + * (for :message) or enum module (for :enum). + * + * The last argument, if present, provides initial content for map. Note that + * this may be an ordinary Ruby hashmap or another Map instance with identical + * key and value types. Also note that this argument may be present whether or + * not value_typeclass is present (and it is unambiguously separate from + * value_typeclass because value_typeclass's presence is strictly determined by + * value_type). The contents of this initial hashmap or Map instance are + * shallow-copied into the new Map: the original map is unmodified, but + * references to underlying objects will be shared if the value type is a + * message type. + */ + @JRubyMethod(required = 2, optional = 2) + public IRubyObject initialize(ThreadContext context, IRubyObject[] args) { + this.table = new HashMap(); + this.keyType = Utils.rubyToFieldType(args[0]); + this.valueType = Utils.rubyToFieldType(args[1]); + + switch(keyType) { + case STRING: + case BYTES: + this.keyTypeIsString = true; + break; + case INT32: + case INT64: + case SINT32: + case SINT64: + case UINT32: + case UINT64: + case FIXED32: + case FIXED64: + case SFIXED32: + case SFIXED64: + case BOOL: + // These are OK. + break; + default: + throw context.runtime.newArgumentError("Invalid key type for map."); + } + + int initValueArg = 2; + if (needTypeclass(this.valueType) && args.length > 2) { + this.valueTypeClass = args[2]; + Utils.validateTypeClass(context, this.valueType, this.valueTypeClass); + initValueArg = 3; + } else { + this.valueTypeClass = context.runtime.getNilClass(); + } + + if (args.length > initValueArg) { + mergeIntoSelf(context, args[initValueArg]); + } + return this; + } + + /* + * call-seq: + * Map.[]=(key, value) => value + * + * Inserts or overwrites the value at the given key with the given new value. + * Throws an exception if the key type is incorrect. Returns the new value that + * was just inserted. + */ + @JRubyMethod(name = "[]=") + public IRubyObject indexSet(ThreadContext context, IRubyObject key, IRubyObject value) { + checkFrozen(); + + /* + * String types for keys return a different error than + * other types for keys, so deal with them specifically first + */ + if (keyTypeIsString && !(key instanceof RubySymbol || key instanceof RubyString)) { + throw Utils.createTypeError(context, "Expected string for map key"); + } + key = Utils.checkType(context, keyType, "key", key, (RubyModule) valueTypeClass); + value = Utils.checkType(context, valueType, "value", value, (RubyModule) valueTypeClass); + IRubyObject symbol; + if (valueType == FieldDescriptor.Type.ENUM && + Utils.isRubyNum(value) && + ! (symbol = RubyEnum.lookup(context, valueTypeClass, value)).isNil()) { + value = symbol; + } + this.table.put(key, value); + return value; + } + + /* + * call-seq: + * Map.[](key) => value + * + * Accesses the element at the given key. Throws an exception if the key type is + * incorrect. Returns nil when the key is not present in the map. + */ + @JRubyMethod(name = "[]") + public IRubyObject index(ThreadContext context, IRubyObject key) { + key = Utils.symToString(key); + return Helpers.nullToNil(table.get(key), context.nil); + } + + /* + * call-seq: + * Map.==(other) => boolean + * + * Compares this map to another. Maps are equal if they have identical key sets, + * and for each key, the values in both maps compare equal. Elements are + * compared as per normal Ruby semantics, by calling their :== methods (or + * performing a more efficient comparison for primitive types). + * + * Maps with dissimilar key types or value types/typeclasses are never equal, + * even if value comparison (for example, between integers and floats) would + * have otherwise indicated that every element has equal value. + */ + @JRubyMethod(name = "==") + public IRubyObject eq(ThreadContext context, IRubyObject _other) { + if (_other instanceof RubyHash) + return singleLevelHash(context).op_equal(context, _other); + RubyMap other = (RubyMap) _other; + if (this == other) return context.runtime.getTrue(); + if (!typeCompatible(other) || this.table.size() != other.table.size()) + return context.runtime.getFalse(); + for (IRubyObject key : table.keySet()) { + if (! other.table.containsKey(key)) + return context.runtime.getFalse(); + if (! other.table.get(key).equals(table.get(key))) + return context.runtime.getFalse(); + } + return context.runtime.getTrue(); + } + + /* + * call-seq: + * Map.inspect => string + * + * Returns a string representing this map's elements. It will be formatted as + * "{key => value, key => value, ...}", with each key and value string + * representation computed by its own #inspect method. + */ + @JRubyMethod + public IRubyObject inspect() { + return singleLevelHash(getRuntime().getCurrentContext()).inspect(); + } + + /* + * call-seq: + * Map.hash => hash_value + * + * Returns a hash value based on this map's contents. + */ + @JRubyMethod + public IRubyObject hash(ThreadContext context) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + for (IRubyObject key : table.keySet()) { + digest.update((byte) key.hashCode()); + digest.update((byte) table.get(key).hashCode()); + } + return context.runtime.newFixnum(ByteBuffer.wrap(digest.digest()).getLong()); + } catch (NoSuchAlgorithmException ignore) { + return context.runtime.newFixnum(System.identityHashCode(table)); + } + } + + /* + * call-seq: + * Map.keys => [list_of_keys] + * + * Returns the list of keys contained in the map, in unspecified order. + */ + @JRubyMethod + public IRubyObject keys(ThreadContext context) { + return RubyArray.newArray(context.runtime, table.keySet()); + } + + /* + * call-seq: + * Map.values => [list_of_values] + * + * Returns the list of values contained in the map, in unspecified order. + */ + @JRubyMethod + public IRubyObject values(ThreadContext context) { + return RubyArray.newArray(context.runtime, table.values()); + } + + /* + * call-seq: + * Map.clear + * + * Removes all entries from the map. + */ + @JRubyMethod + public IRubyObject clear(ThreadContext context) { + checkFrozen(); + table.clear(); + return context.nil; + } + + /* + * call-seq: + * Map.each(&block) + * + * Invokes &block on each |key, value| pair in the map, in unspecified order. + * Note that Map also includes Enumerable; map thus acts like a normal Ruby + * sequence. + */ + @JRubyMethod + public IRubyObject each(ThreadContext context, Block block) { + for (IRubyObject key : table.keySet()) { + block.yieldSpecific(context, key, table.get(key)); + } + return context.nil; + } + + /* + * call-seq: + * Map.delete(key) => old_value + * + * Deletes the value at the given key, if any, returning either the old value or + * nil if none was present. Throws an exception if the key is of the wrong type. + */ + @JRubyMethod + public IRubyObject delete(ThreadContext context, IRubyObject key) { + checkFrozen(); + return table.remove(key); + } + + /* + * call-seq: + * Map.has_key?(key) => bool + * + * Returns true if the given key is present in the map. Throws an exception if + * the key has the wrong type. + */ + @JRubyMethod(name = "has_key?") + public IRubyObject hasKey(ThreadContext context, IRubyObject key) { + return this.table.containsKey(key) ? context.runtime.getTrue() : context.runtime.getFalse(); + } + + /* + * call-seq: + * Map.length + * + * Returns the number of entries (key-value pairs) in the map. + */ + @JRubyMethod(name = {"length", "size"}) + public IRubyObject length(ThreadContext context) { + return context.runtime.newFixnum(this.table.size()); + } + + /* + * call-seq: + * Map.dup => new_map + * + * Duplicates this map with a shallow copy. References to all non-primitive + * element objects (e.g., submessages) are shared. + */ + @JRubyMethod + public IRubyObject dup(ThreadContext context) { + RubyMap newMap = newThisType(context); + for (Map.Entry entry : table.entrySet()) { + newMap.table.put(entry.getKey(), entry.getValue()); + } + return newMap; + } + + @JRubyMethod(name = "to_h") + public RubyHash toHash(ThreadContext context) { + Map mapForHash = new HashMap(); + + table.forEach((key, value) -> { + if (!value.isNil()) { + if (value.respondsTo("to_h")) { + value = Helpers.invoke(context, value, "to_h"); + } else if (value.respondsTo("to_a")) { + value = Helpers.invoke(context, value, "to_a"); + } + mapForHash.put(key, value); + } + }); + + return RubyHash.newHash(context.runtime, mapForHash, context.nil); + } + + // Used by Google::Protobuf.deep_copy but not exposed directly. + protected IRubyObject deepCopy(ThreadContext context) { + RubyMap newMap = newThisType(context); + switch (valueType) { + case MESSAGE: + for (IRubyObject key : table.keySet()) { + RubyMessage message = (RubyMessage) table.get(key); + newMap.table.put(key.dup(), message.deepCopy(context)); + } + break; + default: + for (IRubyObject key : table.keySet()) { + newMap.table.put(key.dup(), table.get(key).dup()); + } + } + return newMap; + } + + protected List build(ThreadContext context, RubyDescriptor descriptor, int depth) { + List list = new ArrayList(); + RubyClass rubyClass = (RubyClass) descriptor.msgclass(context); + FieldDescriptor keyField = descriptor.getField("key"); + FieldDescriptor valueField = descriptor.getField("value"); + for (IRubyObject key : table.keySet()) { + RubyMessage mapMessage = (RubyMessage) rubyClass.newInstance(context, Block.NULL_BLOCK); + mapMessage.setField(context, keyField, key); + mapMessage.setField(context, valueField, table.get(key)); + list.add(mapMessage.build(context, depth + 1)); + } + return list; + } + + protected RubyMap mergeIntoSelf(final ThreadContext context, IRubyObject hashmap) { + if (hashmap instanceof RubyHash) { + ((RubyHash) hashmap).visitAll(context, new RubyHash.Visitor() { + @Override + public void visit(IRubyObject key, IRubyObject val) { + if (val instanceof RubyHash && !valueTypeClass.isNil()) { + val = ((RubyClass) valueTypeClass).newInstance(context, val, Block.NULL_BLOCK); + } + indexSet(context, key, val); + } + }, null); + } else if (hashmap instanceof RubyMap) { + RubyMap other = (RubyMap) hashmap; + if (!typeCompatible(other)) { + throw Utils.createTypeError(context, "Attempt to merge Map with mismatching types"); + } + } else { + throw Utils.createTypeError(context, "Unknown type merging into Map"); + } + return this; + } + + protected boolean typeCompatible(RubyMap other) { + return this.keyType == other.keyType && + this.valueType == other.valueType && + this.valueTypeClass == other.valueTypeClass; + } + + private RubyMap newThisType(ThreadContext context) { + RubyMap newMap; + if (needTypeclass(valueType)) { + newMap = (RubyMap) metaClass.newInstance(context, + Utils.fieldTypeToRuby(context, keyType), + Utils.fieldTypeToRuby(context, valueType), + valueTypeClass, Block.NULL_BLOCK); + } else { + newMap = (RubyMap) metaClass.newInstance(context, + Utils.fieldTypeToRuby(context, keyType), + Utils.fieldTypeToRuby(context, valueType), + Block.NULL_BLOCK); + } + newMap.table = new HashMap(); + return newMap; + } + + /* + * toHash calls toHash on values, for some camparisons we only need + * a hash with the original objects still as values + */ + private RubyHash singleLevelHash(ThreadContext context) { + return RubyHash.newHash(context.runtime, table, context.nil); + } + + private boolean needTypeclass(FieldDescriptor.Type type) { + switch(type) { + case MESSAGE: + case ENUM: + return true; + default: + return false; + } + } + + private FieldDescriptor.Type keyType; + private FieldDescriptor.Type valueType; + private IRubyObject valueTypeClass; + private Map table; + private boolean keyTypeIsString = false; +} diff --git a/tools/go-generator/cmd/generator/_protobuf/ruby/tests/encode_decode_test.rb b/tools/go-generator/cmd/generator/_protobuf/ruby/tests/encode_decode_test.rb new file mode 100755 index 0000000..429ac43 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/ruby/tests/encode_decode_test.rb @@ -0,0 +1,104 @@ +#!/usr/bin/ruby + +# generated_code.rb is in the same directory as this test. +$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__))) + +require 'generated_code_pb' +require 'google/protobuf/well_known_types' +require 'test/unit' + +def hex2bin(s) + s.scan(/../).map { |x| x.hex.chr }.join +end + +class EncodeDecodeTest < Test::Unit::TestCase + def test_discard_unknown + # Test discard unknown in message. + unknown_msg = A::B::C::TestUnknown.new(:unknown_field => 1) + from = A::B::C::TestUnknown.encode(unknown_msg) + m = A::B::C::TestMessage.decode(from) + Google::Protobuf.discard_unknown(m) + to = A::B::C::TestMessage.encode(m) + assert_equal '', to + + # Test discard unknown for singular message field. + unknown_msg = A::B::C::TestUnknown.new( + :optional_unknown => + A::B::C::TestUnknown.new(:unknown_field => 1)) + from = A::B::C::TestUnknown.encode(unknown_msg) + m = A::B::C::TestMessage.decode(from) + Google::Protobuf.discard_unknown(m) + to = A::B::C::TestMessage.encode(m.optional_msg) + assert_equal '', to + + # Test discard unknown for repeated message field. + unknown_msg = A::B::C::TestUnknown.new( + :repeated_unknown => + [A::B::C::TestUnknown.new(:unknown_field => 1)]) + from = A::B::C::TestUnknown.encode(unknown_msg) + m = A::B::C::TestMessage.decode(from) + Google::Protobuf.discard_unknown(m) + to = A::B::C::TestMessage.encode(m.repeated_msg[0]) + assert_equal '', to + + # Test discard unknown for map value message field. + unknown_msg = A::B::C::TestUnknown.new( + :map_unknown => + {"" => A::B::C::TestUnknown.new(:unknown_field => 1)}) + from = A::B::C::TestUnknown.encode(unknown_msg) + m = A::B::C::TestMessage.decode(from) + Google::Protobuf.discard_unknown(m) + to = A::B::C::TestMessage.encode(m.map_string_msg['']) + assert_equal '', to + + # Test discard unknown for oneof message field. + unknown_msg = A::B::C::TestUnknown.new( + :oneof_unknown => + A::B::C::TestUnknown.new(:unknown_field => 1)) + from = A::B::C::TestUnknown.encode(unknown_msg) + m = A::B::C::TestMessage.decode(from) + Google::Protobuf.discard_unknown(m) + to = A::B::C::TestMessage.encode(m.oneof_msg) + assert_equal '', to + end + + def test_encode_json + msg = A::B::C::TestMessage.new({ optional_int32: 22 }) + json = msg.to_json + + to = A::B::C::TestMessage.decode_json(json) + assert_equal to.optional_int32, 22 + + msg = A::B::C::TestMessage.new({ optional_int32: 22 }) + json = msg.to_json({ preserve_proto_fieldnames: true }) + + assert_match 'optional_int32', json + + to = A::B::C::TestMessage.decode_json(json) + assert_equal 22, to.optional_int32 + + msg = A::B::C::TestMessage.new({ optional_int32: 22 }) + json = A::B::C::TestMessage.encode_json( + msg, + { preserve_proto_fieldnames: true, emit_defaults: true } + ) + + assert_match 'optional_int32', json + end + + def test_encode_wrong_msg + assert_raise ::ArgumentError do + m = A::B::C::TestMessage.new( + :optional_int32 => 1, + ) + Google::Protobuf::Any.encode(m) + end + end + + def test_json_name + msg = A::B::C::TestJsonName.new(:value => 42) + json = msg.to_json + assert_match json, "{\"CustomJsonName\":42}" + end + +end diff --git a/tools/go-generator/cmd/generator/_protobuf/ruby/tests/test_import.proto b/tools/go-generator/cmd/generator/_protobuf/ruby/tests/test_import.proto new file mode 100644 index 0000000..230484e --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/ruby/tests/test_import.proto @@ -0,0 +1,5 @@ +syntax = "proto3"; + +package foo_bar; + +message TestImportedMessage {} diff --git a/tools/go-generator/cmd/generator/_protobuf/ruby/tests/test_ruby_package.proto b/tools/go-generator/cmd/generator/_protobuf/ruby/tests/test_ruby_package.proto new file mode 100644 index 0000000..54b7aca --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/ruby/tests/test_ruby_package.proto @@ -0,0 +1,7 @@ +syntax = "proto3"; + +package foo_bar; + +option ruby_package = "A::B"; + +message TestRubyPackageMessage {} diff --git a/tools/go-generator/cmd/generator/_protobuf/src/Makefile.am b/tools/go-generator/cmd/generator/_protobuf/src/Makefile.am new file mode 100644 index 0000000..225061a --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/Makefile.am @@ -0,0 +1,914 @@ +## Process this file with automake to produce Makefile.in + +if HAVE_ZLIB +GZCHECKPROGRAMS = zcgzip zcgunzip +GZHEADERS = google/protobuf/io/gzip_stream.h +GZTESTS = google/protobuf/io/gzip_stream_unittest.sh +ZLIB_DEF = -DHAVE_ZLIB=1 +else +GZCHECKPROGRAMS = +GZHEADERS = +GZTESTS = +ZLIB_DEF = +endif + +if HAVE_PTHREAD +PTHREAD_DEF = -DHAVE_PTHREAD=1 +else +PTHREAD_DEF = +endif + +PROTOBUF_VERSION = 30:4:0 + +if GCC +# Turn on all warnings except for sign comparison (we ignore sign comparison +# in Google so our code base have tons of such warnings). +NO_OPT_CXXFLAGS = $(PTHREAD_CFLAGS) $(PTHREAD_DEF) $(ZLIB_DEF) -Wall -Wno-sign-compare +else +NO_OPT_CXXFLAGS = $(PTHREAD_CFLAGS) $(PTHREAD_DEF) $(ZLIB_DEF) +endif + +AM_CXXFLAGS = $(NO_OPT_CXXFLAGS) $(PROTOBUF_OPT_FLAG) + +AM_LDFLAGS = $(PTHREAD_CFLAGS) ${LIBLOG_LIBS} + +# If I say "dist_include_DATA", automake complains that $(includedir) is not +# a "legitimate" directory for DATA. Screw you, automake. +protodir = $(includedir) + +# If you are adding new files here, also remember to change the build files for +# all other languages, //protoc-artifacts/build-zip.sh and run +# //update_file_list.sh for bazel. +nobase_dist_proto_DATA = \ + google/protobuf/any.proto \ + google/protobuf/api.proto \ + google/protobuf/compiler/plugin.proto \ + google/protobuf/descriptor.proto \ + google/protobuf/duration.proto \ + google/protobuf/empty.proto \ + google/protobuf/field_mask.proto \ + google/protobuf/source_context.proto \ + google/protobuf/struct.proto \ + google/protobuf/timestamp.proto \ + google/protobuf/type.proto \ + google/protobuf/wrappers.proto + +# Not sure why these don't get cleaned automatically. +clean-local: + rm -f *.loT + +CLEANFILES = $(protoc_outputs) unittest_proto_middleman \ + testzip.jar testzip.list testzip.proto testzip.zip \ + no_warning_test.cc + +MAINTAINERCLEANFILES = \ + Makefile.in + +nobase_include_HEADERS = \ + google/protobuf/any.h \ + google/protobuf/any.pb.h \ + google/protobuf/api.pb.h \ + google/protobuf/arena.h \ + google/protobuf/arena_impl.h \ + google/protobuf/arenastring.h \ + google/protobuf/compiler/code_generator.h \ + google/protobuf/compiler/command_line_interface.h \ + google/protobuf/compiler/cpp/cpp_file.h \ + google/protobuf/compiler/cpp/cpp_generator.h \ + google/protobuf/compiler/cpp/cpp_helpers.h \ + google/protobuf/compiler/cpp/cpp_names.h \ + google/protobuf/compiler/csharp/csharp_doc_comment.h \ + google/protobuf/compiler/csharp/csharp_generator.h \ + google/protobuf/compiler/csharp/csharp_names.h \ + google/protobuf/compiler/csharp/csharp_options.h \ + google/protobuf/compiler/importer.h \ + google/protobuf/compiler/java/java_generator.h \ + google/protobuf/compiler/java/java_kotlin_generator.h \ + google/protobuf/compiler/java/java_names.h \ + google/protobuf/compiler/js/js_generator.h \ + google/protobuf/compiler/objectivec/objectivec_generator.h \ + google/protobuf/compiler/objectivec/objectivec_helpers.h \ + google/protobuf/compiler/parser.h \ + google/protobuf/compiler/php/php_generator.h \ + google/protobuf/compiler/plugin.h \ + google/protobuf/compiler/plugin.pb.h \ + google/protobuf/compiler/python/python_generator.h \ + google/protobuf/compiler/ruby/ruby_generator.h \ + google/protobuf/descriptor.h \ + google/protobuf/descriptor.pb.h \ + google/protobuf/descriptor_database.h \ + google/protobuf/duration.pb.h \ + google/protobuf/dynamic_message.h \ + google/protobuf/empty.pb.h \ + google/protobuf/explicitly_constructed.h \ + google/protobuf/extension_set.h \ + google/protobuf/extension_set_inl.h \ + google/protobuf/field_access_listener.h \ + google/protobuf/field_mask.pb.h \ + google/protobuf/generated_enum_reflection.h \ + google/protobuf/generated_enum_util.h \ + google/protobuf/generated_message_bases.h \ + google/protobuf/generated_message_reflection.h \ + google/protobuf/generated_message_table_driven.h \ + google/protobuf/generated_message_table_driven_lite.h \ + google/protobuf/generated_message_tctable_decl.h \ + google/protobuf/generated_message_tctable_impl.h \ + google/protobuf/generated_message_tctable_impl.inc \ + google/protobuf/generated_message_util.h \ + google/protobuf/has_bits.h \ + google/protobuf/implicit_weak_message.h \ + google/protobuf/inlined_string_field.h \ + google/protobuf/io/coded_stream.h \ + $(GZHEADERS) \ + google/protobuf/io/io_win32.h \ + google/protobuf/io/printer.h \ + google/protobuf/io/strtod.h \ + google/protobuf/io/tokenizer.h \ + google/protobuf/io/zero_copy_stream.h \ + google/protobuf/io/zero_copy_stream_impl.h \ + google/protobuf/io/zero_copy_stream_impl_lite.h \ + google/protobuf/map.h \ + google/protobuf/map_entry.h \ + google/protobuf/map_entry_lite.h \ + google/protobuf/map_field.h \ + google/protobuf/map_field_inl.h \ + google/protobuf/map_field_lite.h \ + google/protobuf/map_type_handler.h \ + google/protobuf/message.h \ + google/protobuf/message_lite.h \ + google/protobuf/metadata.h \ + google/protobuf/metadata_lite.h \ + google/protobuf/parse_context.h \ + google/protobuf/port.h \ + google/protobuf/port_def.inc \ + google/protobuf/port_undef.inc \ + google/protobuf/reflection.h \ + google/protobuf/reflection_ops.h \ + google/protobuf/repeated_field.h \ + google/protobuf/repeated_ptr_field.h \ + google/protobuf/service.h \ + google/protobuf/source_context.pb.h \ + google/protobuf/struct.pb.h \ + google/protobuf/stubs/bytestream.h \ + google/protobuf/stubs/callback.h \ + google/protobuf/stubs/casts.h \ + google/protobuf/stubs/common.h \ + google/protobuf/stubs/hash.h \ + google/protobuf/stubs/logging.h \ + google/protobuf/stubs/macros.h \ + google/protobuf/stubs/map_util.h \ + google/protobuf/stubs/mutex.h \ + google/protobuf/stubs/once.h \ + google/protobuf/stubs/platform_macros.h \ + google/protobuf/stubs/port.h \ + google/protobuf/stubs/status.h \ + google/protobuf/stubs/stl_util.h \ + google/protobuf/stubs/stringpiece.h \ + google/protobuf/stubs/strutil.h \ + google/protobuf/stubs/template_util.h \ + google/protobuf/text_format.h \ + google/protobuf/timestamp.pb.h \ + google/protobuf/type.pb.h \ + google/protobuf/unknown_field_set.h \ + google/protobuf/util/delimited_message_util.h \ + google/protobuf/util/field_comparator.h \ + google/protobuf/util/field_mask_util.h \ + google/protobuf/util/json_util.h \ + google/protobuf/util/message_differencer.h \ + google/protobuf/util/time_util.h \ + google/protobuf/util/type_resolver.h \ + google/protobuf/util/type_resolver_util.h \ + google/protobuf/wire_format.h \ + google/protobuf/wire_format_lite.h \ + google/protobuf/wrappers.pb.h + +lib_LTLIBRARIES = libprotobuf-lite.la libprotobuf.la libprotoc.la + +libprotobuf_lite_la_LIBADD = $(PTHREAD_LIBS) $(LIBATOMIC_LIBS) +libprotobuf_lite_la_LDFLAGS = -version-info $(PROTOBUF_VERSION) -export-dynamic -no-undefined +if HAVE_LD_VERSION_SCRIPT +libprotobuf_lite_la_LDFLAGS += -Wl,--version-script=$(srcdir)/libprotobuf-lite.map +EXTRA_libprotobuf_lite_la_DEPENDENCIES = libprotobuf-lite.map +endif +libprotobuf_lite_la_SOURCES = \ + google/protobuf/any_lite.cc \ + google/protobuf/arena.cc \ + google/protobuf/arenastring.cc \ + google/protobuf/extension_set.cc \ + google/protobuf/generated_enum_util.cc \ + google/protobuf/generated_message_table_driven_lite.cc \ + google/protobuf/generated_message_tctable_lite.cc \ + google/protobuf/generated_message_util.cc \ + google/protobuf/implicit_weak_message.cc \ + google/protobuf/inlined_string_field.cc \ + google/protobuf/io/coded_stream.cc \ + google/protobuf/io/io_win32.cc \ + google/protobuf/io/strtod.cc \ + google/protobuf/io/zero_copy_stream.cc \ + google/protobuf/io/zero_copy_stream_impl.cc \ + google/protobuf/io/zero_copy_stream_impl_lite.cc \ + google/protobuf/map.cc \ + google/protobuf/message_lite.cc \ + google/protobuf/parse_context.cc \ + google/protobuf/repeated_field.cc \ + google/protobuf/repeated_ptr_field.cc \ + google/protobuf/string_member_robber.h \ + google/protobuf/stubs/bytestream.cc \ + google/protobuf/stubs/common.cc \ + google/protobuf/stubs/int128.cc \ + google/protobuf/stubs/int128.h \ + google/protobuf/stubs/mathutil.h \ + google/protobuf/stubs/status.cc \ + google/protobuf/stubs/status_macros.h \ + google/protobuf/stubs/statusor.cc \ + google/protobuf/stubs/statusor.h \ + google/protobuf/stubs/stringpiece.cc \ + google/protobuf/stubs/stringprintf.cc \ + google/protobuf/stubs/stringprintf.h \ + google/protobuf/stubs/structurally_valid.cc \ + google/protobuf/stubs/strutil.cc \ + google/protobuf/stubs/time.cc \ + google/protobuf/stubs/time.h \ + google/protobuf/wire_format_lite.cc + +libprotobuf_la_LIBADD = $(PTHREAD_LIBS) $(LIBATOMIC_LIBS) +libprotobuf_la_LDFLAGS = -version-info $(PROTOBUF_VERSION) -export-dynamic -no-undefined +if HAVE_LD_VERSION_SCRIPT +libprotobuf_la_LDFLAGS += -Wl,--version-script=$(srcdir)/libprotobuf.map +EXTRA_libprotobuf_la_DEPENDENCIES = libprotobuf.map +endif +libprotobuf_la_SOURCES = \ + $(libprotobuf_lite_la_SOURCES) \ + google/protobuf/any.cc \ + google/protobuf/any.pb.cc \ + google/protobuf/api.pb.cc \ + google/protobuf/compiler/importer.cc \ + google/protobuf/compiler/parser.cc \ + google/protobuf/descriptor.cc \ + google/protobuf/descriptor.pb.cc \ + google/protobuf/descriptor_database.cc \ + google/protobuf/duration.pb.cc \ + google/protobuf/dynamic_message.cc \ + google/protobuf/empty.pb.cc \ + google/protobuf/extension_set_heavy.cc \ + google/protobuf/field_mask.pb.cc \ + google/protobuf/generated_message_bases.cc \ + google/protobuf/generated_message_reflection.cc \ + google/protobuf/generated_message_table_driven.cc \ + google/protobuf/generated_message_tctable_full.cc \ + google/protobuf/io/gzip_stream.cc \ + google/protobuf/io/printer.cc \ + google/protobuf/io/tokenizer.cc \ + google/protobuf/map_field.cc \ + google/protobuf/message.cc \ + google/protobuf/reflection_internal.h \ + google/protobuf/reflection_ops.cc \ + google/protobuf/service.cc \ + google/protobuf/source_context.pb.cc \ + google/protobuf/struct.pb.cc \ + google/protobuf/stubs/substitute.cc \ + google/protobuf/stubs/substitute.h \ + google/protobuf/text_format.cc \ + google/protobuf/timestamp.pb.cc \ + google/protobuf/type.pb.cc \ + google/protobuf/unknown_field_set.cc \ + google/protobuf/util/delimited_message_util.cc \ + google/protobuf/util/field_comparator.cc \ + google/protobuf/util/field_mask_util.cc \ + google/protobuf/util/internal/constants.h \ + google/protobuf/util/internal/datapiece.cc \ + google/protobuf/util/internal/datapiece.h \ + google/protobuf/util/internal/default_value_objectwriter.cc \ + google/protobuf/util/internal/default_value_objectwriter.h \ + google/protobuf/util/internal/error_listener.cc \ + google/protobuf/util/internal/error_listener.h \ + google/protobuf/util/internal/expecting_objectwriter.h \ + google/protobuf/util/internal/field_mask_utility.cc \ + google/protobuf/util/internal/field_mask_utility.h \ + google/protobuf/util/internal/json_escaping.cc \ + google/protobuf/util/internal/json_escaping.h \ + google/protobuf/util/internal/json_objectwriter.cc \ + google/protobuf/util/internal/json_objectwriter.h \ + google/protobuf/util/internal/json_stream_parser.cc \ + google/protobuf/util/internal/json_stream_parser.h \ + google/protobuf/util/internal/location_tracker.h \ + google/protobuf/util/internal/mock_error_listener.h \ + google/protobuf/util/internal/object_location_tracker.h \ + google/protobuf/util/internal/object_source.h \ + google/protobuf/util/internal/object_writer.cc \ + google/protobuf/util/internal/object_writer.h \ + google/protobuf/util/internal/proto_writer.cc \ + google/protobuf/util/internal/proto_writer.h \ + google/protobuf/util/internal/protostream_objectsource.cc \ + google/protobuf/util/internal/protostream_objectsource.h \ + google/protobuf/util/internal/protostream_objectwriter.cc \ + google/protobuf/util/internal/protostream_objectwriter.h \ + google/protobuf/util/internal/structured_objectwriter.h \ + google/protobuf/util/internal/type_info.cc \ + google/protobuf/util/internal/type_info.h \ + google/protobuf/util/internal/type_info_test_helper.h \ + google/protobuf/util/internal/utility.cc \ + google/protobuf/util/internal/utility.h \ + google/protobuf/util/json_util.cc \ + google/protobuf/util/message_differencer.cc \ + google/protobuf/util/time_util.cc \ + google/protobuf/util/type_resolver_util.cc \ + google/protobuf/wire_format.cc \ + google/protobuf/wrappers.pb.cc + +nodist_libprotobuf_la_SOURCES = $(nodist_libprotobuf_lite_la_SOURCES) + +libprotoc_la_LIBADD = $(PTHREAD_LIBS) libprotobuf.la +libprotoc_la_LDFLAGS = -version-info $(PROTOBUF_VERSION) -export-dynamic -no-undefined +if HAVE_LD_VERSION_SCRIPT +libprotoc_la_LDFLAGS += -Wl,--version-script=$(srcdir)/libprotoc.map +EXTRA_libprotoc_la_DEPENDENCIES = libprotoc.map +endif +libprotoc_la_SOURCES = \ + google/protobuf/compiler/code_generator.cc \ + google/protobuf/compiler/command_line_interface.cc \ + google/protobuf/compiler/cpp/cpp_enum.cc \ + google/protobuf/compiler/cpp/cpp_enum.h \ + google/protobuf/compiler/cpp/cpp_enum_field.cc \ + google/protobuf/compiler/cpp/cpp_enum_field.h \ + google/protobuf/compiler/cpp/cpp_extension.cc \ + google/protobuf/compiler/cpp/cpp_extension.h \ + google/protobuf/compiler/cpp/cpp_field.cc \ + google/protobuf/compiler/cpp/cpp_field.h \ + google/protobuf/compiler/cpp/cpp_file.cc \ + google/protobuf/compiler/cpp/cpp_generator.cc \ + google/protobuf/compiler/cpp/cpp_helpers.cc \ + google/protobuf/compiler/cpp/cpp_map_field.cc \ + google/protobuf/compiler/cpp/cpp_map_field.h \ + google/protobuf/compiler/cpp/cpp_message.cc \ + google/protobuf/compiler/cpp/cpp_message.h \ + google/protobuf/compiler/cpp/cpp_message_field.cc \ + google/protobuf/compiler/cpp/cpp_message_field.h \ + google/protobuf/compiler/cpp/cpp_message_layout_helper.h \ + google/protobuf/compiler/cpp/cpp_options.h \ + google/protobuf/compiler/cpp/cpp_padding_optimizer.cc \ + google/protobuf/compiler/cpp/cpp_padding_optimizer.h \ + google/protobuf/compiler/cpp/cpp_parse_function_generator.cc \ + google/protobuf/compiler/cpp/cpp_parse_function_generator.h \ + google/protobuf/compiler/cpp/cpp_primitive_field.cc \ + google/protobuf/compiler/cpp/cpp_primitive_field.h \ + google/protobuf/compiler/cpp/cpp_service.cc \ + google/protobuf/compiler/cpp/cpp_service.h \ + google/protobuf/compiler/cpp/cpp_string_field.cc \ + google/protobuf/compiler/cpp/cpp_string_field.h \ + google/protobuf/compiler/csharp/csharp_doc_comment.cc \ + google/protobuf/compiler/csharp/csharp_enum.cc \ + google/protobuf/compiler/csharp/csharp_enum.h \ + google/protobuf/compiler/csharp/csharp_enum_field.cc \ + google/protobuf/compiler/csharp/csharp_enum_field.h \ + google/protobuf/compiler/csharp/csharp_field_base.cc \ + google/protobuf/compiler/csharp/csharp_field_base.h \ + google/protobuf/compiler/csharp/csharp_generator.cc \ + google/protobuf/compiler/csharp/csharp_helpers.cc \ + google/protobuf/compiler/csharp/csharp_helpers.h \ + google/protobuf/compiler/csharp/csharp_map_field.cc \ + google/protobuf/compiler/csharp/csharp_map_field.h \ + google/protobuf/compiler/csharp/csharp_message.cc \ + google/protobuf/compiler/csharp/csharp_message.h \ + google/protobuf/compiler/csharp/csharp_message_field.cc \ + google/protobuf/compiler/csharp/csharp_message_field.h \ + google/protobuf/compiler/csharp/csharp_primitive_field.cc \ + google/protobuf/compiler/csharp/csharp_primitive_field.h \ + google/protobuf/compiler/csharp/csharp_reflection_class.cc \ + google/protobuf/compiler/csharp/csharp_reflection_class.h \ + google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc \ + google/protobuf/compiler/csharp/csharp_repeated_enum_field.h \ + google/protobuf/compiler/csharp/csharp_repeated_message_field.cc \ + google/protobuf/compiler/csharp/csharp_repeated_message_field.h \ + google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc \ + google/protobuf/compiler/csharp/csharp_repeated_primitive_field.h \ + google/protobuf/compiler/csharp/csharp_source_generator_base.cc \ + google/protobuf/compiler/csharp/csharp_source_generator_base.h \ + google/protobuf/compiler/csharp/csharp_wrapper_field.cc \ + google/protobuf/compiler/csharp/csharp_wrapper_field.h \ + google/protobuf/compiler/java/java_context.cc \ + google/protobuf/compiler/java/java_context.h \ + google/protobuf/compiler/java/java_doc_comment.cc \ + google/protobuf/compiler/java/java_doc_comment.h \ + google/protobuf/compiler/java/java_enum.cc \ + google/protobuf/compiler/java/java_enum.h \ + google/protobuf/compiler/java/java_enum_field.cc \ + google/protobuf/compiler/java/java_enum_field.h \ + google/protobuf/compiler/java/java_enum_field_lite.cc \ + google/protobuf/compiler/java/java_enum_field_lite.h \ + google/protobuf/compiler/java/java_enum_lite.cc \ + google/protobuf/compiler/java/java_enum_lite.h \ + google/protobuf/compiler/java/java_extension.cc \ + google/protobuf/compiler/java/java_extension.h \ + google/protobuf/compiler/java/java_extension_lite.cc \ + google/protobuf/compiler/java/java_extension_lite.h \ + google/protobuf/compiler/java/java_field.cc \ + google/protobuf/compiler/java/java_field.h \ + google/protobuf/compiler/java/java_file.cc \ + google/protobuf/compiler/java/java_file.h \ + google/protobuf/compiler/java/java_generator.cc \ + google/protobuf/compiler/java/java_generator_factory.cc \ + google/protobuf/compiler/java/java_generator_factory.h \ + google/protobuf/compiler/java/java_helpers.cc \ + google/protobuf/compiler/java/java_helpers.h \ + google/protobuf/compiler/java/java_kotlin_generator.cc \ + google/protobuf/compiler/java/java_map_field.cc \ + google/protobuf/compiler/java/java_map_field.h \ + google/protobuf/compiler/java/java_map_field_lite.cc \ + google/protobuf/compiler/java/java_map_field_lite.h \ + google/protobuf/compiler/java/java_message.cc \ + google/protobuf/compiler/java/java_message.h \ + google/protobuf/compiler/java/java_message_builder.cc \ + google/protobuf/compiler/java/java_message_builder.h \ + google/protobuf/compiler/java/java_message_builder_lite.cc \ + google/protobuf/compiler/java/java_message_builder_lite.h \ + google/protobuf/compiler/java/java_message_field.cc \ + google/protobuf/compiler/java/java_message_field.h \ + google/protobuf/compiler/java/java_message_field_lite.cc \ + google/protobuf/compiler/java/java_message_field_lite.h \ + google/protobuf/compiler/java/java_message_lite.cc \ + google/protobuf/compiler/java/java_message_lite.h \ + google/protobuf/compiler/java/java_name_resolver.cc \ + google/protobuf/compiler/java/java_name_resolver.h \ + google/protobuf/compiler/java/java_options.h \ + google/protobuf/compiler/java/java_primitive_field.cc \ + google/protobuf/compiler/java/java_primitive_field.h \ + google/protobuf/compiler/java/java_primitive_field_lite.cc \ + google/protobuf/compiler/java/java_primitive_field_lite.h \ + google/protobuf/compiler/java/java_service.cc \ + google/protobuf/compiler/java/java_service.h \ + google/protobuf/compiler/java/java_shared_code_generator.cc \ + google/protobuf/compiler/java/java_shared_code_generator.h \ + google/protobuf/compiler/java/java_string_field.cc \ + google/protobuf/compiler/java/java_string_field.h \ + google/protobuf/compiler/java/java_string_field_lite.cc \ + google/protobuf/compiler/java/java_string_field_lite.h \ + google/protobuf/compiler/js/js_generator.cc \ + google/protobuf/compiler/js/well_known_types_embed.cc \ + google/protobuf/compiler/js/well_known_types_embed.h \ + google/protobuf/compiler/objectivec/objectivec_enum.cc \ + google/protobuf/compiler/objectivec/objectivec_enum.h \ + google/protobuf/compiler/objectivec/objectivec_enum_field.cc \ + google/protobuf/compiler/objectivec/objectivec_enum_field.h \ + google/protobuf/compiler/objectivec/objectivec_extension.cc \ + google/protobuf/compiler/objectivec/objectivec_extension.h \ + google/protobuf/compiler/objectivec/objectivec_field.cc \ + google/protobuf/compiler/objectivec/objectivec_field.h \ + google/protobuf/compiler/objectivec/objectivec_file.cc \ + google/protobuf/compiler/objectivec/objectivec_file.h \ + google/protobuf/compiler/objectivec/objectivec_generator.cc \ + google/protobuf/compiler/objectivec/objectivec_helpers.cc \ + google/protobuf/compiler/objectivec/objectivec_map_field.cc \ + google/protobuf/compiler/objectivec/objectivec_map_field.h \ + google/protobuf/compiler/objectivec/objectivec_message.cc \ + google/protobuf/compiler/objectivec/objectivec_message.h \ + google/protobuf/compiler/objectivec/objectivec_message_field.cc \ + google/protobuf/compiler/objectivec/objectivec_message_field.h \ + google/protobuf/compiler/objectivec/objectivec_nsobject_methods.h \ + google/protobuf/compiler/objectivec/objectivec_oneof.cc \ + google/protobuf/compiler/objectivec/objectivec_oneof.h \ + google/protobuf/compiler/objectivec/objectivec_primitive_field.cc \ + google/protobuf/compiler/objectivec/objectivec_primitive_field.h \ + google/protobuf/compiler/php/php_generator.cc \ + google/protobuf/compiler/plugin.cc \ + google/protobuf/compiler/plugin.pb.cc \ + google/protobuf/compiler/python/python_generator.cc \ + google/protobuf/compiler/ruby/ruby_generator.cc \ + google/protobuf/compiler/scc.h \ + google/protobuf/compiler/subprocess.cc \ + google/protobuf/compiler/subprocess.h \ + google/protobuf/compiler/zip_writer.cc \ + google/protobuf/compiler/zip_writer.h + +bin_PROGRAMS = protoc +protoc_LDADD = $(PTHREAD_LIBS) libprotobuf.la libprotoc.la +protoc_SOURCES = google/protobuf/compiler/main.cc + +# Tests ============================================================== + +protoc_inputs = \ + google/protobuf/any_test.proto \ + google/protobuf/compiler/cpp/cpp_test_bad_identifiers.proto \ + google/protobuf/compiler/cpp/cpp_test_large_enum_value.proto \ + google/protobuf/map_lite_unittest.proto \ + google/protobuf/map_proto2_unittest.proto \ + google/protobuf/map_unittest.proto \ + google/protobuf/unittest.proto \ + google/protobuf/unittest_arena.proto \ + google/protobuf/unittest_custom_options.proto \ + google/protobuf/unittest_drop_unknown_fields.proto \ + google/protobuf/unittest_embed_optimize_for.proto \ + google/protobuf/unittest_empty.proto \ + google/protobuf/unittest_enormous_descriptor.proto \ + google/protobuf/unittest_import.proto \ + google/protobuf/unittest_import_lite.proto \ + google/protobuf/unittest_import_public.proto \ + google/protobuf/unittest_import_public_lite.proto \ + google/protobuf/unittest_lazy_dependencies.proto \ + google/protobuf/unittest_lazy_dependencies_custom_option.proto \ + google/protobuf/unittest_lazy_dependencies_enum.proto \ + google/protobuf/unittest_lite.proto \ + google/protobuf/unittest_lite_imports_nonlite.proto \ + google/protobuf/unittest_mset.proto \ + google/protobuf/unittest_mset_wire_format.proto \ + google/protobuf/unittest_no_field_presence.proto \ + google/protobuf/unittest_no_generic_services.proto \ + google/protobuf/unittest_optimize_for.proto \ + google/protobuf/unittest_preserve_unknown_enum.proto \ + google/protobuf/unittest_preserve_unknown_enum2.proto \ + google/protobuf/unittest_proto3.proto \ + google/protobuf/unittest_proto3_arena.proto \ + google/protobuf/unittest_proto3_arena_lite.proto \ + google/protobuf/unittest_proto3_lite.proto \ + google/protobuf/unittest_proto3_optional.proto \ + google/protobuf/unittest_well_known_types.proto \ + google/protobuf/util/internal/testdata/anys.proto \ + google/protobuf/util/internal/testdata/books.proto \ + google/protobuf/util/internal/testdata/default_value.proto \ + google/protobuf/util/internal/testdata/default_value_test.proto \ + google/protobuf/util/internal/testdata/field_mask.proto \ + google/protobuf/util/internal/testdata/maps.proto \ + google/protobuf/util/internal/testdata/oneofs.proto \ + google/protobuf/util/internal/testdata/proto3.proto \ + google/protobuf/util/internal/testdata/struct.proto \ + google/protobuf/util/internal/testdata/timestamp_duration.proto \ + google/protobuf/util/internal/testdata/wrappers.proto \ + google/protobuf/util/json_format.proto \ + google/protobuf/util/json_format_proto3.proto \ + google/protobuf/util/message_differencer_unittest.proto + +EXTRA_DIST = \ + $(protoc_inputs) \ + README.md \ + google/protobuf/compiler/package_info.h \ + google/protobuf/compiler/ruby/ruby_generated_code.proto \ + google/protobuf/compiler/ruby/ruby_generated_code_pb.rb \ + google/protobuf/compiler/ruby/ruby_generated_code_proto2.proto \ + google/protobuf/compiler/ruby/ruby_generated_code_proto2_import.proto \ + google/protobuf/compiler/ruby/ruby_generated_code_proto2_pb.rb \ + google/protobuf/compiler/ruby/ruby_generated_pkg_explicit.proto \ + google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_legacy.proto \ + google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_legacy_pb.rb \ + google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_pb.rb \ + google/protobuf/compiler/ruby/ruby_generated_pkg_implicit.proto \ + google/protobuf/compiler/ruby/ruby_generated_pkg_implicit_pb.rb \ + google/protobuf/compiler/zip_output_unittest.sh \ + google/protobuf/io/gzip_stream.h \ + google/protobuf/io/gzip_stream_unittest.sh \ + google/protobuf/io/package_info.h \ + google/protobuf/package_info.h \ + google/protobuf/test_messages_proto2.proto \ + google/protobuf/test_messages_proto3.proto \ + google/protobuf/testdata/bad_utf8_string \ + google/protobuf/testdata/golden_message \ + google/protobuf/testdata/golden_message_maps \ + google/protobuf/testdata/golden_message_oneof_implemented \ + google/protobuf/testdata/golden_message_proto3 \ + google/protobuf/testdata/golden_packed_fields_message \ + google/protobuf/testdata/map_test_data.txt \ + google/protobuf/testdata/text_format_unittest_data.txt \ + google/protobuf/testdata/text_format_unittest_data_oneof_implemented.txt \ + google/protobuf/testdata/text_format_unittest_data_pointy.txt \ + google/protobuf/testdata/text_format_unittest_data_pointy_oneof.txt \ + google/protobuf/testdata/text_format_unittest_extensions_data.txt \ + google/protobuf/testdata/text_format_unittest_extensions_data_pointy.txt \ + google/protobuf/util/package_info.h \ + libprotobuf-lite.map \ + libprotobuf.map \ + libprotoc.map \ + solaris/libstdc++.la + +protoc_lite_outputs = \ + google/protobuf/map_lite_unittest.pb.cc \ + google/protobuf/map_lite_unittest.pb.h \ + google/protobuf/unittest_import_lite.pb.cc \ + google/protobuf/unittest_import_lite.pb.h \ + google/protobuf/unittest_import_public_lite.pb.cc \ + google/protobuf/unittest_import_public_lite.pb.h \ + google/protobuf/unittest_lite.pb.cc \ + google/protobuf/unittest_lite.pb.h + +protoc_outputs = \ + $(protoc_lite_outputs) \ + google/protobuf/any_test.pb.cc \ + google/protobuf/any_test.pb.h \ + google/protobuf/compiler/cpp/cpp_test_bad_identifiers.pb.cc \ + google/protobuf/compiler/cpp/cpp_test_bad_identifiers.pb.h \ + google/protobuf/compiler/cpp/cpp_test_large_enum_value.pb.cc \ + google/protobuf/compiler/cpp/cpp_test_large_enum_value.pb.h \ + google/protobuf/map_proto2_unittest.pb.cc \ + google/protobuf/map_proto2_unittest.pb.h \ + google/protobuf/map_unittest.pb.cc \ + google/protobuf/map_unittest.pb.h \ + google/protobuf/unittest.pb.cc \ + google/protobuf/unittest.pb.h \ + google/protobuf/unittest_arena.pb.cc \ + google/protobuf/unittest_arena.pb.h \ + google/protobuf/unittest_custom_options.pb.cc \ + google/protobuf/unittest_custom_options.pb.h \ + google/protobuf/unittest_drop_unknown_fields.pb.cc \ + google/protobuf/unittest_drop_unknown_fields.pb.h \ + google/protobuf/unittest_embed_optimize_for.pb.cc \ + google/protobuf/unittest_embed_optimize_for.pb.h \ + google/protobuf/unittest_empty.pb.cc \ + google/protobuf/unittest_empty.pb.h \ + google/protobuf/unittest_enormous_descriptor.pb.cc \ + google/protobuf/unittest_enormous_descriptor.pb.h \ + google/protobuf/unittest_import.pb.cc \ + google/protobuf/unittest_import.pb.h \ + google/protobuf/unittest_import_public.pb.cc \ + google/protobuf/unittest_import_public.pb.h \ + google/protobuf/unittest_lazy_dependencies.pb.cc \ + google/protobuf/unittest_lazy_dependencies.pb.h \ + google/protobuf/unittest_lazy_dependencies_custom_option.pb.cc \ + google/protobuf/unittest_lazy_dependencies_custom_option.pb.h \ + google/protobuf/unittest_lazy_dependencies_enum.pb.cc \ + google/protobuf/unittest_lazy_dependencies_enum.pb.h \ + google/protobuf/unittest_lite_imports_nonlite.pb.cc \ + google/protobuf/unittest_lite_imports_nonlite.pb.h \ + google/protobuf/unittest_mset.pb.cc \ + google/protobuf/unittest_mset.pb.h \ + google/protobuf/unittest_mset_wire_format.pb.cc \ + google/protobuf/unittest_mset_wire_format.pb.h \ + google/protobuf/unittest_no_field_presence.pb.cc \ + google/protobuf/unittest_no_field_presence.pb.h \ + google/protobuf/unittest_no_generic_services.pb.cc \ + google/protobuf/unittest_no_generic_services.pb.h \ + google/protobuf/unittest_optimize_for.pb.cc \ + google/protobuf/unittest_optimize_for.pb.h \ + google/protobuf/unittest_preserve_unknown_enum.pb.cc \ + google/protobuf/unittest_preserve_unknown_enum.pb.h \ + google/protobuf/unittest_preserve_unknown_enum2.pb.cc \ + google/protobuf/unittest_preserve_unknown_enum2.pb.h \ + google/protobuf/unittest_proto3.pb.cc \ + google/protobuf/unittest_proto3.pb.h \ + google/protobuf/unittest_proto3_arena.pb.cc \ + google/protobuf/unittest_proto3_arena.pb.h \ + google/protobuf/unittest_proto3_arena_lite.pb.cc \ + google/protobuf/unittest_proto3_arena_lite.pb.h \ + google/protobuf/unittest_proto3_lite.pb.cc \ + google/protobuf/unittest_proto3_lite.pb.h \ + google/protobuf/unittest_proto3_optional.pb.cc \ + google/protobuf/unittest_proto3_optional.pb.h \ + google/protobuf/unittest_well_known_types.pb.cc \ + google/protobuf/unittest_well_known_types.pb.h \ + google/protobuf/util/internal/testdata/anys.pb.cc \ + google/protobuf/util/internal/testdata/anys.pb.h \ + google/protobuf/util/internal/testdata/books.pb.cc \ + google/protobuf/util/internal/testdata/books.pb.h \ + google/protobuf/util/internal/testdata/default_value.pb.cc \ + google/protobuf/util/internal/testdata/default_value.pb.h \ + google/protobuf/util/internal/testdata/default_value_test.pb.cc \ + google/protobuf/util/internal/testdata/default_value_test.pb.h \ + google/protobuf/util/internal/testdata/field_mask.pb.cc \ + google/protobuf/util/internal/testdata/field_mask.pb.h \ + google/protobuf/util/internal/testdata/maps.pb.cc \ + google/protobuf/util/internal/testdata/maps.pb.h \ + google/protobuf/util/internal/testdata/oneofs.pb.cc \ + google/protobuf/util/internal/testdata/oneofs.pb.h \ + google/protobuf/util/internal/testdata/proto3.pb.cc \ + google/protobuf/util/internal/testdata/proto3.pb.h \ + google/protobuf/util/internal/testdata/struct.pb.cc \ + google/protobuf/util/internal/testdata/struct.pb.h \ + google/protobuf/util/internal/testdata/timestamp_duration.pb.cc \ + google/protobuf/util/internal/testdata/timestamp_duration.pb.h \ + google/protobuf/util/internal/testdata/wrappers.pb.cc \ + google/protobuf/util/internal/testdata/wrappers.pb.h \ + google/protobuf/util/json_format.pb.cc \ + google/protobuf/util/json_format.pb.h \ + google/protobuf/util/json_format_proto3.pb.cc \ + google/protobuf/util/json_format_proto3.pb.h \ + google/protobuf/util/message_differencer_unittest.pb.cc \ + google/protobuf/util/message_differencer_unittest.pb.h + +if USE_EXTERNAL_PROTOC + +unittest_proto_middleman: $(protoc_inputs) + $(PROTOC) -I$(srcdir) --cpp_out=. $^ + touch unittest_proto_middleman + +else + +# We have to cd to $(srcdir) before executing protoc because $(protoc_inputs) is +# relative to srcdir, which may not be the same as the current directory when +# building out-of-tree. +unittest_proto_middleman: protoc$(EXEEXT) $(protoc_inputs) + oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/protoc$(EXEEXT) -I. --cpp_out=$$oldpwd $(protoc_inputs) --experimental_allow_proto3_optional ) + touch unittest_proto_middleman + +endif + +$(protoc_outputs): unittest_proto_middleman + +COMMON_TEST_SOURCES = \ + $(COMMON_LITE_TEST_SOURCES) \ + google/protobuf/compiler/cpp/cpp_unittest.h \ + google/protobuf/map_test_util.h \ + google/protobuf/map_test_util.inc \ + google/protobuf/reflection_tester.cc \ + google/protobuf/reflection_tester.h \ + google/protobuf/test_util.cc \ + google/protobuf/test_util.h \ + google/protobuf/test_util.inc \ + google/protobuf/test_util2.h \ + google/protobuf/testing/file.cc \ + google/protobuf/testing/file.h \ + google/protobuf/testing/googletest.cc \ + google/protobuf/testing/googletest.h + +GOOGLETEST_BUILD_DIR=../third_party/googletest/googletest +GOOGLEMOCK_BUILD_DIR=../third_party/googletest/googlemock +GOOGLETEST_SRC_DIR=$(srcdir)/../third_party/googletest/googletest +GOOGLEMOCK_SRC_DIR=$(srcdir)/../third_party/googletest/googlemock +check_PROGRAMS = protoc protobuf-test protobuf-lazy-descriptor-test \ + protobuf-lite-test test_plugin protobuf-lite-arena-test \ + no-warning-test $(GZCHECKPROGRAMS) +protobuf_test_LDADD = $(PTHREAD_LIBS) libprotobuf.la libprotoc.la \ + $(GOOGLETEST_BUILD_DIR)/lib/libgtest.la \ + $(GOOGLEMOCK_BUILD_DIR)/lib/libgmock.la \ + $(GOOGLEMOCK_BUILD_DIR)/lib/libgmock_main.la +protobuf_test_CPPFLAGS = -I$(GOOGLETEST_SRC_DIR)/include \ + -I$(GOOGLEMOCK_SRC_DIR)/include +# Disable optimization for tests unless the user explicitly asked for it, +# since test_util.cc takes forever to compile with optimization (with GCC). +# See configure.ac for more info. +protobuf_test_CXXFLAGS = $(NO_OPT_CXXFLAGS) +protobuf_test_SOURCES = \ + $(COMMON_TEST_SOURCES) \ + google/protobuf/any_test.cc \ + google/protobuf/arena_unittest.cc \ + google/protobuf/arenastring_unittest.cc \ + google/protobuf/compiler/annotation_test_util.cc \ + google/protobuf/compiler/annotation_test_util.h \ + google/protobuf/compiler/command_line_interface_unittest.cc \ + google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc \ + google/protobuf/compiler/cpp/cpp_move_unittest.cc \ + google/protobuf/compiler/cpp/cpp_plugin_unittest.cc \ + google/protobuf/compiler/cpp/cpp_unittest.cc \ + google/protobuf/compiler/cpp/cpp_unittest.inc \ + google/protobuf/compiler/cpp/metadata_test.cc \ + google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc \ + google/protobuf/compiler/csharp/csharp_generator_unittest.cc \ + google/protobuf/compiler/importer_unittest.cc \ + google/protobuf/compiler/java/java_doc_comment_unittest.cc \ + google/protobuf/compiler/java/java_plugin_unittest.cc \ + google/protobuf/compiler/mock_code_generator.cc \ + google/protobuf/compiler/mock_code_generator.h \ + google/protobuf/compiler/objectivec/objectivec_helpers_unittest.cc \ + google/protobuf/compiler/parser_unittest.cc \ + google/protobuf/compiler/python/python_plugin_unittest.cc \ + google/protobuf/compiler/ruby/ruby_generator_unittest.cc \ + google/protobuf/descriptor_database_unittest.cc \ + google/protobuf/descriptor_unittest.cc \ + google/protobuf/drop_unknown_fields_test.cc \ + google/protobuf/dynamic_message_unittest.cc \ + google/protobuf/extension_set_unittest.cc \ + google/protobuf/generated_message_reflection_unittest.cc \ + google/protobuf/inlined_string_field_unittest.cc \ + google/protobuf/io/coded_stream_unittest.cc \ + google/protobuf/io/io_win32_unittest.cc \ + google/protobuf/io/printer_unittest.cc \ + google/protobuf/io/tokenizer_unittest.cc \ + google/protobuf/io/zero_copy_stream_unittest.cc \ + google/protobuf/map_field_test.cc \ + google/protobuf/map_test.cc \ + google/protobuf/map_test.inc \ + google/protobuf/message_unittest.cc \ + google/protobuf/message_unittest.inc \ + google/protobuf/no_field_presence_test.cc \ + google/protobuf/preserve_unknown_enum_test.cc \ + google/protobuf/proto3_arena_lite_unittest.cc \ + google/protobuf/proto3_arena_unittest.cc \ + google/protobuf/proto3_lite_unittest.cc \ + google/protobuf/proto3_lite_unittest.inc \ + google/protobuf/reflection_ops_unittest.cc \ + google/protobuf/repeated_field_reflection_unittest.cc \ + google/protobuf/repeated_field_unittest.cc \ + google/protobuf/stubs/bytestream_unittest.cc \ + google/protobuf/stubs/common_unittest.cc \ + google/protobuf/stubs/int128_unittest.cc \ + google/protobuf/stubs/status_test.cc \ + google/protobuf/stubs/statusor_test.cc \ + google/protobuf/stubs/stringpiece_unittest.cc \ + google/protobuf/stubs/stringprintf_unittest.cc \ + google/protobuf/stubs/structurally_valid_unittest.cc \ + google/protobuf/stubs/strutil_unittest.cc \ + google/protobuf/stubs/template_util_unittest.cc \ + google/protobuf/stubs/time_test.cc \ + google/protobuf/text_format_unittest.cc \ + google/protobuf/unknown_field_set_unittest.cc \ + google/protobuf/util/delimited_message_util_test.cc \ + google/protobuf/util/field_comparator_test.cc \ + google/protobuf/util/field_mask_util_test.cc \ + google/protobuf/util/internal/default_value_objectwriter_test.cc \ + google/protobuf/util/internal/json_objectwriter_test.cc \ + google/protobuf/util/internal/json_stream_parser_test.cc \ + google/protobuf/util/internal/protostream_objectsource_test.cc \ + google/protobuf/util/internal/protostream_objectwriter_test.cc \ + google/protobuf/util/internal/type_info_test_helper.cc \ + google/protobuf/util/json_util_test.cc \ + google/protobuf/util/message_differencer_unittest.cc \ + google/protobuf/util/time_util_test.cc \ + google/protobuf/util/type_resolver_util_test.cc \ + google/protobuf/well_known_types_unittest.cc \ + google/protobuf/wire_format_unittest.cc \ + google/protobuf/wire_format_unittest.inc + +nodist_protobuf_test_SOURCES = $(protoc_outputs) +$(am_protobuf_test_OBJECTS): unittest_proto_middleman + +# Run cpp_unittest again with PROTOBUF_TEST_NO_DESCRIPTORS defined. +protobuf_lazy_descriptor_test_LDADD = $(PTHREAD_LIBS) libprotobuf.la \ + libprotoc.la \ + $(GOOGLETEST_BUILD_DIR)/lib/libgtest.la \ + $(GOOGLEMOCK_BUILD_DIR)/lib/libgmock.la \ + $(GOOGLEMOCK_BUILD_DIR)/lib/libgmock_main.la +protobuf_lazy_descriptor_test_CPPFLAGS = -I$(GOOGLEMOCK_SRC_DIR)/include \ + -I$(GOOGLETEST_SRC_DIR)/include \ + -DPROTOBUF_TEST_NO_DESCRIPTORS +protobuf_lazy_descriptor_test_CXXFLAGS = $(NO_OPT_CXXFLAGS) +protobuf_lazy_descriptor_test_SOURCES = \ + google/protobuf/compiler/cpp/cpp_unittest.cc \ + $(COMMON_TEST_SOURCES) +nodist_protobuf_lazy_descriptor_test_SOURCES = $(protoc_outputs) +$(am_protobuf_lazy_descriptor_test_OBJECTS): unittest_proto_middleman + +COMMON_LITE_TEST_SOURCES = \ + google/protobuf/arena_test_util.cc \ + google/protobuf/arena_test_util.h \ + google/protobuf/map_lite_test_util.cc \ + google/protobuf/map_lite_test_util.h \ + google/protobuf/map_test_util_impl.h \ + google/protobuf/test_util_lite.cc \ + google/protobuf/test_util_lite.h + +# Build lite_unittest separately, since it doesn't use gtest. It can't +# depend on gtest because our internal version of gtest depend on proto +# full runtime and we want to make sure this test builds without full +# runtime. +protobuf_lite_test_LDADD = $(PTHREAD_LIBS) libprotobuf-lite.la \ + $(GOOGLETEST_BUILD_DIR)/lib/libgtest.la \ + $(GOOGLEMOCK_BUILD_DIR)/lib/libgmock.la \ + $(GOOGLEMOCK_BUILD_DIR)/lib/libgmock_main.la +protobuf_lite_test_CPPFLAGS= -I$(GOOGLEMOCK_SRC_DIR)/include \ + -I$(GOOGLETEST_SRC_DIR)/include +protobuf_lite_test_CXXFLAGS = $(NO_OPT_CXXFLAGS) +protobuf_lite_test_SOURCES = \ + google/protobuf/lite_unittest.cc \ + $(COMMON_LITE_TEST_SOURCES) +nodist_protobuf_lite_test_SOURCES = $(protoc_lite_outputs) +$(am_protobuf_lite_test_OBJECTS): unittest_proto_middleman + +# lite_arena_unittest depends on gtest because teboring@ found that without +# gtest when building the test internally our memory sanitizer doesn't detect +# memory leaks (don't know why). +protobuf_lite_arena_test_LDADD = $(PTHREAD_LIBS) libprotobuf-lite.la \ + $(GOOGLETEST_BUILD_DIR)/lib/libgtest.la \ + $(GOOGLEMOCK_BUILD_DIR)/lib/libgmock.la \ + $(GOOGLEMOCK_BUILD_DIR)/lib/libgmock_main.la +protobuf_lite_arena_test_CPPFLAGS = -I$(GOOGLEMOCK_SRC_DIR)/include \ + -I$(GOOGLETEST_SRC_DIR)/include +protobuf_lite_arena_test_CXXFLAGS = $(NO_OPT_CXXFLAGS) +protobuf_lite_arena_test_SOURCES = \ + google/protobuf/lite_arena_unittest.cc \ + $(COMMON_LITE_TEST_SOURCES) +nodist_protobuf_lite_arena_test_SOURCES = $(protoc_lite_outputs) +$(am_protobuf_lite_arena_test_OBJECTS): unittest_proto_middleman + +# Test plugin binary. +test_plugin_LDADD = $(PTHREAD_LIBS) libprotobuf.la libprotoc.la \ + $(GOOGLETEST_BUILD_DIR)/lib/libgtest.la +test_plugin_CPPFLAGS = -I$(GOOGLETEST_SRC_DIR)/include +test_plugin_SOURCES = \ + google/protobuf/compiler/mock_code_generator.cc \ + google/protobuf/compiler/test_plugin.cc \ + google/protobuf/testing/file.cc \ + google/protobuf/testing/file.h + +if HAVE_ZLIB +zcgzip_LDADD = $(PTHREAD_LIBS) libprotobuf.la +zcgzip_SOURCES = google/protobuf/testing/zcgzip.cc + +zcgunzip_LDADD = $(PTHREAD_LIBS) libprotobuf.la +zcgunzip_SOURCES = google/protobuf/testing/zcgunzip.cc +endif + +# This test target is to ensure all our public header files and generated +# code is free from warnings. We have to be more pedantic about these +# files because they are compiled by users with different compiler flags. +no_warning_test.cc: + echo "// Generated from Makefile.am" > no_warning_test.cc + for FILE in $(nobase_include_HEADERS); do \ + case $$FILE in *.inc) continue;; esac; \ + echo "#include <$${FILE}>" >> no_warning_test.cc; \ + done + echo "int main(int, char**) { return 0; }" >> no_warning_test.cc + +no_warning_test_LDADD = $(PTHREAD_LIBS) libprotobuf.la libprotoc.la +no_warning_test_CXXFLAGS = $(PTHREAD_CFLAGS) $(PTHREAD_DEF) $(ZLIB_DEF) \ + -Wall -Wextra -Werror -Wno-unused-parameter +nodist_no_warning_test_SOURCES = no_warning_test.cc $(protoc_outputs) + +TESTS = protobuf-test protobuf-lazy-descriptor-test protobuf-lite-test \ + google/protobuf/compiler/zip_output_unittest.sh $(GZTESTS) \ + protobuf-lite-arena-test no-warning-test diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/any.pb.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/any.pb.cc new file mode 100644 index 0000000..52c6ccc --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/any.pb.cc @@ -0,0 +1,352 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/any.proto + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +// @@protoc_insertion_point(includes) +#include + +PROTOBUF_PRAGMA_INIT_SEG +PROTOBUF_NAMESPACE_OPEN +constexpr Any::Any( + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) + : type_url_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) + , value_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) + , _any_metadata_(&type_url_, &value_){} +struct AnyDefaultTypeInternal { + constexpr AnyDefaultTypeInternal() + : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} + ~AnyDefaultTypeInternal() {} + union { + Any _instance; + }; +}; +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT AnyDefaultTypeInternal _Any_default_instance_; +PROTOBUF_NAMESPACE_CLOSE +static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_google_2fprotobuf_2fany_2eproto[1]; +static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fany_2eproto = nullptr; +static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fany_2eproto = nullptr; + +const uint32_t TableStruct_google_2fprotobuf_2fany_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Any, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Any, type_url_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Any, value_), +}; +static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Any)}, +}; + +static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { + reinterpret_cast(&::PROTOBUF_NAMESPACE_ID::_Any_default_instance_), +}; + +const char descriptor_table_protodef_google_2fprotobuf_2fany_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = + "\n\031google/protobuf/any.proto\022\017google.prot" + "obuf\"&\n\003Any\022\020\n\010type_url\030\001 \001(\t\022\r\n\005value\030\002" + " \001(\014Bv\n\023com.google.protobufB\010AnyProtoP\001Z" + ",google.golang.org/protobuf/types/known/" + "anypb\242\002\003GPB\252\002\036Google.Protobuf.WellKnownT" + "ypesb\006proto3" + ; +static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2fany_2eproto_once; +const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fany_2eproto = { + false, false, 212, descriptor_table_protodef_google_2fprotobuf_2fany_2eproto, "google/protobuf/any.proto", + &descriptor_table_google_2fprotobuf_2fany_2eproto_once, nullptr, 0, 1, + schemas, file_default_instances, TableStruct_google_2fprotobuf_2fany_2eproto::offsets, + file_level_metadata_google_2fprotobuf_2fany_2eproto, file_level_enum_descriptors_google_2fprotobuf_2fany_2eproto, file_level_service_descriptors_google_2fprotobuf_2fany_2eproto, +}; +PROTOBUF_ATTRIBUTE_WEAK const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable* descriptor_table_google_2fprotobuf_2fany_2eproto_getter() { + return &descriptor_table_google_2fprotobuf_2fany_2eproto; +} + +// Force running AddDescriptors() at dynamic initialization time. +PROTOBUF_ATTRIBUTE_INIT_PRIORITY static ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptorsRunner dynamic_init_dummy_google_2fprotobuf_2fany_2eproto(&descriptor_table_google_2fprotobuf_2fany_2eproto); +PROTOBUF_NAMESPACE_OPEN + +// =================================================================== + +bool Any::GetAnyFieldDescriptors( + const ::PROTOBUF_NAMESPACE_ID::Message& message, + const ::PROTOBUF_NAMESPACE_ID::FieldDescriptor** type_url_field, + const ::PROTOBUF_NAMESPACE_ID::FieldDescriptor** value_field) { + return ::PROTOBUF_NAMESPACE_ID::internal::GetAnyFieldDescriptors( + message, type_url_field, value_field); +} +bool Any::ParseAnyTypeUrl( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam type_url, + std::string* full_type_name) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseAnyTypeUrl(type_url, + full_type_name); +} + +class Any::_Internal { + public: +}; + +Any::Any(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned) + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), + _any_metadata_(&type_url_, &value_) { + SharedCtor(); + if (!is_message_owned) { + RegisterArenaDtor(arena); + } + // @@protoc_insertion_point(arena_constructor:google.protobuf.Any) +} +Any::Any(const Any& from) + : ::PROTOBUF_NAMESPACE_ID::Message(), + _any_metadata_(&type_url_, &value_) { + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); + type_url_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + type_url_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (!from._internal_type_url().empty()) { + type_url_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_type_url(), + GetArenaForAllocation()); + } + value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (!from._internal_value().empty()) { + value_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_value(), + GetArenaForAllocation()); + } + // @@protoc_insertion_point(copy_constructor:google.protobuf.Any) +} + +inline void Any::SharedCtor() { +type_url_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + type_url_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING +value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING +} + +Any::~Any() { + // @@protoc_insertion_point(destructor:google.protobuf.Any) + if (GetArenaForAllocation() != nullptr) return; + SharedDtor(); + _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); +} + +inline void Any::SharedDtor() { + GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); + type_url_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + value_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); +} + +void Any::ArenaDtor(void* object) { + Any* _this = reinterpret_cast< Any* >(object); + (void)_this; +} +void Any::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { +} +void Any::SetCachedSize(int size) const { + _cached_size_.Set(size); +} + +void Any::Clear() { +// @@protoc_insertion_point(message_clear_start:google.protobuf.Any) + uint32_t cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + + type_url_.ClearToEmpty(); + value_.ClearToEmpty(); + _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); +} + +const char* Any::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { +#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure + while (!ctx->Done(&ptr)) { + uint32_t tag; + ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); + switch (tag >> 3) { + // string type_url = 1; + case 1: + if (PROTOBUF_PREDICT_TRUE(static_cast(tag) == 10)) { + auto str = _internal_mutable_type_url(); + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); + CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "google.protobuf.Any.type_url")); + CHK_(ptr); + } else + goto handle_unusual; + continue; + // bytes value = 2; + case 2: + if (PROTOBUF_PREDICT_TRUE(static_cast(tag) == 18)) { + auto str = _internal_mutable_value(); + ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); + CHK_(ptr); + } else + goto handle_unusual; + continue; + default: + goto handle_unusual; + } // switch + handle_unusual: + if ((tag == 0) || ((tag & 7) == 4)) { + CHK_(ptr); + ctx->SetLastTag(tag); + goto message_done; + } + ptr = UnknownFieldParse( + tag, + _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), + ptr, ctx); + CHK_(ptr != nullptr); + } // while +message_done: + return ptr; +failure: + ptr = nullptr; + goto message_done; +#undef CHK_ +} + +uint8_t* Any::_InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { + // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Any) + uint32_t cached_has_bits = 0; + (void) cached_has_bits; + + // string type_url = 1; + if (!this->_internal_type_url().empty()) { + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( + this->_internal_type_url().data(), static_cast(this->_internal_type_url().length()), + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, + "google.protobuf.Any.type_url"); + target = stream->WriteStringMaybeAliased( + 1, this->_internal_type_url(), target); + } + + // bytes value = 2; + if (!this->_internal_value().empty()) { + target = stream->WriteBytesMaybeAliased( + 2, this->_internal_value(), target); + } + + if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { + target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( + _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); + } + // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Any) + return target; +} + +size_t Any::ByteSizeLong() const { +// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Any) + size_t total_size = 0; + + uint32_t cached_has_bits = 0; + // Prevent compiler warnings about cached_has_bits being unused + (void) cached_has_bits; + + // string type_url = 1; + if (!this->_internal_type_url().empty()) { + total_size += 1 + + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( + this->_internal_type_url()); + } + + // bytes value = 2; + if (!this->_internal_value().empty()) { + total_size += 1 + + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( + this->_internal_value()); + } + + return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); +} + +const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Any::_class_data_ = { + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + Any::MergeImpl +}; +const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Any::GetClassData() const { return &_class_data_; } + +void Any::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, + const ::PROTOBUF_NAMESPACE_ID::Message& from) { + static_cast(to)->MergeFrom( + static_cast(from)); +} + + +void Any::MergeFrom(const Any& from) { +// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Any) + GOOGLE_DCHECK_NE(&from, this); + uint32_t cached_has_bits = 0; + (void) cached_has_bits; + + if (!from._internal_type_url().empty()) { + _internal_set_type_url(from._internal_type_url()); + } + if (!from._internal_value().empty()) { + _internal_set_value(from._internal_value()); + } + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); +} + +void Any::CopyFrom(const Any& from) { +// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.Any) + if (&from == this) return; + Clear(); + MergeFrom(from); +} + +bool Any::IsInitialized() const { + return true; +} + +void Any::InternalSwap(Any* other) { + using std::swap; + auto* lhs_arena = GetArenaForAllocation(); + auto* rhs_arena = other->GetArenaForAllocation(); + _internal_metadata_.InternalSwap(&other->_internal_metadata_); + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), + &type_url_, lhs_arena, + &other->type_url_, rhs_arena + ); + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( + &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), + &value_, lhs_arena, + &other->value_, rhs_arena + ); +} + +::PROTOBUF_NAMESPACE_ID::Metadata Any::GetMetadata() const { + return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( + &descriptor_table_google_2fprotobuf_2fany_2eproto_getter, &descriptor_table_google_2fprotobuf_2fany_2eproto_once, + file_level_metadata_google_2fprotobuf_2fany_2eproto[0]); +} + +// @@protoc_insertion_point(namespace_scope) +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOBUF_NOINLINE ::PROTOBUF_NAMESPACE_ID::Any* Arena::CreateMaybeMessage< ::PROTOBUF_NAMESPACE_ID::Any >(Arena* arena) { + return Arena::CreateMessageInternal< ::PROTOBUF_NAMESPACE_ID::Any >(arena); +} +PROTOBUF_NAMESPACE_CLOSE + +// @@protoc_insertion_point(global_scope) +#include diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/any.proto b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/any.proto new file mode 100644 index 0000000..e2c2042 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/any.proto @@ -0,0 +1,158 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package google.protobuf; + +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; +option go_package = "google.golang.org/protobuf/types/known/anypb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "AnyProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; + +// `Any` contains an arbitrary serialized protocol buffer message along with a +// URL that describes the type of the serialized message. +// +// Protobuf library provides support to pack/unpack Any values in the form +// of utility functions or additional generated methods of the Any type. +// +// Example 1: Pack and unpack a message in C++. +// +// Foo foo = ...; +// Any any; +// any.PackFrom(foo); +// ... +// if (any.UnpackTo(&foo)) { +// ... +// } +// +// Example 2: Pack and unpack a message in Java. +// +// Foo foo = ...; +// Any any = Any.pack(foo); +// ... +// if (any.is(Foo.class)) { +// foo = any.unpack(Foo.class); +// } +// +// Example 3: Pack and unpack a message in Python. +// +// foo = Foo(...) +// any = Any() +// any.Pack(foo) +// ... +// if any.Is(Foo.DESCRIPTOR): +// any.Unpack(foo) +// ... +// +// Example 4: Pack and unpack a message in Go +// +// foo := &pb.Foo{...} +// any, err := anypb.New(foo) +// if err != nil { +// ... +// } +// ... +// foo := &pb.Foo{} +// if err := any.UnmarshalTo(foo); err != nil { +// ... +// } +// +// The pack methods provided by protobuf library will by default use +// 'type.googleapis.com/full.type.name' as the type URL and the unpack +// methods only use the fully qualified type name after the last '/' +// in the type URL, for example "foo.bar.com/x/y.z" will yield type +// name "y.z". +// +// +// JSON +// +// The JSON representation of an `Any` value uses the regular +// representation of the deserialized, embedded message, with an +// additional field `@type` which contains the type URL. Example: +// +// package google.profile; +// message Person { +// string first_name = 1; +// string last_name = 2; +// } +// +// { +// "@type": "type.googleapis.com/google.profile.Person", +// "firstName": , +// "lastName": +// } +// +// If the embedded message type is well-known and has a custom JSON +// representation, that representation will be embedded adding a field +// `value` which holds the custom JSON in addition to the `@type` +// field. Example (for message [google.protobuf.Duration][]): +// +// { +// "@type": "type.googleapis.com/google.protobuf.Duration", +// "value": "1.212s" +// } +// +message Any { + // A URL/resource name that uniquely identifies the type of the serialized + // protocol buffer message. This string must contain at least + // one "/" character. The last segment of the URL's path must represent + // the fully qualified name of the type (as in + // `path/google.protobuf.Duration`). The name should be in a canonical form + // (e.g., leading "." is not accepted). + // + // In practice, teams usually precompile into the binary all types that they + // expect it to use in the context of Any. However, for URLs which use the + // scheme `http`, `https`, or no scheme, one can optionally set up a type + // server that maps type URLs to message definitions as follows: + // + // * If no scheme is provided, `https` is assumed. + // * An HTTP GET on the URL must yield a [google.protobuf.Type][] + // value in binary format, or produce an error. + // * Applications are allowed to cache lookup results based on the + // URL, or have them precompiled into a binary to avoid any + // lookup. Therefore, binary compatibility needs to be preserved + // on changes to types. (Use versioned type names to manage + // breaking changes.) + // + // Note: this functionality is not currently available in the official + // protobuf release, and it is not used for type URLs beginning with + // type.googleapis.com. + // + // Schemes other than `http`, `https` (or the empty scheme) might be + // used with implementation specific semantics. + // + string type_url = 1; + + // Must be a valid serialized protocol buffer of the above specified type. + bytes value = 2; +} diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/arena.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/arena.h new file mode 100644 index 0000000..785f273 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/arena.h @@ -0,0 +1,818 @@ +// 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. + +// This file defines an Arena allocator for better allocation performance. + +#ifndef GOOGLE_PROTOBUF_ARENA_H__ +#define GOOGLE_PROTOBUF_ARENA_H__ + + +#include +#include +#include +#if defined(_MSC_VER) && !defined(_LIBCPP_STD_VER) && !_HAS_EXCEPTIONS +// Work around bugs in MSVC header when _HAS_EXCEPTIONS=0. +#include +#include +namespace std { +using type_info = ::type_info; +} +#else +#include +#endif + +#include +#include +#include + +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif + +namespace google { +namespace protobuf { + +struct ArenaOptions; // defined below +class Arena; // defined below +class Message; // defined in message.h +class MessageLite; +template +class Map; + +namespace arena_metrics { + +void EnableArenaMetrics(ArenaOptions* options); + +} // namespace arena_metrics + +namespace TestUtil { +class ReflectionTester; // defined in test_util.h +} // namespace TestUtil + +namespace internal { + +struct ArenaStringPtr; // defined in arenastring.h +class InlinedStringField; // defined in inlined_string_field.h +class LazyField; // defined in lazy_field.h +class EpsCopyInputStream; // defined in parse_context.h + +template +class GenericTypeHandler; // defined in repeated_field.h + +inline PROTOBUF_ALWAYS_INLINE +void* AlignTo(void* ptr, size_t align) { + return reinterpret_cast( + (reinterpret_cast(ptr) + align - 1) & (~align + 1)); +} + +// Templated cleanup methods. +template +void arena_destruct_object(void* object) { + reinterpret_cast(object)->~T(); +} + +template +struct ObjectDestructor { + constexpr static void (*destructor)(void*) = &arena_destruct_object; +}; + +template +struct ObjectDestructor { + constexpr static void (*destructor)(void*) = nullptr; +}; + +template +void arena_delete_object(void* object) { + delete reinterpret_cast(object); +} +} // namespace internal + +// ArenaOptions provides optional additional parameters to arena construction +// that control its block-allocation behavior. +struct ArenaOptions { + // This defines the size of the first block requested from the system malloc. + // Subsequent block sizes will increase in a geometric series up to a maximum. + size_t start_block_size; + + // This defines the maximum block size requested from system malloc (unless an + // individual arena allocation request occurs with a size larger than this + // maximum). Requested block sizes increase up to this value, then remain + // here. + size_t max_block_size; + + // An initial block of memory for the arena to use, or NULL for none. If + // provided, the block must live at least as long as the arena itself. The + // creator of the Arena retains ownership of the block after the Arena is + // destroyed. + char* initial_block; + + // The size of the initial block, if provided. + size_t initial_block_size; + + // A function pointer to an alloc method that returns memory blocks of size + // requested. By default, it contains a ptr to the malloc function. + // + // NOTE: block_alloc and dealloc functions are expected to behave like + // malloc and free, including Asan poisoning. + void* (*block_alloc)(size_t); + // A function pointer to a dealloc method that takes ownership of the blocks + // from the arena. By default, it contains a ptr to a wrapper function that + // calls free. + void (*block_dealloc)(void*, size_t); + + ArenaOptions() + : start_block_size(internal::AllocationPolicy::kDefaultStartBlockSize), + max_block_size(internal::AllocationPolicy::kDefaultMaxBlockSize), + initial_block(NULL), + initial_block_size(0), + block_alloc(nullptr), + block_dealloc(nullptr), + make_metrics_collector(nullptr) {} + + private: + // If make_metrics_collector is not nullptr, it will be called at Arena init + // time. It may return a pointer to a collector instance that will be notified + // of interesting events related to the arena. + internal::ArenaMetricsCollector* (*make_metrics_collector)(); + + internal::ArenaMetricsCollector* MetricsCollector() const { + return make_metrics_collector ? (*make_metrics_collector)() : nullptr; + } + + internal::AllocationPolicy AllocationPolicy() const { + internal::AllocationPolicy res; + res.start_block_size = start_block_size; + res.max_block_size = max_block_size; + res.block_alloc = block_alloc; + res.block_dealloc = block_dealloc; + res.metrics_collector = MetricsCollector(); + return res; + } + + friend void arena_metrics::EnableArenaMetrics(ArenaOptions*); + + friend class Arena; + friend class ArenaOptionsTestFriend; +}; + +// Support for non-RTTI environments. (The metrics hooks API uses type +// information.) +#if PROTOBUF_RTTI +#define RTTI_TYPE_ID(type) (&typeid(type)) +#else +#define RTTI_TYPE_ID(type) (NULL) +#endif + +// Arena allocator. Arena allocation replaces ordinary (heap-based) allocation +// with new/delete, and improves performance by aggregating allocations into +// larger blocks and freeing allocations all at once. Protocol messages are +// allocated on an arena by using Arena::CreateMessage(Arena*), below, and +// are automatically freed when the arena is destroyed. +// +// This is a thread-safe implementation: multiple threads may allocate from the +// arena concurrently. Destruction is not thread-safe and the destructing +// thread must synchronize with users of the arena first. +// +// An arena provides two allocation interfaces: CreateMessage, which works +// for arena-enabled proto2 message types as well as other types that satisfy +// the appropriate protocol (described below), and Create, which works for +// any arbitrary type T. CreateMessage is better when the type T supports it, +// because this interface (i) passes the arena pointer to the created object so +// that its sub-objects and internal allocations can use the arena too, and (ii) +// elides the object's destructor call when possible. Create does not place +// any special requirements on the type T, and will invoke the object's +// destructor when the arena is destroyed. +// +// The arena message allocation protocol, required by +// CreateMessage(Arena* arena, Args&&... args), is as follows: +// +// - The type T must have (at least) two constructors: a constructor callable +// with `args` (without `arena`), called when a T is allocated on the heap; +// and a constructor callable with `Arena* arena, Args&&... args`, called when +// a T is allocated on an arena. If the second constructor is called with a +// NULL arena pointer, it must be equivalent to invoking the first +// (`args`-only) constructor. +// +// - The type T must have a particular type trait: a nested type +// |InternalArenaConstructable_|. This is usually a typedef to |void|. If no +// such type trait exists, then the instantiation CreateMessage will fail +// to compile. +// +// - The type T *may* have the type trait |DestructorSkippable_|. If this type +// trait is present in the type, then its destructor will not be called if and +// only if it was passed a non-NULL arena pointer. If this type trait is not +// present on the type, then its destructor is always called when the +// containing arena is destroyed. +// +// This protocol is implemented by all arena-enabled proto2 message classes as +// well as protobuf container types like RepeatedPtrField and Map. The protocol +// is internal to protobuf and is not guaranteed to be stable. Non-proto types +// should not rely on this protocol. +class PROTOBUF_EXPORT PROTOBUF_ALIGNAS(8) Arena final { + public: + // Default constructor with sensible default options, tuned for average + // use-cases. + inline Arena() : impl_() {} + + // Construct an arena with default options, except for the supplied + // initial block. It is more efficient to use this constructor + // instead of passing ArenaOptions if the only configuration needed + // by the caller is supplying an initial block. + inline Arena(char* initial_block, size_t initial_block_size) + : impl_(initial_block, initial_block_size) {} + + // Arena constructor taking custom options. See ArenaOptions above for + // descriptions of the options available. + explicit Arena(const ArenaOptions& options) + : impl_(options.initial_block, options.initial_block_size, + options.AllocationPolicy()) {} + + // Block overhead. Use this as a guide for how much to over-allocate the + // initial block if you want an allocation of size N to fit inside it. + // + // WARNING: if you allocate multiple objects, it is difficult to guarantee + // that a series of allocations will fit in the initial block, especially if + // Arena changes its alignment guarantees in the future! + static const size_t kBlockOverhead = + internal::ThreadSafeArena::kBlockHeaderSize + + internal::ThreadSafeArena::kSerialArenaSize; + + inline ~Arena() {} + + // TODO(protobuf-team): Fix callers to use constructor and delete this method. + void Init(const ArenaOptions&) {} + + // API to create proto2 message objects on the arena. If the arena passed in + // is NULL, then a heap allocated object is returned. Type T must be a message + // defined in a .proto file with cc_enable_arenas set to true, otherwise a + // compilation error will occur. + // + // RepeatedField and RepeatedPtrField may also be instantiated directly on an + // arena with this method. + // + // This function also accepts any type T that satisfies the arena message + // allocation protocol, documented above. + template + PROTOBUF_ALWAYS_INLINE static T* CreateMessage(Arena* arena, Args&&... args) { + static_assert( + InternalHelper::is_arena_constructable::value, + "CreateMessage can only construct types that are ArenaConstructable"); + // 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, static_cast(args)...); + } + + // API to create any objects on the arena. Note that only the object will + // be created on the arena; the underlying ptrs (in case of a proto2 message) + // will be still heap allocated. Proto messages should usually be allocated + // with CreateMessage() instead. + // + // Note that even if T satisfies the arena message construction protocol + // (InternalArenaConstructable_ trait and optional DestructorSkippable_ + // trait), as described above, this function does not follow the protocol; + // instead, it treats T as a black-box type, just as if it did not have these + // traits. Specifically, T's constructor arguments will always be only those + // passed to Create() -- no additional arena pointer is implicitly added. + // Furthermore, the destructor will always be called at arena destruction time + // (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). + template + PROTOBUF_NDEBUG_INLINE static T* Create(Arena* arena, Args&&... args) { + return CreateInternal(arena, std::is_convertible(), + static_cast(args)...); + } + + // Create an array of object type T on the arena *without* invoking the + // constructor of T. If `arena` is null, then the return value should be freed + // with `delete[] x;` (or `::operator delete[](x);`). + // 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 + PROTOBUF_NDEBUG_INLINE static T* CreateArray(Arena* arena, + size_t num_elements) { + static_assert(std::is_trivial::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))); + } else { + return arena->CreateInternalRawArray(num_elements); + } + } + + // The following are routines are for monitoring. They will approximate the + // total sum allocated and used memory, but the exact value is an + // implementation deal. For instance allocated space depends on growth + // policies. Do not use these in unit tests. + // Returns the total space allocated by the arena, which is the sum of the + // sizes of the underlying blocks. + uint64_t SpaceAllocated() const { return impl_.SpaceAllocated(); } + // Returns the total space used by the arena. Similar to SpaceAllocated but + // does not include free space and block overhead. The total space returned + // may not include space used by other threads executing concurrently with + // the call to this method. + uint64_t SpaceUsed() const { return impl_.SpaceUsed(); } + + // Frees all storage allocated by this arena after calling destructors + // registered with OwnDestructor() and freeing objects registered with Own(). + // Any objects allocated on this arena are unusable after this call. It also + // returns the total space used by the arena which is the sums of the sizes + // of the allocated blocks. This method is not thread-safe. + uint64_t Reset() { return impl_.Reset(); } + + // Adds |object| to a list of heap-allocated objects to be freed with |delete| + // when the arena is destroyed or reset. + template + PROTOBUF_ALWAYS_INLINE void Own(T* object) { + OwnInternal(object, std::is_convertible()); + } + + // Adds |object| to a list of objects whose destructors will be manually + // called when the arena is destroyed or reset. This differs from Own() in + // 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 + PROTOBUF_ALWAYS_INLINE void OwnDestructor(T* object) { + if (object != NULL) { + impl_.AddCleanup(object, &internal::arena_destruct_object); + } + } + + // Adds a custom member function on an object to the list of destructors that + // will be manually called when the arena is destroyed or reset. This differs + // from OwnDestructor() in that any member function may be specified, not only + // the class destructor. + PROTOBUF_ALWAYS_INLINE void OwnCustomDestructor(void* object, + void (*destruct)(void*)) { + impl_.AddCleanup(object, destruct); + } + + // Retrieves the arena associated with |value| if |value| is an arena-capable + // message, or NULL otherwise. If possible, the call resolves at compile time. + // Note that we can often devirtualize calls to `value->GetArena()` so usually + // calling this method is unnecessary. + template + PROTOBUF_ALWAYS_INLINE static Arena* GetArena(const T* value) { + return GetArenaInternal(value); + } + + template + class InternalHelper { + public: + // Provides access to protected GetOwningArena to generated messages. + static Arena* GetOwningArena(const T* p) { return p->GetOwningArena(); } + + // Provides access to protected GetArenaForAllocation to generated messages. + static Arena* GetArenaForAllocation(const T* p) { + return GetArenaForAllocationInternal( + p, std::is_convertible()); + } + + // Creates message-owned arena. + static Arena* CreateMessageOwnedArena() { + return new Arena(internal::MessageOwned{}); + } + + // Checks whether the given arena is message-owned. + static bool IsMessageOwnedArena(Arena* arena) { + return arena->IsMessageOwned(); + } + + private: + static Arena* GetArenaForAllocationInternal( + const T* p, std::true_type /*is_derived_from*/) { + return p->GetArenaForAllocation(); + } + + static Arena* GetArenaForAllocationInternal( + const T* p, std::false_type /*is_derived_from*/) { + return GetArenaForAllocationForNonMessage( + p, typename is_arena_constructable::type()); + } + + static Arena* GetArenaForAllocationForNonMessage( + const T* p, std::true_type /*is_arena_constructible*/) { + return p->GetArena(); + } + + static Arena* GetArenaForAllocationForNonMessage( + const T* p, std::false_type /*is_arena_constructible*/) { + return GetArenaForAllocationForNonMessageNonArenaConstructible( + p, typename has_get_arena::type()); + } + + static Arena* GetArenaForAllocationForNonMessageNonArenaConstructible( + const T* p, std::true_type /*has_get_arena*/) { + return p->GetArena(); + } + + static Arena* GetArenaForAllocationForNonMessageNonArenaConstructible( + const T* /* p */, std::false_type /*has_get_arena*/) { + return nullptr; + } + + template + static char DestructorSkippable(const typename U::DestructorSkippable_*); + template + static double DestructorSkippable(...); + + typedef std::integral_constant< + bool, sizeof(DestructorSkippable(static_cast(0))) == + sizeof(char) || + std::is_trivially_destructible::value> + is_destructor_skippable; + + template + static char ArenaConstructable( + const typename U::InternalArenaConstructable_*); + template + static double ArenaConstructable(...); + + typedef std::integral_constant( + static_cast(0))) == + sizeof(char)> + is_arena_constructable; + + template () + .GetArena())>::value, + int>::type = 0> + static char HasGetArena(decltype(&U::GetArena)); + template + static double HasGetArena(...); + + typedef std::integral_constant(nullptr)) == + sizeof(char)> + has_get_arena; + + template + static T* Construct(void* ptr, Args&&... args) { + return new (ptr) T(static_cast(args)...); + } + + static inline PROTOBUF_ALWAYS_INLINE T* New() { + return new T(nullptr); + } + + static Arena* GetArena(const T* p) { return p->GetArena(); } + + friend class Arena; + friend class TestUtil::ReflectionTester; + }; + + // 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. + // + // 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: + internal::ThreadSafeArena impl_; + + template + struct has_get_arena : InternalHelper::has_get_arena {}; + + // Constructor solely used by message-owned arena. + inline Arena(internal::MessageOwned) : impl_(internal::MessageOwned{}) {} + + // Checks whether this arena is message-owned. + PROTOBUF_ALWAYS_INLINE bool IsMessageOwned() const { + return impl_.IsMessageOwned(); + } + + template + PROTOBUF_NDEBUG_INLINE static T* CreateMessageInternal(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(nullptr, static_cast(args)...); + } else { + return arena->DoCreateMessage(static_cast(args)...); + } + } + + // 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 + PROTOBUF_NDEBUG_INLINE static T* CreateMessageInternal(Arena* arena) { + static_assert( + InternalHelper::is_arena_constructable::value, + "CreateMessage can only construct types that are ArenaConstructable"); + if (arena == NULL) { + // Generated arena constructor T(Arena*) is protected. Call via + // InternalHelper. + return InternalHelper::New(); + } else { + return arena->DoCreateMessage(); + } + } + + // Allocate and also optionally call collector with the allocated type info + // when allocation recording is enabled. + PROTOBUF_NDEBUG_INLINE void* AllocateInternal(size_t size, size_t align, + void (*destructor)(void*), + const std::type_info* type) { + // Monitor allocation if needed. + if (destructor == nullptr) { + return AllocateAlignedWithHook(size, align, type); + } else { + if (align <= 8) { + auto res = AllocateAlignedWithCleanup(internal::AlignUpTo8(size), type); + res.second->elem = res.first; + res.second->cleanup = destructor; + return res.first; + } else { + auto res = AllocateAlignedWithCleanup(size + align - 8, type); + auto ptr = internal::AlignTo(res.first, align); + res.second->elem = ptr; + res.second->cleanup = destructor; + return ptr; + } + } + } + + // CreateMessage requires that T supports arenas, but this private method + // works whether or not T supports arenas. These are not exposed to user code + // 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 + PROTOBUF_ALWAYS_INLINE static Msg* DoCreateMaybeMessage(Arena* arena, + std::true_type, + Args&&... args) { + return CreateMessageInternal(arena, std::forward(args)...); + } + + template + PROTOBUF_ALWAYS_INLINE static T* DoCreateMaybeMessage(Arena* arena, + std::false_type, + Args&&... args) { + return Create(arena, std::forward(args)...); + } + + template + PROTOBUF_ALWAYS_INLINE static T* CreateMaybeMessage(Arena* arena, + Args&&... args) { + return DoCreateMaybeMessage(arena, is_arena_constructable(), + std::forward(args)...); + } + + // Just allocate the required size for the given type assuming the + // type has a trivial constructor. + template + PROTOBUF_NDEBUG_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."; + // We count on compiler to realize that if sizeof(T) is a multiple of + // 8 AlignUpTo can be elided. + const size_t n = sizeof(T) * num_elements; + return static_cast( + AllocateAlignedWithHook(n, alignof(T), RTTI_TYPE_ID(T))); + } + + template + PROTOBUF_NDEBUG_INLINE T* DoCreateMessage(Args&&... args) { + return InternalHelper::Construct( + AllocateInternal(sizeof(T), alignof(T), + internal::ObjectDestructor< + InternalHelper::is_destructor_skippable::value, + T>::destructor, + RTTI_TYPE_ID(T)), + this, std::forward(args)...); + } + + // CreateInArenaStorage is used to implement map field. Without it, + // Map need to call generated message's protected arena constructor, + // which needs to declare Map as friend of generated message. + template + static void CreateInArenaStorage(T* ptr, Arena* arena, Args&&... args) { + CreateInArenaStorageInternal(ptr, arena, + typename is_arena_constructable::type(), + std::forward(args)...); + if (arena != nullptr) { + RegisterDestructorInternal( + ptr, arena, + typename InternalHelper::is_destructor_skippable::type()); + } + } + + template + static void CreateInArenaStorageInternal(T* ptr, Arena* arena, + std::true_type, Args&&... args) { + InternalHelper::Construct(ptr, arena, std::forward(args)...); + } + template + static void CreateInArenaStorageInternal(T* ptr, Arena* /* arena */, + std::false_type, Args&&... args) { + new (ptr) T(std::forward(args)...); + } + + template + static void RegisterDestructorInternal(T* /* ptr */, Arena* /* arena */, + std::true_type) {} + template + static void RegisterDestructorInternal(T* ptr, Arena* arena, + std::false_type) { + arena->OwnDestructor(ptr); + } + + // These implement Create(). The second parameter has type 'true_type' if T is + // a subtype of Message and 'false_type' otherwise. + template + PROTOBUF_ALWAYS_INLINE static T* CreateInternal(Arena* arena, std::true_type, + Args&&... args) { + if (arena == nullptr) { + return new T(std::forward(args)...); + } else { + auto destructor = + internal::ObjectDestructor::value, + T>::destructor; + T* result = + new (arena->AllocateInternal(sizeof(T), alignof(T), destructor, + RTTI_TYPE_ID(T))) + T(std::forward(args)...); + return result; + } + } + template + PROTOBUF_ALWAYS_INLINE static T* CreateInternal(Arena* arena, std::false_type, + Args&&... args) { + if (arena == nullptr) { + return new T(std::forward(args)...); + } else { + auto destructor = + internal::ObjectDestructor::value, + T>::destructor; + return new (arena->AllocateInternal(sizeof(T), alignof(T), destructor, + RTTI_TYPE_ID(T))) + T(std::forward(args)...); + } + } + + // These implement Own(), which registers an object for deletion (destructor + // call and operator delete()). The second parameter has type 'true_type' if T + // is a subtype of Message and 'false_type' otherwise. Collapsing + // all template instantiations to one for generic Message reduces code size, + // using the virtual destructor instead. + template + PROTOBUF_ALWAYS_INLINE void OwnInternal(T* object, std::true_type) { + if (object != NULL) { + impl_.AddCleanup(object, &internal::arena_delete_object); + } + } + template + PROTOBUF_ALWAYS_INLINE void OwnInternal(T* object, std::false_type) { + if (object != NULL) { + impl_.AddCleanup(object, &internal::arena_delete_object); + } + } + + // Implementation for GetArena(). Only message objects with + // InternalArenaConstructable_ tags can be associated with an arena, and such + // objects must implement a GetArena() method. + template ::value, int>::type = 0> + PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* value) { + return InternalHelper::GetArena(value); + } + template ::value && + has_get_arena::value, + int>::type = 0> + PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* value) { + return value->GetArena(); + } + template ::value && + !has_get_arena::value, + int>::type = 0> + PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* value) { + (void)value; + return nullptr; + } + + template + PROTOBUF_ALWAYS_INLINE static Arena* GetOwningArena(const T* value) { + return GetOwningArenaInternal( + value, std::is_convertible()); + } + + // Implementation for GetOwningArena(). All and only message objects have + // GetOwningArena() method. + template + PROTOBUF_ALWAYS_INLINE static Arena* GetOwningArenaInternal( + const T* value, std::true_type) { + return InternalHelper::GetOwningArena(value); + } + template + PROTOBUF_ALWAYS_INLINE static Arena* GetOwningArenaInternal( + const T* /* value */, std::false_type) { + return nullptr; + } + + // For friends of arena. + void* AllocateAligned(size_t n, size_t align = 8) { + if (align <= 8) { + return AllocateAlignedNoHook(internal::AlignUpTo8(n)); + } else { + // We are wasting space by over allocating align - 8 bytes. Compared + // to a dedicated function that takes current alignment in consideration. + // Such a scheme would only waste (align - 8)/2 bytes on average, but + // requires a dedicated function in the outline arena allocation + // functions. Possibly re-evaluate tradeoffs later. + return internal::AlignTo(AllocateAlignedNoHook(n + align - 8), align); + } + } + + void* AllocateAlignedWithHook(size_t n, size_t align, + const std::type_info* type) { + if (align <= 8) { + return AllocateAlignedWithHook(internal::AlignUpTo8(n), type); + } else { + // We are wasting space by over allocating align - 8 bytes. Compared + // to a dedicated function that takes current alignment in consideration. + // Such a schemee would only waste (align - 8)/2 bytes on average, but + // requires a dedicated function in the outline arena allocation + // functions. Possibly re-evaluate tradeoffs later. + return internal::AlignTo(AllocateAlignedWithHook(n + align - 8, type), + align); + } + } + + void* AllocateAlignedNoHook(size_t n); + void* AllocateAlignedWithHook(size_t n, const std::type_info* type); + std::pair + AllocateAlignedWithCleanup(size_t n, const std::type_info* type); + + template + friend class internal::GenericTypeHandler; + friend struct internal::ArenaStringPtr; // For AllocateAligned. + friend class internal::InlinedStringField; // For AllocateAligned. + friend class internal::LazyField; // For CreateMaybeMessage. + friend class internal::EpsCopyInputStream; // For parser performance + friend class MessageLite; + template + friend class Map; +}; + +// Defined above for supporting environments without RTTI. +#undef RTTI_TYPE_ID + +} // namespace protobuf +} // namespace google + +#include + +#endif // GOOGLE_PROTOBUF_ARENA_H__ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/command_line_interface.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/command_line_interface.cc new file mode 100644 index 0000000..6cd17ea --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/command_line_interface.cc @@ -0,0 +1,2618 @@ +// 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. + +#include + +#include + +#include + +#include +#include +#ifdef major +#undef major +#endif +#ifdef minor +#undef minor +#endif +#include +#include +#ifndef _MSC_VER +#include +#endif +#include +#include +#include +#include + +#include //For PATH_MAX + +#include + +#if defined(__APPLE__) +#include +#elif defined(__FreeBSD__) +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#include + +namespace google { +namespace protobuf { +namespace compiler { + +#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 + +namespace { +#if defined(_WIN32) +// DO NOT include , instead create functions in io_win32.{h,cc} and import +// them like we do below. +using google::protobuf::io::win32::access; +using google::protobuf::io::win32::close; +using google::protobuf::io::win32::mkdir; +using google::protobuf::io::win32::open; +using google::protobuf::io::win32::setmode; +using google::protobuf::io::win32::write; +#endif + +static const char* kDefaultDirectDependenciesViolationMsg = + "File is imported but not declared in --direct_dependencies: %s"; + +// Returns true if the text looks like a Windows-style absolute path, starting +// with a drive letter. Example: "C:\foo". TODO(kenton): Share this with +// copy in importer.cc? +static bool IsWindowsAbsolutePath(const std::string& text) { +#if defined(_WIN32) || defined(__CYGWIN__) + return text.size() >= 3 && text[1] == ':' && isalpha(text[0]) && + (text[2] == '/' || text[2] == '\\') && text.find_last_of(':') == 1; +#else + return false; +#endif +} + +void SetFdToTextMode(int fd) { +#ifdef _WIN32 + if (setmode(fd, _O_TEXT) == -1) { + // This should never happen, I think. + GOOGLE_LOG(WARNING) << "setmode(" << fd << ", _O_TEXT): " << strerror(errno); + } +#endif + // (Text and binary are the same on non-Windows platforms.) +} + +void SetFdToBinaryMode(int fd) { +#ifdef _WIN32 + if (setmode(fd, _O_BINARY) == -1) { + // This should never happen, I think. + GOOGLE_LOG(WARNING) << "setmode(" << fd << ", _O_BINARY): " << strerror(errno); + } +#endif + // (Text and binary are the same on non-Windows platforms.) +} + +void AddTrailingSlash(std::string* path) { + if (!path->empty() && path->at(path->size() - 1) != '/') { + path->push_back('/'); + } +} + +bool VerifyDirectoryExists(const std::string& path) { + if (path.empty()) return true; + + if (access(path.c_str(), F_OK) == -1) { + std::cerr << path << ": " << strerror(errno) << std::endl; + return false; + } else { + return true; + } +} + +// Try to create the parent directory of the given file, creating the parent's +// parent if necessary, and so on. The full file name is actually +// (prefix + filename), but we assume |prefix| already exists and only create +// directories listed in |filename|. +bool TryCreateParentDirectory(const std::string& prefix, + const std::string& filename) { + // Recursively create parent directories to the output file. + // On Windows, both '/' and '\' are valid path separators. + std::vector parts = + Split(filename, "/\\", true); + std::string path_so_far = prefix; + for (int i = 0; i < parts.size() - 1; i++) { + path_so_far += parts[i]; + if (mkdir(path_so_far.c_str(), 0777) != 0) { + if (errno != EEXIST) { + std::cerr << filename << ": while trying to create directory " + << path_so_far << ": " << strerror(errno) << std::endl; + return false; + } + } + path_so_far += '/'; + } + + return true; +} + +// Get the absolute path of this protoc binary. +bool GetProtocAbsolutePath(std::string* path) { +#ifdef _WIN32 + char buffer[MAX_PATH]; + int len = GetModuleFileNameA(NULL, buffer, MAX_PATH); +#elif defined(__APPLE__) + char buffer[PATH_MAX]; + int len = 0; + + char dirtybuffer[PATH_MAX]; + uint32_t size = sizeof(dirtybuffer); + if (_NSGetExecutablePath(dirtybuffer, &size) == 0) { + realpath(dirtybuffer, buffer); + len = strlen(buffer); + } +#elif defined(__FreeBSD__) + char buffer[PATH_MAX]; + size_t len = PATH_MAX; + int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1}; + if (sysctl(mib, 4, &buffer, &len, NULL, 0) != 0) { + len = 0; + } +#else + char buffer[PATH_MAX]; + int len = readlink("/proc/self/exe", buffer, PATH_MAX); +#endif + if (len > 0) { + path->assign(buffer, len); + return true; + } else { + return false; + } +} + +// Whether a path is where google/protobuf/descriptor.proto and other well-known +// type protos are installed. +bool IsInstalledProtoPath(const std::string& path) { + // Checking the descriptor.proto file should be good enough. + std::string file_path = path + "/google/protobuf/descriptor.proto"; + return access(file_path.c_str(), F_OK) != -1; +} + +// Add the paths where google/protobuf/descriptor.proto and other well-known +// type protos are installed. +void AddDefaultProtoPaths( + std::vector>* paths) { + // TODO(xiaofeng): The code currently only checks relative paths of where + // the protoc binary is installed. We probably should make it handle more + // cases than that. + std::string path; + if (!GetProtocAbsolutePath(&path)) { + return; + } + // Strip the binary name. + size_t pos = path.find_last_of("/\\"); + if (pos == std::string::npos || pos == 0) { + return; + } + path = path.substr(0, pos); + // Check the binary's directory. + if (IsInstalledProtoPath(path)) { + paths->push_back(std::pair("", path)); + return; + } + // Check if there is an include subdirectory. + if (IsInstalledProtoPath(path + "/include")) { + paths->push_back( + std::pair("", path + "/include")); + return; + } + // Check if the upper level directory has an "include" subdirectory. + pos = path.find_last_of("/\\"); + if (pos == std::string::npos || pos == 0) { + return; + } + path = path.substr(0, pos); + if (IsInstalledProtoPath(path + "/include")) { + paths->push_back( + std::pair("", path + "/include")); + return; + } +} + +std::string PluginName(const std::string& plugin_prefix, + const std::string& directive) { + // Assuming the directive starts with "--" and ends with "_out" or "_opt", + // strip the "--" and "_out/_opt" and add the plugin prefix. + return plugin_prefix + "gen-" + directive.substr(2, directive.size() - 6); +} + +} // namespace + +// A MultiFileErrorCollector that prints errors to stderr. +class CommandLineInterface::ErrorPrinter + : public MultiFileErrorCollector, + public io::ErrorCollector, + public DescriptorPool::ErrorCollector { + public: + ErrorPrinter(ErrorFormat format, DiskSourceTree* tree = NULL) + : format_(format), + tree_(tree), + found_errors_(false), + found_warnings_(false) {} + ~ErrorPrinter() {} + + // implements MultiFileErrorCollector ------------------------------ + void AddError(const std::string& filename, int line, int column, + const std::string& message) override { + found_errors_ = true; + AddErrorOrWarning(filename, line, column, message, "error", std::cerr); + } + + void AddWarning(const std::string& filename, int line, int column, + const std::string& message) override { + found_warnings_ = true; + AddErrorOrWarning(filename, line, column, message, "warning", std::clog); + } + + // implements io::ErrorCollector ----------------------------------- + void AddError(int line, int column, const std::string& message) override { + AddError("input", line, column, message); + } + + void AddWarning(int line, int column, const std::string& message) override { + AddErrorOrWarning("input", line, column, message, "warning", std::clog); + } + + // implements DescriptorPool::ErrorCollector------------------------- + void AddError(const std::string& filename, const std::string& element_name, + const Message* descriptor, ErrorLocation location, + const std::string& message) override { + AddErrorOrWarning(filename, -1, -1, message, "error", std::cerr); + } + + void AddWarning(const std::string& filename, const std::string& element_name, + const Message* descriptor, ErrorLocation location, + const std::string& message) override { + AddErrorOrWarning(filename, -1, -1, message, "warning", std::clog); + } + + bool FoundErrors() const { return found_errors_; } + + bool FoundWarnings() const { return found_warnings_; } + + private: + void AddErrorOrWarning(const std::string& filename, int line, int column, + const std::string& message, const std::string& type, + std::ostream& out) { + // Print full path when running under MSVS + std::string dfile; + if (format_ == CommandLineInterface::ERROR_FORMAT_MSVS && tree_ != NULL && + tree_->VirtualFileToDiskFile(filename, &dfile)) { + out << dfile; + } else { + out << filename; + } + + // Users typically expect 1-based line/column numbers, so we add 1 + // to each here. + if (line != -1) { + // Allow for both GCC- and Visual-Studio-compatible output. + switch (format_) { + case CommandLineInterface::ERROR_FORMAT_GCC: + out << ":" << (line + 1) << ":" << (column + 1); + break; + case CommandLineInterface::ERROR_FORMAT_MSVS: + out << "(" << (line + 1) << ") : " << type + << " in column=" << (column + 1); + break; + } + } + + if (type == "warning") { + out << ": warning: " << message << std::endl; + } else { + out << ": " << message << std::endl; + } + } + + const ErrorFormat format_; + DiskSourceTree* tree_; + bool found_errors_; + bool found_warnings_; +}; + +// ------------------------------------------------------------------- + +// A GeneratorContext implementation that buffers files in memory, then dumps +// them all to disk on demand. +class CommandLineInterface::GeneratorContextImpl : public GeneratorContext { + public: + GeneratorContextImpl(const std::vector& parsed_files); + + // Write all files in the directory to disk at the given output location, + // which must end in a '/'. + bool WriteAllToDisk(const std::string& prefix); + + // Write the contents of this directory to a ZIP-format archive with the + // given name. + bool WriteAllToZip(const std::string& filename); + + // Add a boilerplate META-INF/MANIFEST.MF file as required by the Java JAR + // format, unless one has already been written. + void AddJarManifest(); + + // Get name of all output files. + void GetOutputFilenames(std::vector* output_filenames); + + // implements GeneratorContext -------------------------------------- + io::ZeroCopyOutputStream* Open(const std::string& filename) override; + io::ZeroCopyOutputStream* OpenForAppend(const std::string& filename) override; + io::ZeroCopyOutputStream* OpenForInsert( + const std::string& filename, const std::string& insertion_point) override; + io::ZeroCopyOutputStream* OpenForInsertWithGeneratedCodeInfo( + const std::string& filename, const std::string& insertion_point, + const google::protobuf::GeneratedCodeInfo& info) override; + void ListParsedFiles(std::vector* output) override { + *output = parsed_files_; + } + + private: + friend class MemoryOutputStream; + + // The files_ field maps from path keys to file content values. It's a map + // instead of an unordered_map so that files are written in order (good when + // writing zips). + std::map files_; + const std::vector& parsed_files_; + bool had_error_; +}; + +class CommandLineInterface::MemoryOutputStream + : public io::ZeroCopyOutputStream { + public: + MemoryOutputStream(GeneratorContextImpl* directory, + const std::string& filename, bool append_mode); + MemoryOutputStream(GeneratorContextImpl* directory, + const std::string& filename, + const std::string& insertion_point); + MemoryOutputStream(GeneratorContextImpl* directory, + const std::string& filename, + const std::string& insertion_point, + const google::protobuf::GeneratedCodeInfo& info); + virtual ~MemoryOutputStream(); + + // implements ZeroCopyOutputStream --------------------------------- + bool Next(void** data, int* size) override { + return inner_->Next(data, size); + } + void BackUp(int count) override { inner_->BackUp(count); } + int64_t ByteCount() const override { return inner_->ByteCount(); } + + private: + // Checks to see if "filename_.pb.meta" exists in directory_; if so, fixes the + // offsets in that GeneratedCodeInfo record to reflect bytes inserted in + // filename_ at original offset insertion_offset with length insertion_length. + // Also adds in the data from info_to_insert_ with updated offsets governed by + // insertion_offset and indent_length. We assume that insertions will not + // occur within any given annotated span of text. insertion_content must end + // with an endline. + void UpdateMetadata(const std::string& insertion_content, + size_t insertion_offset, size_t insertion_length, + size_t indent_length); + + // Inserts info_to_insert_ into target_info, assuming that the relevant + // insertion was made at insertion_offset in file_content with the given + // indent_length. insertion_content must end with an endline. + void InsertShiftedInfo(const std::string& insertion_content, + size_t insertion_offset, size_t indent_length, + google::protobuf::GeneratedCodeInfo& target_info); + + // Where to insert the string when it's done. + GeneratorContextImpl* directory_; + std::string filename_; + std::string insertion_point_; + + // The string we're building. + std::string data_; + + // Whether we should append the output stream to the existing file. + bool append_mode_; + + // StringOutputStream writing to data_. + std::unique_ptr inner_; + + // The GeneratedCodeInfo to insert at the insertion point. + google::protobuf::GeneratedCodeInfo info_to_insert_; +}; + +// ------------------------------------------------------------------- + +CommandLineInterface::GeneratorContextImpl::GeneratorContextImpl( + const std::vector& parsed_files) + : parsed_files_(parsed_files), had_error_(false) {} + +bool CommandLineInterface::GeneratorContextImpl::WriteAllToDisk( + const std::string& prefix) { + if (had_error_) { + return false; + } + + if (!VerifyDirectoryExists(prefix)) { + return false; + } + + for (const auto& pair : files_) { + const std::string& relative_filename = pair.first; + const char* data = pair.second.data(); + int size = pair.second.size(); + + if (!TryCreateParentDirectory(prefix, relative_filename)) { + return false; + } + std::string filename = prefix + relative_filename; + + // Create the output file. + int file_descriptor; + do { + file_descriptor = + open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666); + } while (file_descriptor < 0 && errno == EINTR); + + if (file_descriptor < 0) { + int error = errno; + std::cerr << filename << ": " << strerror(error); + return false; + } + + // Write the file. + while (size > 0) { + int write_result; + do { + write_result = write(file_descriptor, data, size); + } while (write_result < 0 && errno == EINTR); + + if (write_result <= 0) { + // Write error. + + // FIXME(kenton): According to the man page, if write() returns zero, + // there was no error; write() simply did not write anything. It's + // unclear under what circumstances this might happen, but presumably + // errno won't be set in this case. I am confused as to how such an + // event should be handled. For now I'm treating it as an error, + // since retrying seems like it could lead to an infinite loop. I + // suspect this never actually happens anyway. + + if (write_result < 0) { + int error = errno; + std::cerr << filename << ": write: " << strerror(error); + } else { + std::cerr << filename << ": write() returned zero?" << std::endl; + } + return false; + } + + data += write_result; + size -= write_result; + } + + if (close(file_descriptor) != 0) { + int error = errno; + std::cerr << filename << ": close: " << strerror(error); + return false; + } + } + + return true; +} + +bool CommandLineInterface::GeneratorContextImpl::WriteAllToZip( + const std::string& filename) { + if (had_error_) { + return false; + } + + // Create the output file. + int file_descriptor; + do { + file_descriptor = + open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666); + } while (file_descriptor < 0 && errno == EINTR); + + if (file_descriptor < 0) { + int error = errno; + std::cerr << filename << ": " << strerror(error); + return false; + } + + // Create the ZipWriter + io::FileOutputStream stream(file_descriptor); + ZipWriter zip_writer(&stream); + + for (const auto& pair : files_) { + zip_writer.Write(pair.first, pair.second); + } + + zip_writer.WriteDirectory(); + + if (stream.GetErrno() != 0) { + std::cerr << filename << ": " << strerror(stream.GetErrno()) << std::endl; + return false; + } + + if (!stream.Close()) { + std::cerr << filename << ": " << strerror(stream.GetErrno()) << std::endl; + return false; + } + + return true; +} + +void CommandLineInterface::GeneratorContextImpl::AddJarManifest() { + auto pair = files_.insert({"META-INF/MANIFEST.MF", ""}); + if (pair.second) { + pair.first->second = + "Manifest-Version: 1.0\n" + "Created-By: 1.6.0 (protoc)\n" + "\n"; + } +} + +void CommandLineInterface::GeneratorContextImpl::GetOutputFilenames( + std::vector* output_filenames) { + for (const auto& pair : files_) { + output_filenames->push_back(pair.first); + } +} + +io::ZeroCopyOutputStream* CommandLineInterface::GeneratorContextImpl::Open( + const std::string& filename) { + return new MemoryOutputStream(this, filename, false); +} + +io::ZeroCopyOutputStream* +CommandLineInterface::GeneratorContextImpl::OpenForAppend( + const std::string& filename) { + return new MemoryOutputStream(this, filename, true); +} + +io::ZeroCopyOutputStream* +CommandLineInterface::GeneratorContextImpl::OpenForInsert( + const std::string& filename, const std::string& insertion_point) { + return new MemoryOutputStream(this, filename, insertion_point); +} + +io::ZeroCopyOutputStream* +CommandLineInterface::GeneratorContextImpl::OpenForInsertWithGeneratedCodeInfo( + const std::string& filename, const std::string& insertion_point, + const google::protobuf::GeneratedCodeInfo& info) { + return new MemoryOutputStream(this, filename, insertion_point, info); +} + +// ------------------------------------------------------------------- + +CommandLineInterface::MemoryOutputStream::MemoryOutputStream( + GeneratorContextImpl* directory, const std::string& filename, + bool append_mode) + : directory_(directory), + filename_(filename), + append_mode_(append_mode), + inner_(new io::StringOutputStream(&data_)) {} + +CommandLineInterface::MemoryOutputStream::MemoryOutputStream( + GeneratorContextImpl* directory, const std::string& filename, + const std::string& insertion_point) + : directory_(directory), + filename_(filename), + insertion_point_(insertion_point), + inner_(new io::StringOutputStream(&data_)) {} + +CommandLineInterface::MemoryOutputStream::MemoryOutputStream( + GeneratorContextImpl* directory, const std::string& filename, + const std::string& insertion_point, const google::protobuf::GeneratedCodeInfo& info) + : directory_(directory), + filename_(filename), + insertion_point_(insertion_point), + inner_(new io::StringOutputStream(&data_)), + info_to_insert_(info) {} + +void CommandLineInterface::MemoryOutputStream::InsertShiftedInfo( + const std::string& insertion_content, size_t insertion_offset, + size_t indent_length, google::protobuf::GeneratedCodeInfo& target_info) { + // Keep track of how much extra data was added for indents before the + // current annotation being inserted. `pos` and `source_annotation.begin()` + // are offsets in `insertion_content`. `insertion_offset` is updated so that + // it can be added to an annotation's `begin` field to reflect that + // annotation's updated location after `insertion_content` was inserted into + // the target file. + size_t pos = 0; + insertion_offset += indent_length; + for (const auto& source_annotation : info_to_insert_.annotation()) { + GeneratedCodeInfo::Annotation* annotation = target_info.add_annotation(); + int inner_indent = 0; + // insertion_content is guaranteed to end in an endline. This last endline + // has no effect on indentation. + for (; pos < source_annotation.end() && pos < insertion_content.size() - 1; + ++pos) { + if (insertion_content[pos] == '\n') { + if (pos >= source_annotation.begin()) { + // The beginning of the annotation is at insertion_offset, but the end + // can still move further in the target file. + inner_indent += indent_length; + } else { + insertion_offset += indent_length; + } + } + } + *annotation = source_annotation; + annotation->set_begin(annotation->begin() + insertion_offset); + insertion_offset += inner_indent; + annotation->set_end(annotation->end() + insertion_offset); + } +} + +void CommandLineInterface::MemoryOutputStream::UpdateMetadata( + const std::string& insertion_content, size_t insertion_offset, + size_t insertion_length, size_t indent_length) { + auto it = directory_->files_.find(filename_ + ".pb.meta"); + if (it == directory_->files_.end() && info_to_insert_.annotation().empty()) { + // No metadata was recorded for this file. + return; + } + GeneratedCodeInfo metadata; + bool is_text_format = false; + std::string* encoded_data = nullptr; + if (it != directory_->files_.end()) { + encoded_data = &it->second; + // Try to decode a GeneratedCodeInfo proto from the .pb.meta file. It may be + // in wire or text format. Keep the same format when the data is written out + // later. + if (!metadata.ParseFromString(*encoded_data)) { + if (!TextFormat::ParseFromString(*encoded_data, &metadata)) { + // The metadata is invalid. + std::cerr + << filename_ + << ".pb.meta: Could not parse metadata as wire or text format." + << std::endl; + return; + } + // Generators that use the public plugin interface emit text-format + // metadata (because in the public plugin protocol, file content must be + // UTF8-encoded strings). + is_text_format = true; + } + } else { + // Create a new file to store the new metadata in info_to_insert_. + encoded_data = + &directory_->files_.insert({filename_ + ".pb.meta", ""}).first->second; + } + GeneratedCodeInfo new_metadata; + bool crossed_offset = false; + size_t to_add = 0; + for (const auto& source_annotation : metadata.annotation()) { + // The first time an annotation at or after the insertion point is found, + // insert the new metadata from info_to_insert_. Shift all annotations + // after the new metadata by the length of the text that was inserted + // (including any additional indent length). + if (source_annotation.begin() >= insertion_offset && !crossed_offset) { + crossed_offset = true; + InsertShiftedInfo(insertion_content, insertion_offset, indent_length, + new_metadata); + to_add += insertion_length; + } + GeneratedCodeInfo::Annotation* annotation = new_metadata.add_annotation(); + *annotation = source_annotation; + annotation->set_begin(annotation->begin() + to_add); + annotation->set_end(annotation->end() + to_add); + } + // If there were never any annotations at or after the insertion point, + // make sure to still insert the new metadata from info_to_insert_. + if (!crossed_offset) { + InsertShiftedInfo(insertion_content, insertion_offset, indent_length, + new_metadata); + } + if (is_text_format) { + TextFormat::PrintToString(new_metadata, encoded_data); + } else { + new_metadata.SerializeToString(encoded_data); + } +} + +CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() { + // Make sure all data has been written. + inner_.reset(); + + // Insert into the directory. + auto pair = directory_->files_.insert({filename_, ""}); + auto it = pair.first; + bool already_present = !pair.second; + + if (insertion_point_.empty()) { + // This was just a regular Open(). + if (already_present) { + if (append_mode_) { + it->second.append(data_); + } else { + std::cerr << filename_ << ": Tried to write the same file twice." + << std::endl; + directory_->had_error_ = true; + } + return; + } + + it->second.swap(data_); + } else { + // This was an OpenForInsert(). + + // If the data doesn't end with a clean line break, add one. + if (!data_.empty() && data_[data_.size() - 1] != '\n') { + data_.push_back('\n'); + } + + // Find the file we are going to insert into. + if (!already_present) { + std::cerr << filename_ + << ": Tried to insert into file that doesn't exist." + << std::endl; + directory_->had_error_ = true; + return; + } + std::string* target = &it->second; + + // Find the insertion point. + std::string magic_string = + strings::Substitute("@@protoc_insertion_point($0)", insertion_point_); + std::string::size_type pos = target->find(magic_string); + + if (pos == std::string::npos) { + std::cerr << filename_ << ": insertion point \"" << insertion_point_ + << "\" not found." << std::endl; + directory_->had_error_ = true; + return; + } + + if ((pos > 3) && (target->substr(pos - 3, 2) == "/*")) { + // Support for inline "/* @@protoc_insertion_point() */" + pos = pos - 3; + } else { + // Seek backwards to the beginning of the line, which is where we will + // insert the data. Note that this has the effect of pushing the + // insertion point down, so the data is inserted before it. This is + // intentional because it means that multiple insertions at the same point + // will end up in the expected order in the final output. + pos = target->find_last_of('\n', pos); + if (pos == std::string::npos) { + // Insertion point is on the first line. + pos = 0; + } else { + // Advance to character after '\n'. + ++pos; + } + } + + // Extract indent. + std::string indent_(*target, pos, + target->find_first_not_of(" \t", pos) - pos); + + if (indent_.empty()) { + // No indent. This makes things easier. + target->insert(pos, data_); + UpdateMetadata(data_, pos, data_.size(), 0); + } else { + // Calculate how much space we need. + int indent_size = 0; + for (int i = 0; i < data_.size(); i++) { + if (data_[i] == '\n') indent_size += indent_.size(); + } + + // Make a hole for it. + target->insert(pos, data_.size() + indent_size, '\0'); + + // Now copy in the data. + std::string::size_type data_pos = 0; + char* target_ptr = ::google::protobuf::string_as_array(target) + pos; + while (data_pos < data_.size()) { + // Copy indent. + memcpy(target_ptr, indent_.data(), indent_.size()); + target_ptr += indent_.size(); + + // Copy line from data_. + // We already guaranteed that data_ ends with a newline (above), so this + // search can't fail. + std::string::size_type line_length = + data_.find_first_of('\n', data_pos) + 1 - data_pos; + memcpy(target_ptr, data_.data() + data_pos, line_length); + target_ptr += line_length; + data_pos += line_length; + } + UpdateMetadata(data_, pos, data_.size() + indent_size, indent_.size()); + + GOOGLE_CHECK_EQ(target_ptr, + ::google::protobuf::string_as_array(target) + pos + data_.size() + indent_size); + } + } +} + +// =================================================================== + +#if defined(_WIN32) && !defined(__CYGWIN__) +const char* const CommandLineInterface::kPathSeparator = ";"; +#else +const char* const CommandLineInterface::kPathSeparator = ":"; +#endif + +CommandLineInterface::CommandLineInterface() + : direct_dependencies_violation_msg_( + kDefaultDirectDependenciesViolationMsg) {} + +CommandLineInterface::~CommandLineInterface() {} + +void CommandLineInterface::RegisterGenerator(const std::string& flag_name, + CodeGenerator* generator, + const std::string& help_text) { + GeneratorInfo info; + info.flag_name = flag_name; + info.generator = generator; + info.help_text = help_text; + generators_by_flag_name_[flag_name] = info; +} + +void CommandLineInterface::RegisterGenerator( + const std::string& flag_name, const std::string& option_flag_name, + CodeGenerator* generator, const std::string& help_text) { + GeneratorInfo info; + info.flag_name = flag_name; + info.option_flag_name = option_flag_name; + info.generator = generator; + info.help_text = help_text; + generators_by_flag_name_[flag_name] = info; + generators_by_option_name_[option_flag_name] = info; +} + +void CommandLineInterface::AllowPlugins(const std::string& exe_name_prefix) { + plugin_prefix_ = exe_name_prefix; +} + +namespace { + +bool ContainsProto3Optional(const Descriptor* desc) { + for (int i = 0; i < desc->field_count(); i++) { + if (desc->field(i)->has_optional_keyword()) { + return true; + } + } + for (int i = 0; i < desc->nested_type_count(); i++) { + if (ContainsProto3Optional(desc->nested_type(i))) { + return true; + } + } + return false; +} + +bool ContainsProto3Optional(const FileDescriptor* file) { + if (file->syntax() == FileDescriptor::SYNTAX_PROTO3) { + for (int i = 0; i < file->message_type_count(); i++) { + if (ContainsProto3Optional(file->message_type(i))) { + return true; + } + } + } + return false; +} + +} // namespace + +namespace { +std::unique_ptr +PopulateSingleSimpleDescriptorDatabase(const std::string& descriptor_set_name); +} + +int CommandLineInterface::Run(int argc, const char* const argv[]) { + Clear(); + switch (ParseArguments(argc, argv)) { + case PARSE_ARGUMENT_DONE_AND_EXIT: + return 0; + case PARSE_ARGUMENT_FAIL: + return 1; + case PARSE_ARGUMENT_DONE_AND_CONTINUE: + break; + } + + std::vector parsed_files; + std::unique_ptr disk_source_tree; + std::unique_ptr error_collector; + std::unique_ptr descriptor_pool; + + // The SimpleDescriptorDatabases here are the constituents of the + // MergedDescriptorDatabase descriptor_set_in_database, so this vector is for + // managing their lifetimes. Its scope should match descriptor_set_in_database + std::vector> + databases_per_descriptor_set; + std::unique_ptr descriptor_set_in_database; + + std::unique_ptr source_tree_database; + + // Any --descriptor_set_in FileDescriptorSet objects will be used as a + // fallback to input_files on command line, so create that db first. + if (!descriptor_set_in_names_.empty()) { + for (const std::string& name : descriptor_set_in_names_) { + std::unique_ptr database_for_descriptor_set = + PopulateSingleSimpleDescriptorDatabase(name); + if (!database_for_descriptor_set) { + return EXIT_FAILURE; + } + databases_per_descriptor_set.push_back( + std::move(database_for_descriptor_set)); + } + + std::vector raw_databases_per_descriptor_set; + raw_databases_per_descriptor_set.reserve( + databases_per_descriptor_set.size()); + for (const std::unique_ptr& db : + databases_per_descriptor_set) { + raw_databases_per_descriptor_set.push_back(db.get()); + } + descriptor_set_in_database.reset( + new MergedDescriptorDatabase(raw_databases_per_descriptor_set)); + } + + if (proto_path_.empty()) { + // If there are no --proto_path flags, then just look in the specified + // --descriptor_set_in files. But first, verify that the input files are + // there. + if (!VerifyInputFilesInDescriptors(descriptor_set_in_database.get())) { + return 1; + } + + error_collector.reset(new ErrorPrinter(error_format_)); + descriptor_pool.reset(new DescriptorPool(descriptor_set_in_database.get(), + error_collector.get())); + } else { + disk_source_tree.reset(new DiskSourceTree()); + if (!InitializeDiskSourceTree(disk_source_tree.get(), + descriptor_set_in_database.get())) { + return 1; + } + + error_collector.reset( + new ErrorPrinter(error_format_, disk_source_tree.get())); + + source_tree_database.reset(new SourceTreeDescriptorDatabase( + disk_source_tree.get(), descriptor_set_in_database.get())); + source_tree_database->RecordErrorsTo(error_collector.get()); + + descriptor_pool.reset(new DescriptorPool( + source_tree_database.get(), + source_tree_database->GetValidationErrorCollector())); + } + + descriptor_pool->EnforceWeakDependencies(true); + if (!ParseInputFiles(descriptor_pool.get(), disk_source_tree.get(), + &parsed_files)) { + return 1; + } + + + // We construct a separate GeneratorContext for each output location. Note + // that two code generators may output to the same location, in which case + // they should share a single GeneratorContext so that OpenForInsert() works. + GeneratorContextMap output_directories; + + // Generate output. + if (mode_ == MODE_COMPILE) { + for (int i = 0; i < output_directives_.size(); i++) { + std::string output_location = output_directives_[i].output_location; + if (!HasSuffixString(output_location, ".zip") && + !HasSuffixString(output_location, ".jar") && + !HasSuffixString(output_location, ".srcjar")) { + AddTrailingSlash(&output_location); + } + + auto& generator = output_directories[output_location]; + + if (!generator) { + // First time we've seen this output location. + generator.reset(new GeneratorContextImpl(parsed_files)); + } + + if (!GenerateOutput(parsed_files, output_directives_[i], + generator.get())) { + return 1; + } + } + } + + // Write all output to disk. + for (const auto& pair : output_directories) { + const std::string& location = pair.first; + GeneratorContextImpl* directory = pair.second.get(); + if (HasSuffixString(location, "/")) { + if (!directory->WriteAllToDisk(location)) { + return 1; + } + } else { + if (HasSuffixString(location, ".jar")) { + directory->AddJarManifest(); + } + + if (!directory->WriteAllToZip(location)) { + return 1; + } + } + } + + if (!dependency_out_name_.empty()) { + GOOGLE_DCHECK(disk_source_tree.get()); + if (!GenerateDependencyManifestFile(parsed_files, output_directories, + disk_source_tree.get())) { + return 1; + } + } + + if (!descriptor_set_out_name_.empty()) { + if (!WriteDescriptorSet(parsed_files)) { + return 1; + } + } + + if (mode_ == MODE_ENCODE || mode_ == MODE_DECODE) { + if (codec_type_.empty()) { + // HACK: Define an EmptyMessage type to use for decoding. + DescriptorPool pool; + FileDescriptorProto file; + file.set_name("empty_message.proto"); + file.add_message_type()->set_name("EmptyMessage"); + GOOGLE_CHECK(pool.BuildFile(file) != NULL); + codec_type_ = "EmptyMessage"; + if (!EncodeOrDecode(&pool)) { + return 1; + } + } else { + if (!EncodeOrDecode(descriptor_pool.get())) { + return 1; + } + } + } + + if (error_collector->FoundErrors() || + (fatal_warnings_ && error_collector->FoundWarnings())) { + return 1; + } + + if (mode_ == MODE_PRINT) { + switch (print_mode_) { + case PRINT_FREE_FIELDS: + for (int i = 0; i < parsed_files.size(); ++i) { + const FileDescriptor* fd = parsed_files[i]; + for (int j = 0; j < fd->message_type_count(); ++j) { + PrintFreeFieldNumbers(fd->message_type(j)); + } + } + break; + case PRINT_NONE: + GOOGLE_LOG(ERROR) << "If the code reaches here, it usually means a bug of " + "flag parsing in the CommandLineInterface."; + return 1; + + // Do not add a default case. + } + } + + return 0; +} + +bool CommandLineInterface::InitializeDiskSourceTree( + DiskSourceTree* source_tree, DescriptorDatabase* fallback_database) { + AddDefaultProtoPaths(&proto_path_); + + // Set up the source tree. + for (int i = 0; i < proto_path_.size(); i++) { + source_tree->MapPath(proto_path_[i].first, proto_path_[i].second); + } + + // Map input files to virtual paths if possible. + if (!MakeInputsBeProtoPathRelative(source_tree, fallback_database)) { + return false; + } + + return true; +} + +namespace { +std::unique_ptr +PopulateSingleSimpleDescriptorDatabase(const std::string& descriptor_set_name) { + int fd; + do { + fd = open(descriptor_set_name.c_str(), O_RDONLY | O_BINARY); + } while (fd < 0 && errno == EINTR); + if (fd < 0) { + std::cerr << descriptor_set_name << ": " << strerror(ENOENT) << std::endl; + return nullptr; + } + + FileDescriptorSet file_descriptor_set; + bool parsed = file_descriptor_set.ParseFromFileDescriptor(fd); + if (close(fd) != 0) { + std::cerr << descriptor_set_name << ": close: " << strerror(errno) + << std::endl; + return nullptr; + } + + if (!parsed) { + std::cerr << descriptor_set_name << ": Unable to parse." << std::endl; + return nullptr; + } + + std::unique_ptr database{ + new SimpleDescriptorDatabase()}; + + for (int j = 0; j < file_descriptor_set.file_size(); j++) { + FileDescriptorProto previously_added_file_descriptor_proto; + if (database->FindFileByName(file_descriptor_set.file(j).name(), + &previously_added_file_descriptor_proto)) { + // already present - skip + continue; + } + if (!database->Add(file_descriptor_set.file(j))) { + return nullptr; + } + } + return database; +} + +} // namespace + + +bool CommandLineInterface::VerifyInputFilesInDescriptors( + DescriptorDatabase* database) { + for (const auto& input_file : input_files_) { + FileDescriptorProto file_descriptor; + if (!database->FindFileByName(input_file, &file_descriptor)) { + std::cerr << "Could not find file in descriptor database: " << input_file + << ": " << strerror(ENOENT) << std::endl; + return false; + } + + // Enforce --disallow_services. + if (disallow_services_ && file_descriptor.service_size() > 0) { + std::cerr << file_descriptor.name() + << ": This file contains services, but " + "--disallow_services was used." + << std::endl; + return false; + } + + } + return true; +} + +bool CommandLineInterface::ParseInputFiles( + DescriptorPool* descriptor_pool, DiskSourceTree* source_tree, + std::vector* parsed_files) { + + if (!proto_path_.empty()) { + // Track unused imports in all source files that were loaded from the + // filesystem. We do not track unused imports for files loaded from + // descriptor sets as they may be programmatically generated in which case + // exerting this level of rigor is less desirable. We're also making the + // assumption that the initial parse of the proto from the filesystem + // was rigorous in checking unused imports and that the descriptor set + // being parsed was produced then and that it was subsequent mutations + // of that descriptor set that left unused imports. + // + // Note that relying on proto_path exclusively is limited in that we may + // be loading descriptors from both the filesystem and descriptor sets + // depending on the invocation. At least for invocations that are + // exclusively reading from descriptor sets, we can eliminate this failure + // condition. + for (const auto& input_file : input_files_) { + descriptor_pool->AddUnusedImportTrackFile(input_file); + } + } + + bool result = true; + // Parse each file. + for (const auto& input_file : input_files_) { + // Import the file. + const FileDescriptor* parsed_file = + descriptor_pool->FindFileByName(input_file); + if (parsed_file == NULL) { + result = false; + break; + } + parsed_files->push_back(parsed_file); + + // Enforce --disallow_services. + if (disallow_services_ && parsed_file->service_count() > 0) { + std::cerr << parsed_file->name() + << ": This file contains services, but " + "--disallow_services was used." + << std::endl; + result = false; + break; + } + + + // Enforce --direct_dependencies + if (direct_dependencies_explicitly_set_) { + bool indirect_imports = false; + for (int i = 0; i < parsed_file->dependency_count(); i++) { + if (direct_dependencies_.find(parsed_file->dependency(i)->name()) == + direct_dependencies_.end()) { + indirect_imports = true; + std::cerr << parsed_file->name() << ": " + << StringReplace(direct_dependencies_violation_msg_, "%s", + parsed_file->dependency(i)->name(), + true /* replace_all */) + << std::endl; + } + } + if (indirect_imports) { + result = false; + break; + } + } + } + descriptor_pool->ClearUnusedImportTrackFiles(); + return result; +} + +void CommandLineInterface::Clear() { + // Clear all members that are set by Run(). Note that we must not clear + // members which are set by other methods before Run() is called. + executable_name_.clear(); + proto_path_.clear(); + input_files_.clear(); + direct_dependencies_.clear(); + direct_dependencies_violation_msg_ = kDefaultDirectDependenciesViolationMsg; + output_directives_.clear(); + codec_type_.clear(); + descriptor_set_in_names_.clear(); + descriptor_set_out_name_.clear(); + dependency_out_name_.clear(); + + + mode_ = MODE_COMPILE; + print_mode_ = PRINT_NONE; + imports_in_descriptor_set_ = false; + source_info_in_descriptor_set_ = false; + disallow_services_ = false; + direct_dependencies_explicitly_set_ = false; + deterministic_output_ = false; +} + +bool CommandLineInterface::MakeProtoProtoPathRelative( + DiskSourceTree* source_tree, std::string* proto, + DescriptorDatabase* fallback_database) { + // If it's in the fallback db, don't report non-existent file errors. + FileDescriptorProto fallback_file; + bool in_fallback_database = + fallback_database != nullptr && + fallback_database->FindFileByName(*proto, &fallback_file); + + // If the input file path is not a physical file path, it must be a virtual + // path. + if (access(proto->c_str(), F_OK) < 0) { + std::string disk_file; + if (source_tree->VirtualFileToDiskFile(*proto, &disk_file) || + in_fallback_database) { + return true; + } else { + std::cerr << "Could not make proto path relative: " << *proto << ": " + << strerror(ENOENT) << std::endl; + return false; + } + } + + std::string virtual_file, shadowing_disk_file; + switch (source_tree->DiskFileToVirtualFile(*proto, &virtual_file, + &shadowing_disk_file)) { + case DiskSourceTree::SUCCESS: + *proto = virtual_file; + break; + case DiskSourceTree::SHADOWED: + std::cerr << *proto << ": Input is shadowed in the --proto_path by \"" + << shadowing_disk_file + << "\". Either use the latter file as your input or reorder " + "the --proto_path so that the former file's location " + "comes first." + << std::endl; + return false; + case DiskSourceTree::CANNOT_OPEN: { + if (in_fallback_database) { + return true; + } + std::string error_str = source_tree->GetLastErrorMessage().empty() + ? strerror(errno) + : source_tree->GetLastErrorMessage(); + std::cerr << "Could not map to virtual file: " << *proto << ": " + << error_str << std::endl; + return false; + } + case DiskSourceTree::NO_MAPPING: { + // Try to interpret the path as a virtual path. + std::string disk_file; + if (source_tree->VirtualFileToDiskFile(*proto, &disk_file) || + in_fallback_database) { + return true; + } else { + // The input file path can't be mapped to any --proto_path and it also + // can't be interpreted as a virtual path. + std::cerr + << *proto + << ": File does not reside within any path " + "specified using --proto_path (or -I). You must specify a " + "--proto_path which encompasses this file. Note that the " + "proto_path must be an exact prefix of the .proto file " + "names -- protoc is too dumb to figure out when two paths " + "(e.g. absolute and relative) are equivalent (it's harder " + "than you think)." + << std::endl; + return false; + } + } + } + return true; +} + +bool CommandLineInterface::MakeInputsBeProtoPathRelative( + DiskSourceTree* source_tree, DescriptorDatabase* fallback_database) { + for (auto& input_file : input_files_) { + if (!MakeProtoProtoPathRelative(source_tree, &input_file, + fallback_database)) { + return false; + } + } + + return true; +} + + +bool CommandLineInterface::ExpandArgumentFile( + const std::string& file, std::vector* arguments) { + // The argument file is searched in the working directory only. We don't + // use the proto import path here. + std::ifstream file_stream(file.c_str()); + if (!file_stream.is_open()) { + return false; + } + std::string argument; + // We don't support any kind of shell expansion right now. + while (std::getline(file_stream, argument)) { + arguments->push_back(argument); + } + return true; +} + +CommandLineInterface::ParseArgumentStatus CommandLineInterface::ParseArguments( + int argc, const char* const argv[]) { + executable_name_ = argv[0]; + + std::vector arguments; + for (int i = 1; i < argc; ++i) { + if (argv[i][0] == '@') { + if (!ExpandArgumentFile(argv[i] + 1, &arguments)) { + std::cerr << "Failed to open argument file: " << (argv[i] + 1) + << std::endl; + return PARSE_ARGUMENT_FAIL; + } + continue; + } + arguments.push_back(argv[i]); + } + + // if no arguments are given, show help + if (arguments.empty()) { + PrintHelpText(); + return PARSE_ARGUMENT_DONE_AND_EXIT; // Exit without running compiler. + } + + // Iterate through all arguments and parse them. + for (int i = 0; i < arguments.size(); ++i) { + std::string name, value; + + if (ParseArgument(arguments[i].c_str(), &name, &value)) { + // Returned true => Use the next argument as the flag value. + if (i + 1 == arguments.size() || arguments[i + 1][0] == '-') { + std::cerr << "Missing value for flag: " << name << std::endl; + if (name == "--decode") { + std::cerr << "To decode an unknown message, use --decode_raw." + << std::endl; + } + return PARSE_ARGUMENT_FAIL; + } else { + ++i; + value = arguments[i]; + } + } + + ParseArgumentStatus status = InterpretArgument(name, value); + if (status != PARSE_ARGUMENT_DONE_AND_CONTINUE) return status; + } + + // Make sure each plugin option has a matching plugin output. + bool foundUnknownPluginOption = false; + for (std::map::const_iterator i = + plugin_parameters_.begin(); + i != plugin_parameters_.end(); ++i) { + if (plugins_.find(i->first) != plugins_.end()) { + continue; + } + bool foundImplicitPlugin = false; + for (std::vector::const_iterator j = + output_directives_.begin(); + j != output_directives_.end(); ++j) { + if (j->generator == NULL) { + std::string plugin_name = PluginName(plugin_prefix_, j->name); + if (plugin_name == i->first) { + foundImplicitPlugin = true; + break; + } + } + } + if (!foundImplicitPlugin) { + std::cerr << "Unknown flag: " + // strip prefix + "gen-" and add back "_opt" + << "--" + i->first.substr(plugin_prefix_.size() + 4) + "_opt" + << std::endl; + foundUnknownPluginOption = true; + } + } + if (foundUnknownPluginOption) { + return PARSE_ARGUMENT_FAIL; + } + + // The --proto_path & --descriptor_set_in flags both specify places to look + // for proto files. If neither were given, use the current working directory. + if (proto_path_.empty() && descriptor_set_in_names_.empty()) { + // Don't use make_pair as the old/default standard library on Solaris + // doesn't support it without explicit template parameters, which are + // incompatible with C++0x's make_pair. + proto_path_.push_back(std::pair("", ".")); + } + + // Check error cases that span multiple flag values. + bool missing_proto_definitions = false; + switch (mode_) { + case MODE_COMPILE: + missing_proto_definitions = input_files_.empty(); + break; + case MODE_DECODE: + // Handle --decode_raw separately, since it requires that no proto + // definitions are specified. + if (codec_type_.empty()) { + if (!input_files_.empty() || !descriptor_set_in_names_.empty()) { + std::cerr + << "When using --decode_raw, no input files should be given." + << std::endl; + return PARSE_ARGUMENT_FAIL; + } + missing_proto_definitions = false; + break; // only for --decode_raw + } + // --decode (not raw) is handled the same way as the rest of the modes. + PROTOBUF_FALLTHROUGH_INTENDED; + case MODE_ENCODE: + case MODE_PRINT: + missing_proto_definitions = + input_files_.empty() && descriptor_set_in_names_.empty(); + break; + default: + GOOGLE_LOG(FATAL) << "Unexpected mode: " << mode_; + } + if (missing_proto_definitions) { + std::cerr << "Missing input file." << std::endl; + return PARSE_ARGUMENT_FAIL; + } + if (mode_ == MODE_COMPILE && output_directives_.empty() && + descriptor_set_out_name_.empty()) { + std::cerr << "Missing output directives." << std::endl; + return PARSE_ARGUMENT_FAIL; + } + if (mode_ != MODE_COMPILE && !dependency_out_name_.empty()) { + std::cerr << "Can only use --dependency_out=FILE when generating code." + << std::endl; + return PARSE_ARGUMENT_FAIL; + } + if (mode_ != MODE_ENCODE && deterministic_output_) { + std::cerr << "Can only use --deterministic_output with --encode." + << std::endl; + return PARSE_ARGUMENT_FAIL; + } + if (!dependency_out_name_.empty() && input_files_.size() > 1) { + std::cerr + << "Can only process one input file when using --dependency_out=FILE." + << std::endl; + return PARSE_ARGUMENT_FAIL; + } + if (imports_in_descriptor_set_ && descriptor_set_out_name_.empty()) { + std::cerr << "--include_imports only makes sense when combined with " + "--descriptor_set_out." + << std::endl; + } + if (source_info_in_descriptor_set_ && descriptor_set_out_name_.empty()) { + std::cerr << "--include_source_info only makes sense when combined with " + "--descriptor_set_out." + << std::endl; + } + + return PARSE_ARGUMENT_DONE_AND_CONTINUE; +} + +bool CommandLineInterface::ParseArgument(const char* arg, std::string* name, + std::string* value) { + bool parsed_value = false; + + if (arg[0] != '-') { + // Not a flag. + name->clear(); + parsed_value = true; + *value = arg; + } else if (arg[1] == '-') { + // Two dashes: Multi-character name, with '=' separating name and + // value. + const char* equals_pos = strchr(arg, '='); + if (equals_pos != NULL) { + *name = std::string(arg, equals_pos - arg); + *value = equals_pos + 1; + parsed_value = true; + } else { + *name = arg; + } + } else { + // One dash: One-character name, all subsequent characters are the + // value. + if (arg[1] == '\0') { + // arg is just "-". We treat this as an input file, except that at + // present this will just lead to a "file not found" error. + name->clear(); + *value = arg; + parsed_value = true; + } else { + *name = std::string(arg, 2); + *value = arg + 2; + parsed_value = !value->empty(); + } + } + + // Need to return true iff the next arg should be used as the value for this + // one, false otherwise. + + if (parsed_value) { + // We already parsed a value for this flag. + return false; + } + + if (*name == "-h" || *name == "--help" || *name == "--disallow_services" || + *name == "--include_imports" || *name == "--include_source_info" || + *name == "--version" || *name == "--decode_raw" || + *name == "--print_free_field_numbers" || + *name == "--experimental_allow_proto3_optional" || + *name == "--deterministic_output" || *name == "--fatal_warnings") { + // HACK: These are the only flags that don't take a value. + // They probably should not be hard-coded like this but for now it's + // not worth doing better. + return false; + } + + // Next argument is the flag value. + return true; +} + +CommandLineInterface::ParseArgumentStatus +CommandLineInterface::InterpretArgument(const std::string& name, + const std::string& value) { + if (name.empty()) { + // Not a flag. Just a filename. + if (value.empty()) { + std::cerr + << "You seem to have passed an empty string as one of the " + "arguments to " + << executable_name_ + << ". This is actually " + "sort of hard to do. Congrats. Unfortunately it is not valid " + "input so the program is going to die now." + << std::endl; + return PARSE_ARGUMENT_FAIL; + } + +#if defined(_WIN32) + // On Windows, the shell (typically cmd.exe) does not expand wildcards in + // file names (e.g. foo\*.proto), so we do it ourselves. + switch (google::protobuf::io::win32::ExpandWildcards( + value, + [this](const std::string& path) { + this->input_files_.push_back(path); + })) { + case google::protobuf::io::win32::ExpandWildcardsResult::kSuccess: + break; + case google::protobuf::io::win32::ExpandWildcardsResult:: + kErrorNoMatchingFile: + // Path does not exist, is not a file, or it's longer than MAX_PATH and + // long path handling is disabled. + std::cerr << "Invalid file name pattern or missing input file \"" + << value << "\"" << std::endl; + return PARSE_ARGUMENT_FAIL; + default: + std::cerr << "Cannot convert path \"" << value + << "\" to or from Windows style" << std::endl; + return PARSE_ARGUMENT_FAIL; + } +#else // not _WIN32 + // On other platforms than Windows (e.g. Linux, Mac OS) the shell (typically + // Bash) expands wildcards. + input_files_.push_back(value); +#endif // _WIN32 + + } else if (name == "-I" || name == "--proto_path") { + // Java's -classpath (and some other languages) delimits path components + // with colons. Let's accept that syntax too just to make things more + // intuitive. + std::vector parts = Split( + value, CommandLineInterface::kPathSeparator, + true); + + for (int i = 0; i < parts.size(); i++) { + std::string virtual_path; + std::string disk_path; + + std::string::size_type equals_pos = parts[i].find_first_of('='); + if (equals_pos == std::string::npos) { + virtual_path = ""; + disk_path = parts[i]; + } else { + virtual_path = parts[i].substr(0, equals_pos); + disk_path = parts[i].substr(equals_pos + 1); + } + + if (disk_path.empty()) { + std::cerr + << "--proto_path passed empty directory name. (Use \".\" for " + "current directory.)" + << std::endl; + return PARSE_ARGUMENT_FAIL; + } + + // Make sure disk path exists, warn otherwise. + if (access(disk_path.c_str(), F_OK) < 0) { + // 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; + } else { + virtual_path = ""; + disk_path = parts[i]; + } + } + + // Don't use make_pair as the old/default standard library on Solaris + // doesn't support it without explicit template parameters, which are + // incompatible with C++0x's make_pair. + proto_path_.push_back( + std::pair(virtual_path, disk_path)); + } + + } else if (name == "--direct_dependencies") { + if (direct_dependencies_explicitly_set_) { + std::cerr << name + << " may only be passed once. To specify multiple " + "direct dependencies, pass them all as a single " + "parameter separated by ':'." + << std::endl; + return PARSE_ARGUMENT_FAIL; + } + + direct_dependencies_explicitly_set_ = true; + std::vector direct = + Split(value, ":", true); + GOOGLE_DCHECK(direct_dependencies_.empty()); + direct_dependencies_.insert(direct.begin(), direct.end()); + + } else if (name == "--direct_dependencies_violation_msg") { + direct_dependencies_violation_msg_ = value; + + } else if (name == "--descriptor_set_in") { + if (!descriptor_set_in_names_.empty()) { + std::cerr << name + << " may only be passed once. To specify multiple " + "descriptor sets, pass them all as a single " + "parameter separated by '" + << CommandLineInterface::kPathSeparator << "'." << std::endl; + return PARSE_ARGUMENT_FAIL; + } + if (value.empty()) { + std::cerr << name << " requires a non-empty value." << std::endl; + return PARSE_ARGUMENT_FAIL; + } + if (!dependency_out_name_.empty()) { + std::cerr << name << " cannot be used with --dependency_out." + << std::endl; + return PARSE_ARGUMENT_FAIL; + } + + descriptor_set_in_names_ = Split( + value, CommandLineInterface::kPathSeparator, + true); + + } else if (name == "-o" || name == "--descriptor_set_out") { + if (!descriptor_set_out_name_.empty()) { + std::cerr << name << " may only be passed once." << std::endl; + return PARSE_ARGUMENT_FAIL; + } + if (value.empty()) { + std::cerr << name << " requires a non-empty value." << std::endl; + return PARSE_ARGUMENT_FAIL; + } + if (mode_ != MODE_COMPILE) { + std::cerr + << "Cannot use --encode or --decode and generate descriptors at the " + "same time." + << std::endl; + return PARSE_ARGUMENT_FAIL; + } + descriptor_set_out_name_ = value; + + } else if (name == "--dependency_out") { + if (!dependency_out_name_.empty()) { + std::cerr << name << " may only be passed once." << std::endl; + return PARSE_ARGUMENT_FAIL; + } + if (value.empty()) { + std::cerr << name << " requires a non-empty value." << std::endl; + return PARSE_ARGUMENT_FAIL; + } + if (!descriptor_set_in_names_.empty()) { + std::cerr << name << " cannot be used with --descriptor_set_in." + << std::endl; + return PARSE_ARGUMENT_FAIL; + } + dependency_out_name_ = value; + + } else if (name == "--include_imports") { + if (imports_in_descriptor_set_) { + std::cerr << name << " may only be passed once." << std::endl; + return PARSE_ARGUMENT_FAIL; + } + imports_in_descriptor_set_ = true; + + } else if (name == "--include_source_info") { + if (source_info_in_descriptor_set_) { + std::cerr << name << " may only be passed once." << std::endl; + return PARSE_ARGUMENT_FAIL; + } + source_info_in_descriptor_set_ = true; + + } else if (name == "-h" || name == "--help") { + PrintHelpText(); + return PARSE_ARGUMENT_DONE_AND_EXIT; // Exit without running compiler. + + } else if (name == "--version") { + if (!version_info_.empty()) { + std::cout << version_info_ << std::endl; + } + std::cout << "libprotoc " << internal::VersionString(PROTOBUF_VERSION) + << PROTOBUF_VERSION_SUFFIX << std::endl; + return PARSE_ARGUMENT_DONE_AND_EXIT; // Exit without running compiler. + + } else if (name == "--disallow_services") { + disallow_services_ = true; + + + } else if (name == "--experimental_allow_proto3_optional") { + // Flag is no longer observed, but we allow it for backward compat. + } else if (name == "--encode" || name == "--decode" || + name == "--decode_raw") { + if (mode_ != MODE_COMPILE) { + std::cerr << "Only one of --encode and --decode can be specified." + << std::endl; + return PARSE_ARGUMENT_FAIL; + } + if (!output_directives_.empty() || !descriptor_set_out_name_.empty()) { + std::cerr << "Cannot use " << name + << " and generate code or descriptors at the same time." + << std::endl; + return PARSE_ARGUMENT_FAIL; + } + + mode_ = (name == "--encode") ? MODE_ENCODE : MODE_DECODE; + + if (value.empty() && name != "--decode_raw") { + std::cerr << "Type name for " << name << " cannot be blank." << std::endl; + if (name == "--decode") { + std::cerr << "To decode an unknown message, use --decode_raw." + << std::endl; + } + return PARSE_ARGUMENT_FAIL; + } else if (!value.empty() && name == "--decode_raw") { + std::cerr << "--decode_raw does not take a parameter." << std::endl; + return PARSE_ARGUMENT_FAIL; + } + + codec_type_ = value; + + } else if (name == "--deterministic_output") { + deterministic_output_ = true; + + } else if (name == "--error_format") { + if (value == "gcc") { + error_format_ = ERROR_FORMAT_GCC; + } else if (value == "msvs") { + error_format_ = ERROR_FORMAT_MSVS; + } else { + std::cerr << "Unknown error format: " << value << std::endl; + return PARSE_ARGUMENT_FAIL; + } + + } else if (name == "--fatal_warnings") { + if (fatal_warnings_) { + std::cerr << name << " may only be passed once." << std::endl; + return PARSE_ARGUMENT_FAIL; + } + fatal_warnings_ = true; + } else if (name == "--plugin") { + if (plugin_prefix_.empty()) { + std::cerr << "This compiler does not support plugins." << std::endl; + return PARSE_ARGUMENT_FAIL; + } + + std::string plugin_name; + std::string path; + + std::string::size_type equals_pos = value.find_first_of('='); + if (equals_pos == std::string::npos) { + // Use the basename of the file. + std::string::size_type slash_pos = value.find_last_of('/'); + if (slash_pos == std::string::npos) { + plugin_name = value; + } else { + plugin_name = value.substr(slash_pos + 1); + } + path = value; + } else { + plugin_name = value.substr(0, equals_pos); + path = value.substr(equals_pos + 1); + } + + plugins_[plugin_name] = path; + + } else if (name == "--print_free_field_numbers") { + if (mode_ != MODE_COMPILE) { + std::cerr << "Cannot use " << name + << " and use --encode, --decode or print " + << "other info at the same time." << std::endl; + return PARSE_ARGUMENT_FAIL; + } + if (!output_directives_.empty() || !descriptor_set_out_name_.empty()) { + std::cerr << "Cannot use " << name + << " and generate code or descriptors at the same time." + << std::endl; + return PARSE_ARGUMENT_FAIL; + } + mode_ = MODE_PRINT; + print_mode_ = PRINT_FREE_FIELDS; + } else { + // Some other flag. Look it up in the generators list. + const GeneratorInfo* generator_info = + FindOrNull(generators_by_flag_name_, name); + if (generator_info == NULL && + (plugin_prefix_.empty() || !HasSuffixString(name, "_out"))) { + // Check if it's a generator option flag. + generator_info = FindOrNull(generators_by_option_name_, name); + if (generator_info != NULL) { + std::string* parameters = + &generator_parameters_[generator_info->flag_name]; + if (!parameters->empty()) { + parameters->append(","); + } + parameters->append(value); + } else if (HasPrefixString(name, "--") && HasSuffixString(name, "_opt")) { + std::string* parameters = + &plugin_parameters_[PluginName(plugin_prefix_, name)]; + if (!parameters->empty()) { + parameters->append(","); + } + parameters->append(value); + } else { + std::cerr << "Unknown flag: " << name << std::endl; + return PARSE_ARGUMENT_FAIL; + } + } else { + // It's an output flag. Add it to the output directives. + if (mode_ != MODE_COMPILE) { + std::cerr << "Cannot use --encode, --decode or print .proto info and " + "generate code at the same time." + << std::endl; + return PARSE_ARGUMENT_FAIL; + } + + OutputDirective directive; + directive.name = name; + if (generator_info == NULL) { + directive.generator = NULL; + } else { + directive.generator = generator_info->generator; + } + + // Split value at ':' to separate the generator parameter from the + // filename. However, avoid doing this if the colon is part of a valid + // Windows-style absolute path. + std::string::size_type colon_pos = value.find_first_of(':'); + if (colon_pos == std::string::npos || IsWindowsAbsolutePath(value)) { + directive.output_location = value; + } else { + directive.parameter = value.substr(0, colon_pos); + directive.output_location = value.substr(colon_pos + 1); + } + + output_directives_.push_back(directive); + } + } + + return PARSE_ARGUMENT_DONE_AND_CONTINUE; +} + +void CommandLineInterface::PrintHelpText() { + // Sorry for indentation here; line wrapping would be uglier. + std::cout << "Usage: " << executable_name_ << " [OPTION] PROTO_FILES"; + std::cout << R"( +Parse PROTO_FILES and generate output based on the options given: + -IPATH, --proto_path=PATH Specify the directory in which to search for + imports. May be specified multiple times; + directories will be searched in order. If not + given, the current working directory is used. + If not found in any of the these directories, + the --descriptor_set_in descriptors will be + checked for required proto file. + --version Show version info and exit. + -h, --help Show this text and exit. + --encode=MESSAGE_TYPE Read a text-format message of the given type + from standard input and write it in binary + to standard output. The message type must + be defined in PROTO_FILES or their imports. + --deterministic_output When using --encode, ensure map fields are + deterministically ordered. Note that this order + is not canonical, and changes across builds or + releases of protoc. + --decode=MESSAGE_TYPE Read a binary message of the given type from + standard input and write it in text format + to standard output. The message type must + be defined in PROTO_FILES or their imports. + --decode_raw Read an arbitrary protocol message from + standard input and write the raw tag/value + pairs in text format to standard output. No + PROTO_FILES should be given when using this + flag. + --descriptor_set_in=FILES Specifies a delimited list of FILES + each containing a FileDescriptorSet (a + protocol buffer defined in descriptor.proto). + The FileDescriptor for each of the PROTO_FILES + provided will be loaded from these + FileDescriptorSets. If a FileDescriptor + appears multiple times, the first occurrence + will be used. + -oFILE, Writes a FileDescriptorSet (a protocol buffer, + --descriptor_set_out=FILE defined in descriptor.proto) containing all of + the input files to FILE. + --include_imports When using --descriptor_set_out, also include + all dependencies of the input files in the + set, so that the set is self-contained. + --include_source_info When using --descriptor_set_out, do not strip + SourceCodeInfo from the FileDescriptorProto. + This results in vastly larger descriptors that + include information about the original + location of each decl in the source file as + well as surrounding comments. + --dependency_out=FILE Write a dependency output file in the format + expected by make. This writes the transitive + set of input file paths to FILE + --error_format=FORMAT Set the format in which to print errors. + FORMAT may be 'gcc' (the default) or 'msvs' + (Microsoft Visual Studio format). + --fatal_warnings Make warnings be fatal (similar to -Werr in + gcc). This flag will make protoc return + with a non-zero exit code if any warnings + are generated. + --print_free_field_numbers Print the free field numbers of the messages + defined in the given proto files. Groups share + the same field number space with the parent + message. Extension ranges are counted as + occupied fields numbers.)"; + if (!plugin_prefix_.empty()) { + std::cout << R"( + --plugin=EXECUTABLE Specifies a plugin executable to use. + Normally, protoc searches the PATH for + plugins, but you may specify additional + executables not in the path using this flag. + Additionally, EXECUTABLE may be of the form + NAME=PATH, in which case the given plugin name + is mapped to the given executable even if + the executable's own name differs.)"; + } + + for (GeneratorMap::iterator iter = generators_by_flag_name_.begin(); + iter != generators_by_flag_name_.end(); ++iter) { + // FIXME(kenton): If the text is long enough it will wrap, which is ugly, + // but fixing this nicely (e.g. splitting on spaces) is probably more + // trouble than it's worth. + std::cout << std::endl + << " " << iter->first << "=OUT_DIR " + << std::string(19 - iter->first.size(), + ' ') // Spaces for alignment. + << iter->second.help_text; + } + std::cout << R"( + @ Read options and filenames from file. If a + relative file path is specified, the file + will be searched in the working directory. + The --proto_path option will not affect how + this argument file is searched. Content of + the file will be expanded in the position of + @ as in the argument list. Note + that shell expansion is not applied to the + content of the file (i.e., you cannot use + quotes, wildcards, escapes, commands, etc.). + Each line corresponds to a single argument, + even if it contains spaces.)"; + std::cout << std::endl; +} + +bool CommandLineInterface::EnforceProto3OptionalSupport( + const std::string& codegen_name, uint64_t supported_features, + const std::vector& parsed_files) const { + bool supports_proto3_optional = + supported_features & CodeGenerator::FEATURE_PROTO3_OPTIONAL; + if (!supports_proto3_optional) { + for (const auto fd : parsed_files) { + if (ContainsProto3Optional(fd)) { + std::cerr << fd->name() + << ": is a proto3 file that contains optional fields, but " + "code generator " + << codegen_name + << " hasn't been updated to support optional fields in " + "proto3. Please ask the owner of this code generator to " + "support proto3 optional."; + return false; + } + } + } + return true; +} + +bool CommandLineInterface::GenerateOutput( + const std::vector& parsed_files, + const OutputDirective& output_directive, + GeneratorContext* generator_context) { + // Call the generator. + std::string error; + if (output_directive.generator == NULL) { + // This is a plugin. + GOOGLE_CHECK(HasPrefixString(output_directive.name, "--") && + HasSuffixString(output_directive.name, "_out")) + << "Bad name for plugin generator: " << output_directive.name; + + std::string plugin_name = PluginName(plugin_prefix_, output_directive.name); + std::string parameters = output_directive.parameter; + if (!plugin_parameters_[plugin_name].empty()) { + if (!parameters.empty()) { + parameters.append(","); + } + parameters.append(plugin_parameters_[plugin_name]); + } + if (!GeneratePluginOutput(parsed_files, plugin_name, parameters, + generator_context, &error)) { + std::cerr << output_directive.name << ": " << error << std::endl; + return false; + } + } else { + // Regular generator. + std::string parameters = output_directive.parameter; + if (!generator_parameters_[output_directive.name].empty()) { + if (!parameters.empty()) { + parameters.append(","); + } + parameters.append(generator_parameters_[output_directive.name]); + } + if (!EnforceProto3OptionalSupport( + output_directive.name, + output_directive.generator->GetSupportedFeatures(), parsed_files)) { + return false; + } + + if (!output_directive.generator->GenerateAll(parsed_files, parameters, + generator_context, &error)) { + // Generator returned an error. + std::cerr << output_directive.name << ": " << error << std::endl; + return false; + } + } + + return true; +} + +bool CommandLineInterface::GenerateDependencyManifestFile( + const std::vector& parsed_files, + const GeneratorContextMap& output_directories, + DiskSourceTree* source_tree) { + FileDescriptorSet file_set; + + std::set already_seen; + for (int i = 0; i < parsed_files.size(); i++) { + GetTransitiveDependencies(parsed_files[i], false, false, &already_seen, + file_set.mutable_file()); + } + + std::vector output_filenames; + for (const auto& pair : output_directories) { + const std::string& location = pair.first; + GeneratorContextImpl* directory = pair.second.get(); + std::vector relative_output_filenames; + directory->GetOutputFilenames(&relative_output_filenames); + for (int i = 0; i < relative_output_filenames.size(); i++) { + std::string output_filename = location + relative_output_filenames[i]; + if (output_filename.compare(0, 2, "./") == 0) { + output_filename = output_filename.substr(2); + } + output_filenames.push_back(output_filename); + } + } + + int fd; + do { + fd = open(dependency_out_name_.c_str(), + O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666); + } while (fd < 0 && errno == EINTR); + + if (fd < 0) { + perror(dependency_out_name_.c_str()); + return false; + } + + io::FileOutputStream out(fd); + io::Printer printer(&out, '$'); + + for (int i = 0; i < output_filenames.size(); i++) { + printer.Print(output_filenames[i].c_str()); + if (i == output_filenames.size() - 1) { + printer.Print(":"); + } else { + printer.Print(" \\\n"); + } + } + + for (int i = 0; i < file_set.file_size(); i++) { + const FileDescriptorProto& file = file_set.file(i); + const std::string& virtual_file = file.name(); + std::string disk_file; + if (source_tree && + source_tree->VirtualFileToDiskFile(virtual_file, &disk_file)) { + printer.Print(" $disk_file$", "disk_file", disk_file); + if (i < file_set.file_size() - 1) printer.Print("\\\n"); + } else { + std::cerr << "Unable to identify path for file " << virtual_file + << std::endl; + return false; + } + } + + return true; +} + +bool CommandLineInterface::GeneratePluginOutput( + const std::vector& parsed_files, + const std::string& plugin_name, const std::string& parameter, + GeneratorContext* generator_context, std::string* error) { + CodeGeneratorRequest request; + CodeGeneratorResponse response; + std::string processed_parameter = parameter; + + + // Build the request. + if (!processed_parameter.empty()) { + request.set_parameter(processed_parameter); + } + + + std::set already_seen; + for (int i = 0; i < parsed_files.size(); i++) { + request.add_file_to_generate(parsed_files[i]->name()); + GetTransitiveDependencies(parsed_files[i], + true, // Include json_name for plugins. + true, // Include source code info. + &already_seen, request.mutable_proto_file()); + } + + google::protobuf::compiler::Version* version = + request.mutable_compiler_version(); + version->set_major(PROTOBUF_VERSION / 1000000); + version->set_minor(PROTOBUF_VERSION / 1000 % 1000); + version->set_patch(PROTOBUF_VERSION % 1000); + version->set_suffix(PROTOBUF_VERSION_SUFFIX); + + // Invoke the plugin. + Subprocess subprocess; + + if (plugins_.count(plugin_name) > 0) { + subprocess.Start(plugins_[plugin_name], Subprocess::EXACT_NAME); + } else { + subprocess.Start(plugin_name, Subprocess::SEARCH_PATH); + } + + std::string communicate_error; + if (!subprocess.Communicate(request, &response, &communicate_error)) { + *error = strings::Substitute("$0: $1", plugin_name, communicate_error); + return false; + } + + // Write the files. We do this even if there was a generator error in order + // to match the behavior of a compiled-in generator. + 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()) { + std::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->OpenForInsertWithGeneratedCodeInfo( + filename, output_file.insertion_point(), + output_file.generated_code_info())); + } 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 + // before the new one is opened. + current_output.reset(); + current_output.reset(generator_context->Open(output_file.name())); + } else if (current_output == NULL) { + *error = strings::Substitute( + "$0: First file chunk returned by plugin did not specify a file " + "name.", + plugin_name); + return false; + } + + // Use CodedOutputStream for convenience; otherwise we'd need to provide + // our own buffer-copying loop. + io::CodedOutputStream writer(current_output.get()); + writer.WriteString(output_file.content()); + } + + // Check for errors. + if (!response.error().empty()) { + // Generator returned an error. + *error = response.error(); + return false; + } else if (!EnforceProto3OptionalSupport( + plugin_name, response.supported_features(), parsed_files)) { + return false; + } + + return true; +} + +bool CommandLineInterface::EncodeOrDecode(const DescriptorPool* pool) { + // Look up the type. + const Descriptor* type = pool->FindMessageTypeByName(codec_type_); + if (type == NULL) { + std::cerr << "Type not defined: " << codec_type_ << std::endl; + return false; + } + + DynamicMessageFactory dynamic_factory(pool); + std::unique_ptr message(dynamic_factory.GetPrototype(type)->New()); + + if (mode_ == MODE_ENCODE) { + SetFdToTextMode(STDIN_FILENO); + SetFdToBinaryMode(STDOUT_FILENO); + } else { + SetFdToBinaryMode(STDIN_FILENO); + SetFdToTextMode(STDOUT_FILENO); + } + + io::FileInputStream in(STDIN_FILENO); + io::FileOutputStream out(STDOUT_FILENO); + + if (mode_ == MODE_ENCODE) { + // Input is text. + ErrorPrinter error_collector(error_format_); + TextFormat::Parser parser; + parser.RecordErrorsTo(&error_collector); + parser.AllowPartialMessage(true); + + if (!parser.Parse(&in, message.get())) { + std::cerr << "Failed to parse input." << std::endl; + return false; + } + } else { + // Input is binary. + if (!message->ParsePartialFromZeroCopyStream(&in)) { + std::cerr << "Failed to parse input." << std::endl; + return false; + } + } + + if (!message->IsInitialized()) { + std::cerr << "warning: Input message is missing required fields: " + << message->InitializationErrorString() << std::endl; + } + + if (mode_ == MODE_ENCODE) { + // Output is binary. + io::CodedOutputStream coded_out(&out); + coded_out.SetSerializationDeterministic(deterministic_output_); + if (!message->SerializePartialToCodedStream(&coded_out)) { + std::cerr << "output: I/O error." << std::endl; + return false; + } + } else { + // Output is text. + if (!TextFormat::Print(*message, &out)) { + std::cerr << "output: I/O error." << std::endl; + return false; + } + } + + return true; +} + +bool CommandLineInterface::WriteDescriptorSet( + const std::vector& parsed_files) { + FileDescriptorSet file_set; + + std::set already_seen; + if (!imports_in_descriptor_set_) { + // Since we don't want to output transitive dependencies, but we do want + // things to be in dependency order, add all dependencies that aren't in + // parsed_files to already_seen. This will short circuit the recursion + // in GetTransitiveDependencies. + std::set to_output; + to_output.insert(parsed_files.begin(), parsed_files.end()); + for (int i = 0; i < parsed_files.size(); i++) { + const FileDescriptor* file = parsed_files[i]; + for (int j = 0; j < file->dependency_count(); j++) { + const FileDescriptor* dependency = file->dependency(j); + // if the dependency isn't in parsed files, mark it as already seen + if (to_output.find(dependency) == to_output.end()) { + already_seen.insert(dependency); + } + } + } + } + for (int i = 0; i < parsed_files.size(); i++) { + GetTransitiveDependencies(parsed_files[i], + true, // Include json_name + source_info_in_descriptor_set_, &already_seen, + file_set.mutable_file()); + } + + int fd; + do { + fd = open(descriptor_set_out_name_.c_str(), + O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666); + } while (fd < 0 && errno == EINTR); + + if (fd < 0) { + perror(descriptor_set_out_name_.c_str()); + return false; + } + + io::FileOutputStream out(fd); + + { + io::CodedOutputStream coded_out(&out); + // Determinism is useful here because build outputs are sometimes checked + // into version control. + coded_out.SetSerializationDeterministic(true); + if (!file_set.SerializeToCodedStream(&coded_out)) { + std::cerr << descriptor_set_out_name_ << ": " << strerror(out.GetErrno()) + << std::endl; + out.Close(); + return false; + } + } + + if (!out.Close()) { + std::cerr << descriptor_set_out_name_ << ": " << strerror(out.GetErrno()) + << std::endl; + return false; + } + + return true; +} + +void CommandLineInterface::GetTransitiveDependencies( + const FileDescriptor* file, bool include_json_name, + bool include_source_code_info, + std::set* already_seen, + RepeatedPtrField* output) { + if (!already_seen->insert(file).second) { + // Already saw this file. Skip. + return; + } + + // Add all dependencies. + for (int i = 0; i < file->dependency_count(); i++) { + GetTransitiveDependencies(file->dependency(i), include_json_name, + include_source_code_info, already_seen, output); + } + + // Add this file. + FileDescriptorProto* new_descriptor = output->Add(); + file->CopyTo(new_descriptor); + if (include_json_name) { + file->CopyJsonNameTo(new_descriptor); + } + if (include_source_code_info) { + file->CopySourceCodeInfoTo(new_descriptor); + } +} + +namespace { + +// Utility function for PrintFreeFieldNumbers. +// Stores occupied ranges into the ranges parameter, and next level of sub +// message types into the nested_messages parameter. The FieldRange is left +// inclusive, right exclusive. i.e. [a, b). +// +// Nested Messages: +// Note that it only stores the nested message type, iff the nested type is +// either a direct child of the given descriptor, or the nested type is a +// descendant of the given descriptor and all the nodes between the +// nested type and the given descriptor are group types. e.g. +// +// message Foo { +// message Bar { +// message NestedBar {} +// } +// group Baz = 1 { +// group NestedBazGroup = 2 { +// message Quz { +// message NestedQuz {} +// } +// } +// message NestedBaz {} +// } +// } +// +// In this case, Bar, Quz and NestedBaz will be added into the nested types. +// Since free field numbers of group types will not be printed, this makes sure +// the nested message types in groups will not be dropped. The nested_messages +// parameter will contain the direct children (when groups are ignored in the +// tree) of the given descriptor for the caller to traverse. The declaration +// order of the nested messages is also preserved. +typedef std::pair FieldRange; +void GatherOccupiedFieldRanges( + const Descriptor* descriptor, std::set* ranges, + std::vector* nested_messages) { + std::set groups; + for (int i = 0; i < descriptor->field_count(); ++i) { + const FieldDescriptor* fd = descriptor->field(i); + ranges->insert(FieldRange(fd->number(), fd->number() + 1)); + if (fd->type() == FieldDescriptor::TYPE_GROUP) { + groups.insert(fd->message_type()); + } + } + for (int i = 0; i < descriptor->extension_range_count(); ++i) { + ranges->insert(FieldRange(descriptor->extension_range(i)->start, + descriptor->extension_range(i)->end)); + } + for (int i = 0; i < descriptor->reserved_range_count(); ++i) { + ranges->insert(FieldRange(descriptor->reserved_range(i)->start, + descriptor->reserved_range(i)->end)); + } + // Handle the nested messages/groups in declaration order to make it + // post-order strict. + for (int i = 0; i < descriptor->nested_type_count(); ++i) { + const Descriptor* nested_desc = descriptor->nested_type(i); + if (groups.find(nested_desc) != groups.end()) { + GatherOccupiedFieldRanges(nested_desc, ranges, nested_messages); + } else { + nested_messages->push_back(nested_desc); + } + } +} + +// Utility function for PrintFreeFieldNumbers. +// Actually prints the formatted free field numbers for given message name and +// occupied ranges. +void FormatFreeFieldNumbers(const std::string& name, + const std::set& ranges) { + std::string output; + StringAppendF(&output, "%-35s free:", name.c_str()); + int next_free_number = 1; + for (std::set::const_iterator i = ranges.begin(); + i != ranges.end(); ++i) { + // This happens when groups re-use parent field numbers, in which + // case we skip the FieldRange entirely. + if (next_free_number >= i->second) continue; + + if (next_free_number < i->first) { + if (next_free_number + 1 == i->first) { + // Singleton + StringAppendF(&output, " %d", next_free_number); + } else { + // Range + StringAppendF(&output, " %d-%d", next_free_number, i->first - 1); + } + } + next_free_number = i->second; + } + if (next_free_number <= FieldDescriptor::kMaxNumber) { + StringAppendF(&output, " %d-INF", next_free_number); + } + std::cout << output << std::endl; +} + +} // namespace + +void CommandLineInterface::PrintFreeFieldNumbers(const Descriptor* descriptor) { + std::set ranges; + std::vector nested_messages; + GatherOccupiedFieldRanges(descriptor, &ranges, &nested_messages); + + for (int i = 0; i < nested_messages.size(); ++i) { + PrintFreeFieldNumbers(nested_messages[i]); + } + FormatFreeFieldNumbers(descriptor->full_name(), ranges); +} + + +} // namespace compiler +} // namespace protobuf +} // namespace google diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_message.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_message.cc new file mode 100644 index 0000000..1385046 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_message.cc @@ -0,0 +1,4584 @@ +// 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. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +// Must be included last. +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace cpp { + +using internal::WireFormat; +using internal::WireFormatLite; + +namespace { + +static constexpr int kNoHasbit = -1; + +// Create an expression that evaluates to +// "for all i, (_has_bits_[i] & masks[i]) == masks[i]" +// masks is allowed to be shorter than _has_bits_, but at least one element of +// masks must be non-zero. +std::string ConditionalToCheckBitmasks( + const std::vector& masks, bool return_success = true, + StringPiece has_bits_var = "_has_bits_") { + std::vector parts; + for (int i = 0; i < masks.size(); i++) { + if (masks[i] == 0) continue; + std::string m = StrCat("0x", strings::Hex(masks[i], strings::ZERO_PAD_8)); + // Each xor evaluates to 0 if the expected bits are present. + parts.push_back( + StrCat("((", has_bits_var, "[", i, "] & ", m, ") ^ ", m, ")")); + } + GOOGLE_CHECK(!parts.empty()); + // If we have multiple parts, each expected to be 0, then bitwise-or them. + std::string result = + parts.size() == 1 + ? parts[0] + : StrCat("(", Join(parts, "\n | "), ")"); + return result + (return_success ? " == 0" : " != 0"); +} + +void PrintPresenceCheck(const Formatter& format, const FieldDescriptor* field, + const std::vector& has_bit_indices, + io::Printer* printer, int* cached_has_word_index) { + if (!field->options().weak()) { + int has_bit_index = has_bit_indices[field->index()]; + if (*cached_has_word_index != (has_bit_index / 32)) { + *cached_has_word_index = (has_bit_index / 32); + format("cached_has_bits = _has_bits_[$1$];\n", *cached_has_word_index); + } + const std::string mask = + StrCat(strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8)); + format("if (cached_has_bits & 0x$1$u) {\n", mask); + } else { + format("if (has_$1$()) {\n", FieldName(field)); + } + format.Indent(); +} + +struct FieldOrderingByNumber { + inline bool operator()(const FieldDescriptor* a, + const FieldDescriptor* b) const { + return a->number() < b->number(); + } +}; + +// Sort the fields of the given Descriptor by number into a new[]'d array +// and return it. +std::vector SortFieldsByNumber( + const Descriptor* descriptor) { + std::vector fields(descriptor->field_count()); + for (int i = 0; i < descriptor->field_count(); i++) { + fields[i] = descriptor->field(i); + } + std::sort(fields.begin(), fields.end(), FieldOrderingByNumber()); + return fields; +} + +// Functor for sorting extension ranges by their "start" field number. +struct ExtensionRangeSorter { + bool operator()(const Descriptor::ExtensionRange* left, + const Descriptor::ExtensionRange* right) const { + return left->start < right->start; + } +}; + +bool IsPOD(const FieldDescriptor* field) { + if (field->is_repeated() || field->is_extension()) return false; + switch (field->cpp_type()) { + case FieldDescriptor::CPPTYPE_ENUM: + case FieldDescriptor::CPPTYPE_INT32: + case FieldDescriptor::CPPTYPE_INT64: + case FieldDescriptor::CPPTYPE_UINT32: + case FieldDescriptor::CPPTYPE_UINT64: + case FieldDescriptor::CPPTYPE_FLOAT: + case FieldDescriptor::CPPTYPE_DOUBLE: + case FieldDescriptor::CPPTYPE_BOOL: + return true; + case FieldDescriptor::CPPTYPE_STRING: + return false; + default: + return false; + } +} + +// Helper for the code that emits the SharedCtor() and InternalSwap() methods. +// Anything that is a POD or a "normal" message (represented by a pointer) can +// be manipulated as raw bytes. +bool CanBeManipulatedAsRawBytes(const FieldDescriptor* field, + const Options& options, + MessageSCCAnalyzer* scc_analyzer) { + bool ret = CanInitializeByZeroing(field); + + // Non-repeated, non-lazy message fields are simply raw pointers, so we can + // swap them or use memset to initialize these in SharedCtor. We cannot use + // this in Clear, as we need to potentially delete the existing value. + ret = + ret || (!field->is_repeated() && !IsLazy(field, options, scc_analyzer) && + field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE); + return ret; +} + +bool StrContains(const std::string& haystack, const std::string& needle) { + return haystack.find(needle) != std::string::npos; +} + +// Finds runs of fields for which `predicate` is true. +// RunMap maps from fields that start each run to the number of fields in that +// run. This is optimized for the common case that there are very few runs in +// a message and that most of the eligible fields appear together. +using RunMap = std::unordered_map; +RunMap FindRuns(const std::vector& fields, + const std::function& predicate) { + RunMap runs; + const FieldDescriptor* last_start = nullptr; + + for (auto field : fields) { + if (predicate(field)) { + if (last_start == nullptr) { + last_start = field; + } + + runs[last_start]++; + } else { + last_start = nullptr; + } + } + return runs; +} + +// Emits an if-statement with a condition that evaluates to true if |field| is +// considered non-default (will be sent over the wire), for message types +// without true field presence. Should only be called if +// !HasHasbit(field). +bool EmitFieldNonDefaultCondition(io::Printer* printer, + const std::string& prefix, + const FieldDescriptor* field) { + GOOGLE_CHECK(!HasHasbit(field)); + Formatter format(printer); + format.Set("prefix", prefix); + format.Set("name", FieldName(field)); + // Merge and serialize semantics: primitive fields are merged/serialized only + // if non-zero (numeric) or non-empty (string). + if (!field->is_repeated() && !field->containing_oneof()) { + if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) { + format("if (!$prefix$_internal_$name$().empty()) {\n"); + } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { + // Message fields still have has_$name$() methods. + format("if ($prefix$_internal_has_$name$()) {\n"); + } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_FLOAT) { + format( + "static_assert(sizeof(uint32_t) == sizeof(float), \"Code assumes " + "uint32_t and float are the same size.\");\n" + "float tmp_$name$ = $prefix$_internal_$name$();\n" + "uint32_t raw_$name$;\n" + "memcpy(&raw_$name$, &tmp_$name$, sizeof(tmp_$name$));\n" + "if (raw_$name$ != 0) {\n"); + } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_DOUBLE) { + format( + "static_assert(sizeof(uint64_t) == sizeof(double), \"Code assumes " + "uint64_t and double are the same size.\");\n" + "double tmp_$name$ = $prefix$_internal_$name$();\n" + "uint64_t raw_$name$;\n" + "memcpy(&raw_$name$, &tmp_$name$, sizeof(tmp_$name$));\n" + "if (raw_$name$ != 0) {\n"); + } else { + format("if ($prefix$_internal_$name$() != 0) {\n"); + } + format.Indent(); + return true; + } else if (field->real_containing_oneof()) { + format("if (_internal_has_$name$()) {\n"); + format.Indent(); + return true; + } + return false; +} + +// Does the given field have a has_$name$() method? +bool HasHasMethod(const FieldDescriptor* field) { + if (!IsProto3(field->file())) { + // In proto1/proto2, every field has a has_$name$() method. + return true; + } + // For message types without true field presence, only fields with a message + // type or inside an one-of have a has_$name$() method. + return field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE || + field->has_optional_keyword() || field->real_containing_oneof(); +} + +// Collects map entry message type information. +void CollectMapInfo(const Options& options, const Descriptor* descriptor, + std::map* variables) { + GOOGLE_CHECK(IsMapEntryMessage(descriptor)); + std::map& vars = *variables; + const FieldDescriptor* key = descriptor->map_key(); + const FieldDescriptor* val = descriptor->map_value(); + vars["key_cpp"] = PrimitiveTypeName(options, key->cpp_type()); + switch (val->cpp_type()) { + case FieldDescriptor::CPPTYPE_MESSAGE: + vars["val_cpp"] = FieldMessageTypeName(val, options); + break; + case FieldDescriptor::CPPTYPE_ENUM: + vars["val_cpp"] = ClassName(val->enum_type(), true); + break; + default: + vars["val_cpp"] = PrimitiveTypeName(options, val->cpp_type()); + } + vars["key_wire_type"] = + "TYPE_" + ToUpper(DeclaredTypeMethodName(key->type())); + vars["val_wire_type"] = + "TYPE_" + ToUpper(DeclaredTypeMethodName(val->type())); +} + +// Does the given field have a private (internal helper only) has_$name$() +// method? +bool HasPrivateHasMethod(const FieldDescriptor* field) { + // Only for oneofs in message types with no field presence. has_$name$(), + // based on the oneof case, is still useful internally for generated code. + return IsProto3(field->file()) && field->real_containing_oneof(); +} + +// TODO(ckennelly): Cull these exclusions if/when these protos do not have +// their methods overridden by subclasses. + +bool ShouldMarkClassAsFinal(const Descriptor* descriptor, + const Options& options) { + return true; +} + + +// Returns true to make the message serialize in order, decided by the following +// factors in the order of precedence. +// --options().message_set_wire_format() == true +// --the message is in the allowlist (true) +// --GOOGLE_PROTOBUF_SHUFFLE_SERIALIZE is defined (false) +// --a ranage of message names that are allowed to stay in order (true) +bool ShouldSerializeInOrder(const Descriptor* descriptor, + const Options& options) { + return true; +} + +bool TableDrivenParsingEnabled(const Descriptor* descriptor, + const Options& options, + MessageSCCAnalyzer* scc_analyzer) { + if (!options.table_driven_parsing) { + return false; + } + + // Consider table-driven parsing. We only do this if: + // - We have has_bits for fields. This avoids a check on every field we set + // when are present (the common case). + bool has_hasbit = false; + for (int i = 0; i < descriptor->field_count(); i++) { + if (HasHasbit(descriptor->field(i))) { + has_hasbit = true; + break; + } + } + + if (!has_hasbit) return false; + + const double table_sparseness = 0.5; + int max_field_number = 0; + for (auto field : FieldRange(descriptor)) { + if (max_field_number < field->number()) { + max_field_number = field->number(); + } + + // - There are no weak fields. + if (IsWeak(field, options)) { + return false; + } + + // - There are no lazy fields (they require the non-lite library). + if (IsLazy(field, options, scc_analyzer)) { + return false; + } + } + + // - There range of field numbers is "small" + if (max_field_number >= (2 << 14)) { + return false; + } + + // - Field numbers are relatively dense within the actual number of fields. + // We check for strictly greater than in the case where there are no fields + // (only extensions) so max_field_number == descriptor->field_count() == 0. + if (max_field_number * table_sparseness > descriptor->field_count()) { + return false; + } + + // - This is not a MapEntryMessage. + if (IsMapEntryMessage(descriptor)) { + return false; + } + + return true; +} + +bool IsCrossFileMapField(const FieldDescriptor* field) { + if (!field->is_map()) { + return false; + } + + const Descriptor* d = field->message_type(); + const FieldDescriptor* value = d->FindFieldByNumber(2); + + return IsCrossFileMessage(value); +} + +bool IsCrossFileMaybeMap(const FieldDescriptor* field) { + if (IsCrossFileMapField(field)) { + return true; + } + + return IsCrossFileMessage(field); +} + +bool IsRequired(const std::vector& v) { + return v.front()->is_required(); +} + +bool HasSingularString(const Descriptor* desc, const Options& options) { + for (const auto* field : FieldRange(desc)) { + if (IsString(field, options) && !IsStringInlined(field, options) && + !field->is_repeated() && !field->real_containing_oneof()) { + return true; + } + } + return false; +} + +// Collects neighboring fields based on a given criteria (equivalent predicate). +template +std::vector> CollectFields( + const std::vector& fields, + const Predicate& equivalent) { + std::vector> chunks; + for (auto field : fields) { + if (chunks.empty() || !equivalent(chunks.back().back(), field)) { + chunks.emplace_back(); + } + chunks.back().push_back(field); + } + return chunks; +} + +// Returns a bit mask based on has_bit index of "fields" that are typically on +// the same chunk. It is used in a group presence check where _has_bits_ is +// masked to tell if any thing in "fields" is present. +uint32_t GenChunkMask(const std::vector& fields, + const std::vector& has_bit_indices) { + GOOGLE_CHECK(!fields.empty()); + int first_index_offset = has_bit_indices[fields.front()->index()] / 32; + uint32_t chunk_mask = 0; + for (auto field : fields) { + // "index" defines where in the _has_bits_ the field appears. + int index = has_bit_indices[field->index()]; + GOOGLE_CHECK_EQ(first_index_offset, index / 32); + chunk_mask |= static_cast(1) << (index % 32); + } + GOOGLE_CHECK_NE(0, chunk_mask); + return chunk_mask; +} + +// Return the number of bits set in n, a non-negative integer. +static int popcnt(uint32_t n) { + int result = 0; + while (n != 0) { + result += (n & 1); + n = n / 2; + } + return result; +} + +// For a run of cold chunks, opens and closes an external if statement that +// checks multiple has_bits words to skip bulk of cold fields. +class ColdChunkSkipper { + public: + ColdChunkSkipper( + const Options& options, + const std::vector>& chunks, + const std::vector& has_bit_indices, const double cold_threshold) + : chunks_(chunks), + has_bit_indices_(has_bit_indices), + access_info_map_(options.access_info_map), + cold_threshold_(cold_threshold) { + SetCommonVars(options, &variables_); + } + + // May open an external if check for a batch of cold fields. "from" is the + // prefix to _has_bits_ to allow MergeFrom to use "from._has_bits_". + // Otherwise, it should be "". + void OnStartChunk(int chunk, int cached_has_word_index, + const std::string& from, io::Printer* printer); + bool OnEndChunk(int chunk, io::Printer* printer); + + private: + bool IsColdChunk(int chunk); + + int HasbitWord(int chunk, int offset) { + return has_bit_indices_[chunks_[chunk][offset]->index()] / 32; + } + + const std::vector>& chunks_; + const std::vector& has_bit_indices_; + const AccessInfoMap* access_info_map_; + const double cold_threshold_; + std::map variables_; + int limit_chunk_ = -1; +}; + +// Tuning parameters for ColdChunkSkipper. +const double kColdRatio = 0.005; + +bool ColdChunkSkipper::IsColdChunk(int chunk) { + // Mark this variable as used until it is actually used + (void)cold_threshold_; + return false; +} + + +void ColdChunkSkipper::OnStartChunk(int chunk, int cached_has_word_index, + const std::string& from, + io::Printer* printer) { + Formatter format(printer, variables_); + if (!access_info_map_) { + return; + } else if (chunk < limit_chunk_) { + // We are already inside a run of cold chunks. + return; + } else if (!IsColdChunk(chunk)) { + // We can't start a run of cold chunks. + return; + } + + // Find the end of consecutive cold chunks. + limit_chunk_ = chunk; + while (limit_chunk_ < chunks_.size() && IsColdChunk(limit_chunk_)) { + limit_chunk_++; + } + + if (limit_chunk_ <= chunk + 1) { + // Require at least two chunks to emit external has_bit checks. + limit_chunk_ = -1; + return; + } + + // Emit has_bit check for each has_bit_dword index. + format("if (PROTOBUF_PREDICT_FALSE("); + int first_word = HasbitWord(chunk, 0); + while (chunk < limit_chunk_) { + uint32_t mask = 0; + int this_word = HasbitWord(chunk, 0); + // Generate mask for chunks on the same word. + for (; chunk < limit_chunk_ && HasbitWord(chunk, 0) == this_word; chunk++) { + for (auto field : chunks_[chunk]) { + int hasbit_index = has_bit_indices_[field->index()]; + // Fields on a chunk must be in the same word. + GOOGLE_CHECK_EQ(this_word, hasbit_index / 32); + mask |= 1 << (hasbit_index % 32); + } + } + + if (this_word != first_word) { + format(" ||\n "); + } + format.Set("mask", strings::Hex(mask, strings::ZERO_PAD_8)); + if (this_word == cached_has_word_index) { + format("(cached_has_bits & 0x$mask$u) != 0"); + } else { + format("($1$_has_bits_[$2$] & 0x$mask$u) != 0", from, this_word); + } + } + format(")) {\n"); + format.Indent(); +} + +bool ColdChunkSkipper::OnEndChunk(int chunk, io::Printer* printer) { + Formatter format(printer, variables_); + if (chunk != limit_chunk_ - 1) { + return false; + } + format.Outdent(); + format("}\n"); + return true; +} + +void MaySetAnnotationVariable(const Options& options, + StringPiece annotation_name, + StringPiece injector_template_prefix, + StringPiece injector_template_suffix, + std::map* variables) { + if (options.field_listener_options.forbidden_field_listener_events.count( + std::string(annotation_name))) + return; + (*variables)[StrCat("annotate_", annotation_name)] = strings::Substitute( + StrCat(injector_template_prefix, injector_template_suffix), + (*variables)["classtype"]); +} + +void GenerateExtensionAnnotations( + const Descriptor* descriptor, const Options& options, + std::map* variables) { + const std::map accessor_annotations_to_hooks = { + {"annotate_extension_has", "OnHasExtension"}, + {"annotate_extension_clear", "OnClearExtension"}, + {"annotate_extension_repeated_size", "OnExtensionSize"}, + {"annotate_extension_get", "OnGetExtension"}, + {"annotate_extension_mutable", "OnMutableExtension"}, + {"annotate_extension_set", "OnSetExtension"}, + {"annotate_extension_release", "OnReleaseExtension"}, + {"annotate_repeated_extension_get", "OnGetExtension"}, + {"annotate_repeated_extension_mutable", "OnMutableExtension"}, + {"annotate_repeated_extension_set", "OnSetExtension"}, + {"annotate_repeated_extension_add", "OnAddExtension"}, + {"annotate_repeated_extension_add_mutable", "OnAddMutableExtension"}, + {"annotate_repeated_extension_list", "OnListExtension"}, + {"annotate_repeated_extension_list_mutable", "OnMutableListExtension"}, + }; + for (const auto& annotation : accessor_annotations_to_hooks) { + (*variables)[annotation.first] = ""; + } + if (!options.field_listener_options.inject_field_listener_events || + descriptor->file()->options().optimize_for() == + google::protobuf::FileOptions::LITE_RUNTIME) { + return; + } + for (const auto& annotation : accessor_annotations_to_hooks) { + const std::string& annotation_name = annotation.first; + const std::string& listener_call = annotation.second; + if (!StrContains(annotation_name, "repeated") && + !StrContains(annotation_name, "size") && + !StrContains(annotation_name, "clear")) { + // Primitive fields accessors. + // "Has" is here as users calling "has" on a repeated field is a mistake. + (*variables)[annotation_name] = StrCat( + " _tracker_.", listener_call, + "(this, id.number(), _proto_TypeTraits::GetPtr(id.number(), " + "_extensions_, id.default_value_ref()));"); + } else if (StrContains(annotation_name, "repeated") && + !StrContains(annotation_name, "list") && + !StrContains(annotation_name, "size")) { + // Repeated index accessors. + std::string str_index = "index"; + if (StrContains(annotation_name, "add")) { + str_index = "_extensions_.ExtensionSize(id.number()) - 1"; + } + (*variables)[annotation_name] = + StrCat(" _tracker_.", listener_call, + "(this, id.number(), " + "_proto_TypeTraits::GetPtr(id.number(), _extensions_, ", + str_index, "));"); + } else if (StrContains(annotation_name, "list") || + StrContains(annotation_name, "size")) { + // Repeated full accessors. + (*variables)[annotation_name] = StrCat( + " _tracker_.", listener_call, + "(this, id.number(), _proto_TypeTraits::GetRepeatedPtr(id.number(), " + "_extensions_));"); + } else { + // Generic accessors such as "clear". + // TODO(b/190614678): Generalize clear from both repeated and non repeated + // calls, currently their underlying memory interfaces are very different. + // Or think of removing clear callback as no usages are needed and no + // memory exist after calling clear(). + } + } +} + +} // anonymous namespace + +// =================================================================== + +MessageGenerator::MessageGenerator( + const Descriptor* descriptor, + const std::map& vars, int index_in_file_messages, + const Options& options, MessageSCCAnalyzer* scc_analyzer) + : descriptor_(descriptor), + index_in_file_messages_(index_in_file_messages), + classname_(ClassName(descriptor, false)), + options_(options), + field_generators_(descriptor, options, scc_analyzer), + max_has_bit_index_(0), + max_inlined_string_index_(0), + num_weak_fields_(0), + scc_analyzer_(scc_analyzer), + variables_(vars) { + if (!message_layout_helper_) { + message_layout_helper_.reset(new PaddingOptimizer()); + } + + // Variables that apply to this class + variables_["classname"] = classname_; + variables_["classtype"] = QualifiedClassName(descriptor_, options); + variables_["full_name"] = descriptor_->full_name(); + variables_["superclass"] = SuperClassName(descriptor_, options_); + variables_["annotate_serialize"] = ""; + variables_["annotate_deserialize"] = ""; + variables_["annotate_reflection"] = ""; + variables_["annotate_bytesize"] = ""; + variables_["annotate_mergefrom"] = ""; + + if (options.field_listener_options.inject_field_listener_events && + descriptor->file()->options().optimize_for() != + google::protobuf::FileOptions::LITE_RUNTIME) { + const std::string injector_template = " _tracker_."; + + MaySetAnnotationVariable(options, "serialize", injector_template, + "OnSerialize(this);\n", &variables_); + MaySetAnnotationVariable(options, "deserialize", injector_template, + "OnDeserialize(this);\n", &variables_); + // TODO(danilak): Ideally annotate_reflection should not exist and we need + // to annotate all reflective calls on our own, however, as this is a cause + // for side effects, i.e. reading values dynamically, we want the users know + // that dynamic access can happen. + MaySetAnnotationVariable(options, "reflection", injector_template, + "OnGetMetadata();\n", &variables_); + MaySetAnnotationVariable(options, "bytesize", injector_template, + "OnByteSize(this);\n", &variables_); + MaySetAnnotationVariable(options, "mergefrom", injector_template, + "OnMergeFrom(this, &from);\n", &variables_); + } + + GenerateExtensionAnnotations(descriptor_, options_, &variables_); + + SetUnknownFieldsVariable(descriptor_, options_, &variables_); + + // Compute optimized field order to be used for layout and initialization + // purposes. + for (auto field : FieldRange(descriptor_)) { + if (IsFieldStripped(field, options_)) { + continue; + } + + if (IsWeak(field, options_)) { + num_weak_fields_++; + } else if (!field->real_containing_oneof()) { + optimized_order_.push_back(field); + } + } + + message_layout_helper_->OptimizeLayout(&optimized_order_, options_, + scc_analyzer_); + + // This message has hasbits iff one or more fields need one. + for (auto field : optimized_order_) { + if (HasHasbit(field)) { + if (has_bit_indices_.empty()) { + has_bit_indices_.resize(descriptor_->field_count(), kNoHasbit); + } + has_bit_indices_[field->index()] = max_has_bit_index_++; + } + if (IsStringInlined(field, options_)) { + if (inlined_string_indices_.empty()) { + inlined_string_indices_.resize(descriptor_->field_count(), kNoHasbit); + } + inlined_string_indices_[field->index()] = max_inlined_string_index_++; + } + } + + if (!has_bit_indices_.empty()) { + field_generators_.SetHasBitIndices(has_bit_indices_); + } + + if (!inlined_string_indices_.empty()) { + field_generators_.SetInlinedStringIndices(inlined_string_indices_); + } + + num_required_fields_ = 0; + for (int i = 0; i < descriptor->field_count(); i++) { + if (descriptor->field(i)->is_required()) { + ++num_required_fields_; + } + } + + table_driven_ = + TableDrivenParsingEnabled(descriptor_, options_, scc_analyzer_); + parse_function_generator_.reset(new ParseFunctionGenerator( + descriptor_, max_has_bit_index_, has_bit_indices_, + inlined_string_indices_, options_, scc_analyzer_, variables_)); +} + +MessageGenerator::~MessageGenerator() = default; + +size_t MessageGenerator::HasBitsSize() const { + return (max_has_bit_index_ + 31) / 32; +} + +size_t MessageGenerator::InlinedStringDonatedSize() const { + return (max_inlined_string_index_ + 31) / 32; +} + +int MessageGenerator::HasBitIndex(const FieldDescriptor* field) const { + return has_bit_indices_.empty() ? kNoHasbit + : has_bit_indices_[field->index()]; +} + +int MessageGenerator::HasByteIndex(const FieldDescriptor* field) const { + int hasbit = HasBitIndex(field); + return hasbit == kNoHasbit ? kNoHasbit : hasbit / 8; +} + +int MessageGenerator::HasWordIndex(const FieldDescriptor* field) const { + int hasbit = HasBitIndex(field); + return hasbit == kNoHasbit ? kNoHasbit : hasbit / 32; +} + +void MessageGenerator::AddGenerators( + std::vector>* enum_generators, + std::vector>* extension_generators) { + for (int i = 0; i < descriptor_->enum_type_count(); i++) { + enum_generators->emplace_back( + new EnumGenerator(descriptor_->enum_type(i), variables_, options_)); + enum_generators_.push_back(enum_generators->back().get()); + } + for (int i = 0; i < descriptor_->extension_count(); i++) { + extension_generators->emplace_back(new ExtensionGenerator( + descriptor_->extension(i), options_, scc_analyzer_)); + extension_generators_.push_back(extension_generators->back().get()); + } +} + +void MessageGenerator::GenerateFieldAccessorDeclarations(io::Printer* printer) { + Formatter format(printer, variables_); + // optimized_fields_ does not contain fields where + // field->real_containing_oneof() + // so we need to iterate over those as well. + // + // We place the non-oneof fields in optimized_order_, as that controls the + // order of the _has_bits_ entries and we want GDB's pretty printers to be + // able to infer these indices from the k[FIELDNAME]FieldNumber order. + std::vector ordered_fields; + ordered_fields.reserve(descriptor_->field_count()); + + ordered_fields.insert(ordered_fields.begin(), optimized_order_.begin(), + optimized_order_.end()); + for (auto field : FieldRange(descriptor_)) { + if (!field->real_containing_oneof() && !field->options().weak() && + !IsFieldStripped(field, options_)) { + continue; + } + ordered_fields.push_back(field); + } + + if (!ordered_fields.empty()) { + format("enum : int {\n"); + for (auto field : ordered_fields) { + Formatter::SaveState save(&format); + + std::map vars; + SetCommonFieldVariables(field, &vars, options_); + format.AddMap(vars); + format(" ${1$$2$$}$ = $number$,\n", field, FieldConstantName(field)); + } + format("};\n"); + } + for (auto field : ordered_fields) { + PrintFieldComment(format, field); + + Formatter::SaveState save(&format); + + std::map vars; + SetCommonFieldVariables(field, &vars, options_); + format.AddMap(vars); + + if (field->is_repeated()) { + format("$deprecated_attr$int ${1$$name$_size$}$() const$2$\n", field, + !IsFieldStripped(field, options_) ? ";" : " {__builtin_trap();}"); + if (!IsFieldStripped(field, options_)) { + format( + "private:\n" + "int ${1$_internal_$name$_size$}$() const;\n" + "public:\n", + field); + } + } else if (HasHasMethod(field)) { + format("$deprecated_attr$bool ${1$has_$name$$}$() const$2$\n", field, + !IsFieldStripped(field, options_) ? ";" : " {__builtin_trap();}"); + if (!IsFieldStripped(field, options_)) { + format( + "private:\n" + "bool _internal_has_$name$() const;\n" + "public:\n"); + } + } else if (HasPrivateHasMethod(field)) { + if (!IsFieldStripped(field, options_)) { + format( + "private:\n" + "bool ${1$_internal_has_$name$$}$() const;\n" + "public:\n", + field); + } + } + format("$deprecated_attr$void ${1$clear_$name$$}$()$2$\n", field, + !IsFieldStripped(field, options_) ? ";" : "{__builtin_trap();}"); + + // Generate type-specific accessor declarations. + field_generators_.get(field).GenerateAccessorDeclarations(printer); + + format("\n"); + } + + if (descriptor_->extension_range_count() > 0) { + // Generate accessors for extensions. + // We use "_proto_TypeTraits" as a type name below because "TypeTraits" + // causes problems if the class has a nested message or enum type with that + // name and "_TypeTraits" is technically reserved for the C++ library since + // it starts with an underscore followed by a capital letter. + // + // For similar reason, we use "_field_type" and "_is_packed" as parameter + // names below, so that "field_type" and "is_packed" can be used as field + // names. + format(R"( +template +inline bool HasExtension( + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< + $classname$, _proto_TypeTraits, _field_type, _is_packed>& id) const { +$annotate_extension_has$ + return _extensions_.Has(id.number()); +} + +template +inline void ClearExtension( + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< + $classname$, _proto_TypeTraits, _field_type, _is_packed>& id) { + _extensions_.ClearExtension(id.number()); +$annotate_extension_clear$ +} + +template +inline int ExtensionSize( + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< + $classname$, _proto_TypeTraits, _field_type, _is_packed>& id) const { +$annotate_extension_repeated_size$ + return _extensions_.ExtensionSize(id.number()); +} + +template +inline typename _proto_TypeTraits::Singular::ConstType GetExtension( + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< + $classname$, _proto_TypeTraits, _field_type, _is_packed>& id) const { +$annotate_extension_get$ + return _proto_TypeTraits::Get(id.number(), _extensions_, + id.default_value()); +} + +template +inline typename _proto_TypeTraits::Singular::MutableType MutableExtension( + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< + $classname$, _proto_TypeTraits, _field_type, _is_packed>& id) { +$annotate_extension_mutable$ + return _proto_TypeTraits::Mutable(id.number(), _field_type, + &_extensions_); +} + +template +inline void SetExtension( + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< + $classname$, _proto_TypeTraits, _field_type, _is_packed>& id, + typename _proto_TypeTraits::Singular::ConstType value) { + _proto_TypeTraits::Set(id.number(), _field_type, value, &_extensions_); +$annotate_extension_set$ +} + +template +inline void SetAllocatedExtension( + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< + $classname$, _proto_TypeTraits, _field_type, _is_packed>& id, + typename _proto_TypeTraits::Singular::MutableType value) { + _proto_TypeTraits::SetAllocated(id.number(), _field_type, value, + &_extensions_); +$annotate_extension_set$ +} +template +inline void UnsafeArenaSetAllocatedExtension( + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< + $classname$, _proto_TypeTraits, _field_type, _is_packed>& id, + typename _proto_TypeTraits::Singular::MutableType value) { + _proto_TypeTraits::UnsafeArenaSetAllocated(id.number(), _field_type, + value, &_extensions_); +$annotate_extension_set$ +} +template +PROTOBUF_NODISCARD inline + typename _proto_TypeTraits::Singular::MutableType + ReleaseExtension( + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< + $classname$, _proto_TypeTraits, _field_type, _is_packed>& id) { +$annotate_extension_release$ + return _proto_TypeTraits::Release(id.number(), _field_type, + &_extensions_); +} +template +inline typename _proto_TypeTraits::Singular::MutableType +UnsafeArenaReleaseExtension( + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< + $classname$, _proto_TypeTraits, _field_type, _is_packed>& id) { +$annotate_extension_release$ + return _proto_TypeTraits::UnsafeArenaRelease(id.number(), _field_type, + &_extensions_); +} + +template +inline typename _proto_TypeTraits::Repeated::ConstType GetExtension( + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< + $classname$, _proto_TypeTraits, _field_type, _is_packed>& id, + int index) const { +$annotate_repeated_extension_get$ + return _proto_TypeTraits::Get(id.number(), _extensions_, index); +} + +template +inline typename _proto_TypeTraits::Repeated::MutableType MutableExtension( + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< + $classname$, _proto_TypeTraits, _field_type, _is_packed>& id, + int index) { +$annotate_repeated_extension_mutable$ + return _proto_TypeTraits::Mutable(id.number(), index, &_extensions_); +} + +template +inline void SetExtension( + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< + $classname$, _proto_TypeTraits, _field_type, _is_packed>& id, + int index, typename _proto_TypeTraits::Repeated::ConstType value) { + _proto_TypeTraits::Set(id.number(), index, value, &_extensions_); +$annotate_repeated_extension_set$ +} + +template +inline typename _proto_TypeTraits::Repeated::MutableType AddExtension( + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< + $classname$, _proto_TypeTraits, _field_type, _is_packed>& id) { + typename _proto_TypeTraits::Repeated::MutableType to_add = + _proto_TypeTraits::Add(id.number(), _field_type, &_extensions_); +$annotate_repeated_extension_add_mutable$ + return to_add; +} + +template +inline void AddExtension( + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< + $classname$, _proto_TypeTraits, _field_type, _is_packed>& id, + typename _proto_TypeTraits::Repeated::ConstType value) { + _proto_TypeTraits::Add(id.number(), _field_type, _is_packed, value, + &_extensions_); +$annotate_repeated_extension_add$ +} + +template +inline const typename _proto_TypeTraits::Repeated::RepeatedFieldType& +GetRepeatedExtension( + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< + $classname$, _proto_TypeTraits, _field_type, _is_packed>& id) const { +$annotate_repeated_extension_list$ + return _proto_TypeTraits::GetRepeated(id.number(), _extensions_); +} + +template +inline typename _proto_TypeTraits::Repeated::RepeatedFieldType* +MutableRepeatedExtension( + const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< + $classname$, _proto_TypeTraits, _field_type, _is_packed>& id) { +$annotate_repeated_extension_list_mutable$ + return _proto_TypeTraits::MutableRepeated(id.number(), _field_type, + _is_packed, &_extensions_); +} + +)"); + // Generate MessageSet specific APIs for proto2 MessageSet. + // For testing purposes we don't check for bridge.MessageSet, so + // we don't use IsProto2MessageSet + if (descriptor_->options().message_set_wire_format() && + !options_.opensource_runtime && !options_.lite_implicit_weak_fields) { + // Special-case MessageSet + format("GOOGLE_PROTOBUF_EXTENSION_MESSAGE_SET_ACCESSORS($classname$)\n"); + } + } + + for (auto oneof : OneOfRange(descriptor_)) { + Formatter::SaveState saver(&format); + format.Set("oneof_name", oneof->name()); + format.Set("camel_oneof_name", UnderscoresToCamelCase(oneof->name(), true)); + format( + "void ${1$clear_$oneof_name$$}$();\n" + "$camel_oneof_name$Case $oneof_name$_case() const;\n", + oneof); + } +} + +void MessageGenerator::GenerateSingularFieldHasBits( + const FieldDescriptor* field, Formatter format) { + if (IsFieldStripped(field, options_)) { + format( + "inline bool $classname$::has_$name$() const { " + "__builtin_trap(); }\n"); + return; + } + if (field->options().weak()) { + format( + "inline bool $classname$::has_$name$() const {\n" + "$annotate_has$" + " return _weak_field_map_.Has($number$);\n" + "}\n"); + return; + } + if (HasHasbit(field)) { + int has_bit_index = HasBitIndex(field); + GOOGLE_CHECK_NE(has_bit_index, kNoHasbit); + + format.Set("has_array_index", has_bit_index / 32); + format.Set("has_mask", + strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8)); + format( + "inline bool $classname$::_internal_has_$name$() const {\n" + " bool value = " + "(_has_bits_[$has_array_index$] & 0x$has_mask$u) != 0;\n"); + + if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && + !IsLazy(field, options_, scc_analyzer_)) { + // We maintain the invariant that for a submessage x, has_x() returning + // true implies that x_ is not null. By giving this information to the + // compiler, we allow it to eliminate unnecessary null checks later on. + format(" PROTOBUF_ASSUME(!value || $name$_ != nullptr);\n"); + } + + format( + " return value;\n" + "}\n" + "inline bool $classname$::has_$name$() const {\n" + "$annotate_has$" + " return _internal_has_$name$();\n" + "}\n"); + } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { + // Message fields have a has_$name$() method. + if (IsLazy(field, options_, scc_analyzer_)) { + format( + "inline bool $classname$::_internal_has_$name$() const {\n" + " return !$name$_.IsCleared();\n" + "}\n"); + } else { + format( + "inline bool $classname$::_internal_has_$name$() const {\n" + " return this != internal_default_instance() " + "&& $name$_ != nullptr;\n" + "}\n"); + } + format( + "inline bool $classname$::has_$name$() const {\n" + "$annotate_has$" + " return _internal_has_$name$();\n" + "}\n"); + } +} + +void MessageGenerator::GenerateOneofHasBits(io::Printer* printer) { + Formatter format(printer, variables_); + for (auto oneof : OneOfRange(descriptor_)) { + format.Set("oneof_name", oneof->name()); + format.Set("oneof_index", oneof->index()); + format.Set("cap_oneof_name", ToUpper(oneof->name())); + format( + "inline bool $classname$::has_$oneof_name$() const {\n" + " return $oneof_name$_case() != $cap_oneof_name$_NOT_SET;\n" + "}\n" + "inline void $classname$::clear_has_$oneof_name$() {\n" + " _oneof_case_[$oneof_index$] = $cap_oneof_name$_NOT_SET;\n" + "}\n"); + } +} + +void MessageGenerator::GenerateOneofMemberHasBits(const FieldDescriptor* field, + const Formatter& format) { + if (IsFieldStripped(field, options_)) { + if (HasHasMethod(field)) { + format( + "inline bool $classname$::has_$name$() const { " + "__builtin_trap(); }\n"); + } + format( + "inline void $classname$::set_has_$name$() { __builtin_trap(); " + "}\n"); + return; + } + // Singular field in a oneof + // N.B.: Without field presence, we do not use has-bits or generate + // has_$name$() methods, but oneofs still have set_has_$name$(). + // Oneofs also have has_$name$() but only as a private helper + // method, so that generated code is slightly cleaner (vs. comparing + // _oneof_case_[index] against a constant everywhere). + // + // If has_$name$() is private, there is no need to add an internal accessor. + // Only annotate public accessors. + if (HasHasMethod(field)) { + format( + "inline bool $classname$::_internal_has_$name$() const {\n" + " return $oneof_name$_case() == k$field_name$;\n" + "}\n" + "inline bool $classname$::has_$name$() const {\n" + "$annotate_has$" + " return _internal_has_$name$();\n" + "}\n"); + } else if (HasPrivateHasMethod(field)) { + format( + "inline bool $classname$::_internal_has_$name$() const {\n" + " return $oneof_name$_case() == k$field_name$;\n" + "}\n"); + } + // set_has_$name$() for oneof fields is always private; hence should not be + // annotated. + format( + "inline void $classname$::set_has_$name$() {\n" + " _oneof_case_[$oneof_index$] = k$field_name$;\n" + "}\n"); +} + +void MessageGenerator::GenerateFieldClear(const FieldDescriptor* field, + bool is_inline, Formatter format) { + if (IsFieldStripped(field, options_)) { + format("void $classname$::clear_$name$() { __builtin_trap(); }\n"); + return; + } + + // Generate clear_$name$(). + if (is_inline) { + format("inline "); + } + format("void $classname$::clear_$name$() {\n"); + + format.Indent(); + + if (field->real_containing_oneof()) { + // Clear this field only if it is the active field in this oneof, + // otherwise ignore + format("if (_internal_has_$name$()) {\n"); + format.Indent(); + field_generators_.get(field).GenerateClearingCode(format.printer()); + format("clear_has_$oneof_name$();\n"); + format.Outdent(); + format("}\n"); + } else { + field_generators_.get(field).GenerateClearingCode(format.printer()); + if (HasHasbit(field)) { + int has_bit_index = HasBitIndex(field); + format.Set("has_array_index", has_bit_index / 32); + format.Set("has_mask", + strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8)); + format("_has_bits_[$has_array_index$] &= ~0x$has_mask$u;\n"); + } + } + format("$annotate_clear$"); + format.Outdent(); + format("}\n"); +} + +void MessageGenerator::GenerateFieldAccessorDefinitions(io::Printer* printer) { + Formatter format(printer, variables_); + format("// $classname$\n\n"); + + for (auto field : FieldRange(descriptor_)) { + PrintFieldComment(format, field); + + if (IsFieldStripped(field, options_)) { + continue; + } + + std::map vars; + SetCommonFieldVariables(field, &vars, options_); + + Formatter::SaveState saver(&format); + format.AddMap(vars); + + // Generate has_$name$() or $name$_size(). + if (field->is_repeated()) { + if (IsFieldStripped(field, options_)) { + format( + "inline int $classname$::$name$_size() const { " + "__builtin_trap(); }\n"); + } else { + format( + "inline int $classname$::_internal_$name$_size() const {\n" + " return $name$_$1$.size();\n" + "}\n" + "inline int $classname$::$name$_size() const {\n" + "$annotate_size$" + " return _internal_$name$_size();\n" + "}\n", + IsImplicitWeakField(field, options_, scc_analyzer_) && + field->message_type() + ? ".weak" + : ""); + } + } else if (field->real_containing_oneof()) { + format.Set("field_name", UnderscoresToCamelCase(field->name(), true)); + format.Set("oneof_name", field->containing_oneof()->name()); + format.Set("oneof_index", + StrCat(field->containing_oneof()->index())); + GenerateOneofMemberHasBits(field, format); + } else { + // Singular field. + GenerateSingularFieldHasBits(field, format); + } + + if (!IsCrossFileMaybeMap(field)) { + GenerateFieldClear(field, true, format); + } + + // Generate type-specific accessors. + if (!IsFieldStripped(field, options_)) { + field_generators_.get(field).GenerateInlineAccessorDefinitions(printer); + } + + format("\n"); + } + + // Generate has_$name$() and clear_has_$name$() functions for oneofs. + GenerateOneofHasBits(printer); +} + +void MessageGenerator::GenerateClassDefinition(io::Printer* printer) { + Formatter format(printer, variables_); + format.Set("class_final", + ShouldMarkClassAsFinal(descriptor_, options_) ? "final" : ""); + + if (IsMapEntryMessage(descriptor_)) { + std::map vars; + CollectMapInfo(options_, descriptor_, &vars); + vars["lite"] = + HasDescriptorMethods(descriptor_->file(), options_) ? "" : "Lite"; + format.AddMap(vars); + format( + "class $classname$ : public " + "::$proto_ns$::internal::MapEntry$lite$<$classname$, \n" + " $key_cpp$, $val_cpp$,\n" + " ::$proto_ns$::internal::WireFormatLite::$key_wire_type$,\n" + " ::$proto_ns$::internal::WireFormatLite::$val_wire_type$> {\n" + "public:\n" + " typedef ::$proto_ns$::internal::MapEntry$lite$<$classname$, \n" + " $key_cpp$, $val_cpp$,\n" + " ::$proto_ns$::internal::WireFormatLite::$key_wire_type$,\n" + " ::$proto_ns$::internal::WireFormatLite::$val_wire_type$> " + "SuperType;\n" + " $classname$();\n" + " explicit constexpr $classname$(\n" + " ::$proto_ns$::internal::ConstantInitialized);\n" + " explicit $classname$(::$proto_ns$::Arena* arena);\n" + " void MergeFrom(const $classname$& other);\n" + " static const $classname$* internal_default_instance() { return " + "reinterpret_cast(&_$classname$_default_instance_); }\n"); + auto utf8_check = GetUtf8CheckMode(descriptor_->field(0), options_); + if (descriptor_->field(0)->type() == FieldDescriptor::TYPE_STRING && + utf8_check != Utf8CheckMode::kNone) { + if (utf8_check == Utf8CheckMode::kStrict) { + format( + " static bool ValidateKey(std::string* s) {\n" + " return ::$proto_ns$::internal::WireFormatLite::" + "VerifyUtf8String(s->data(), static_cast(s->size()), " + "::$proto_ns$::internal::WireFormatLite::PARSE, \"$1$\");\n" + " }\n", + descriptor_->field(0)->full_name()); + } else { + GOOGLE_CHECK(utf8_check == Utf8CheckMode::kVerify); + format( + " static bool ValidateKey(std::string* s) {\n" + "#ifndef NDEBUG\n" + " ::$proto_ns$::internal::WireFormatLite::VerifyUtf8String(\n" + " s->data(), static_cast(s->size()), " + "::$proto_ns$::internal::" + "WireFormatLite::PARSE, \"$1$\");\n" + "#else\n" + " (void) s;\n" + "#endif\n" + " return true;\n" + " }\n", + descriptor_->field(0)->full_name()); + } + } else { + format(" static bool ValidateKey(void*) { return true; }\n"); + } + if (descriptor_->field(1)->type() == FieldDescriptor::TYPE_STRING && + utf8_check != Utf8CheckMode::kNone) { + if (utf8_check == Utf8CheckMode::kStrict) { + format( + " static bool ValidateValue(std::string* s) {\n" + " return ::$proto_ns$::internal::WireFormatLite::" + "VerifyUtf8String(s->data(), static_cast(s->size()), " + "::$proto_ns$::internal::WireFormatLite::PARSE, \"$1$\");\n" + " }\n", + descriptor_->field(1)->full_name()); + } else { + GOOGLE_CHECK(utf8_check == Utf8CheckMode::kVerify); + format( + " static bool ValidateValue(std::string* s) {\n" + "#ifndef NDEBUG\n" + " ::$proto_ns$::internal::WireFormatLite::VerifyUtf8String(\n" + " s->data(), static_cast(s->size()), " + "::$proto_ns$::internal::" + "WireFormatLite::PARSE, \"$1$\");\n" + "#else\n" + " (void) s;\n" + "#endif\n" + " return true;\n" + " }\n", + descriptor_->field(1)->full_name()); + } + } else { + format(" static bool ValidateValue(void*) { return true; }\n"); + } + if (HasDescriptorMethods(descriptor_->file(), options_)) { + format( + " using ::$proto_ns$::Message::MergeFrom;\n" + "" + " ::$proto_ns$::Metadata GetMetadata() const final;\n"); + } + format("};\n"); + return; + } + + format( + "class $dllexport_decl $${1$$classname$$}$$ class_final$ :\n" + " public $superclass$ /* @@protoc_insertion_point(" + "class_definition:$full_name$) */ {\n", + descriptor_); + format(" public:\n"); + format.Indent(); + + if (EnableMessageOwnedArena(descriptor_)) { + format( + "inline $classname$() : $classname$(" + "::$proto_ns$::Arena::InternalHelper<$classname$>::\n" + " CreateMessageOwnedArena(), true) {}\n"); + } else { + format("inline $classname$() : $classname$(nullptr) {}\n"); + } + if (!HasSimpleBaseClass(descriptor_, options_)) { + format("~$classname$() override;\n"); + } + format( + "explicit constexpr " + "$classname$(::$proto_ns$::internal::ConstantInitialized);\n" + "\n" + "$classname$(const $classname$& from);\n" + "$classname$($classname$&& from) noexcept\n" + " : $classname$() {\n" + " *this = ::std::move(from);\n" + "}\n" + "\n" + "inline $classname$& operator=(const $classname$& from) {\n" + " CopyFrom(from);\n" + " return *this;\n" + "}\n" + "inline $classname$& operator=($classname$&& from) noexcept {\n" + " if (this == &from) return *this;\n" + " if (GetOwningArena() == from.GetOwningArena()\n" + "#ifdef PROTOBUF_FORCE_COPY_IN_MOVE\n" + " && GetOwningArena() != nullptr\n" + "#endif // !PROTOBUF_FORCE_COPY_IN_MOVE\n" + " ) {\n" + " InternalSwap(&from);\n" + " } else {\n" + " CopyFrom(from);\n" + " }\n" + " return *this;\n" + "}\n" + "\n"); + + if (options_.table_driven_serialization) { + format( + "private:\n" + "const void* InternalGetTable() const override;\n" + "public:\n" + "\n"); + } + + if (PublicUnknownFieldsAccessors(descriptor_)) { + format( + "inline const $unknown_fields_type$& unknown_fields() const {\n" + " return $unknown_fields$;\n" + "}\n" + "inline $unknown_fields_type$* mutable_unknown_fields() {\n" + " return $mutable_unknown_fields$;\n" + "}\n" + "\n"); + } + + // Only generate this member if it's not disabled. + if (HasDescriptorMethods(descriptor_->file(), options_) && + !descriptor_->options().no_standard_descriptor_accessor()) { + format( + "static const ::$proto_ns$::Descriptor* descriptor() {\n" + " return GetDescriptor();\n" + "}\n"); + } + + if (HasDescriptorMethods(descriptor_->file(), options_)) { + // These shadow non-static methods of the same names in Message. We + // redefine them here because calls directly on the generated class can be + // statically analyzed -- we know what descriptor types are being requested. + // It also avoids a vtable dispatch. + // + // We would eventually like to eliminate the methods in Message, and having + // this separate also lets us track calls to the base class methods + // separately. + format( + "static const ::$proto_ns$::Descriptor* GetDescriptor() {\n" + " return default_instance().GetMetadata().descriptor;\n" + "}\n" + "static const ::$proto_ns$::Reflection* GetReflection() {\n" + " return default_instance().GetMetadata().reflection;\n" + "}\n"); + } + + format( + "static const $classname$& default_instance() {\n" + " return *internal_default_instance();\n" + "}\n"); + + // Generate enum values for every field in oneofs. One list is generated for + // each oneof with an additional *_NOT_SET value. + for (auto oneof : OneOfRange(descriptor_)) { + format("enum $1$Case {\n", UnderscoresToCamelCase(oneof->name(), true)); + format.Indent(); + for (auto field : FieldRange(oneof)) { + format("$1$ = $2$,\n", OneofCaseConstantName(field), // 1 + field->number()); // 2 + } + format("$1$_NOT_SET = 0,\n", ToUpper(oneof->name())); + format.Outdent(); + format( + "};\n" + "\n"); + } + + // TODO(gerbens) make this private, while still granting other protos access. + format( + "static inline const $classname$* internal_default_instance() {\n" + " return reinterpret_cast(\n" + " &_$classname$_default_instance_);\n" + "}\n" + "static constexpr int kIndexInFileMessages =\n" + " $1$;\n" + "\n", + index_in_file_messages_); + + if (IsAnyMessage(descriptor_, options_)) { + format( + "// implements Any -----------------------------------------------\n" + "\n"); + if (HasDescriptorMethods(descriptor_->file(), options_)) { + format( + "bool PackFrom(const ::$proto_ns$::Message& message) {\n" + " return _any_metadata_.PackFrom(GetArena(), message);\n" + "}\n" + "bool PackFrom(const ::$proto_ns$::Message& message,\n" + " ::PROTOBUF_NAMESPACE_ID::ConstStringParam " + "type_url_prefix) {\n" + " return _any_metadata_.PackFrom(GetArena(), message, " + "type_url_prefix);\n" + "}\n" + "bool UnpackTo(::$proto_ns$::Message* message) const {\n" + " return _any_metadata_.UnpackTo(message);\n" + "}\n" + "static bool GetAnyFieldDescriptors(\n" + " const ::$proto_ns$::Message& message,\n" + " const ::$proto_ns$::FieldDescriptor** type_url_field,\n" + " const ::$proto_ns$::FieldDescriptor** value_field);\n" + "template " + "::value>::type>\n" + "bool PackFrom(const T& message) {\n" + " return _any_metadata_.PackFrom(GetArena(), message);\n" + "}\n" + "template " + "::value>::type>\n" + "bool PackFrom(const T& message,\n" + " ::PROTOBUF_NAMESPACE_ID::ConstStringParam " + "type_url_prefix) {\n" + " return _any_metadata_.PackFrom(GetArena(), message, " + "type_url_prefix);" + "}\n" + "template " + "::value>::type>\n" + "bool UnpackTo(T* message) const {\n" + " return _any_metadata_.UnpackTo(message);\n" + "}\n"); + } else { + format( + "template \n" + "bool PackFrom(const T& message) {\n" + " return _any_metadata_.PackFrom(GetArena(), message);\n" + "}\n" + "template \n" + "bool PackFrom(const T& message,\n" + " ::PROTOBUF_NAMESPACE_ID::ConstStringParam " + "type_url_prefix) {\n" + " return _any_metadata_.PackFrom(GetArena(), message, " + "type_url_prefix);\n" + "}\n" + "template \n" + "bool UnpackTo(T* message) const {\n" + " return _any_metadata_.UnpackTo(message);\n" + "}\n"); + } + format( + "template bool Is() const {\n" + " return _any_metadata_.Is();\n" + "}\n" + "static bool ParseAnyTypeUrl(::PROTOBUF_NAMESPACE_ID::ConstStringParam " + "type_url,\n" + " std::string* full_type_name);\n"); + } + + format( + "friend void swap($classname$& a, $classname$& b) {\n" + " a.Swap(&b);\n" + "}\n" + "inline void Swap($classname$* other) {\n" + " if (other == this) return;\n" + "#ifdef PROTOBUF_FORCE_COPY_IN_SWAP\n" + " if (GetOwningArena() != nullptr &&\n" + " GetOwningArena() == other->GetOwningArena()) {\n " + "#else // PROTOBUF_FORCE_COPY_IN_SWAP\n" + " if (GetOwningArena() == other->GetOwningArena()) {\n" + "#endif // !PROTOBUF_FORCE_COPY_IN_SWAP\n" + " InternalSwap(other);\n" + " } else {\n" + " ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);\n" + " }\n" + "}\n" + "void UnsafeArenaSwap($classname$* other) {\n" + " if (other == this) return;\n" + " $DCHK$(GetOwningArena() == other->GetOwningArena());\n" + " InternalSwap(other);\n" + "}\n"); + + format( + "\n" + "// implements Message ----------------------------------------------\n" + "\n" + "$classname$* New(::$proto_ns$::Arena* arena = nullptr) const final {\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. + format.Set("full_final", HasDescriptorMethods(descriptor_->file(), options_) + ? "final" + : ""); + + if (HasGeneratedMethods(descriptor_->file(), options_)) { + if (HasDescriptorMethods(descriptor_->file(), options_)) { + if (!HasSimpleBaseClass(descriptor_, options_)) { + format( + // Use Message's built-in MergeFrom and CopyFrom when the passed-in + // argument is a generic Message instance, and only define the + // custom MergeFrom and CopyFrom instances when the source of the + // merge/copy is known to be the same class as the destination. + // TODO(jorg): Define MergeFrom in terms of MergeImpl, rather than + // the other way around, to save even more code size. + "using $superclass$::CopyFrom;\n" + "void CopyFrom(const $classname$& from);\n" + "" + "using $superclass$::MergeFrom;\n" + "void MergeFrom(const $classname$& from);\n" + "private:\n" + "static void MergeImpl(::$proto_ns$::Message* to, const " + "::$proto_ns$::Message& from);\n" + "public:\n"); + } else { + format( + "using $superclass$::CopyFrom;\n" + "inline void CopyFrom(const $classname$& from) {\n" + " $superclass$::CopyImpl(this, from);\n" + "}\n" + "" + "using $superclass$::MergeFrom;\n" + "void MergeFrom(const $classname$& from) {\n" + " $superclass$::MergeImpl(this, from);\n" + "}\n" + "public:\n"); + } + } else { + format( + "void CheckTypeAndMergeFrom(const ::$proto_ns$::MessageLite& from)" + " final;\n" + "void CopyFrom(const $classname$& from);\n" + "void MergeFrom(const $classname$& from);\n"); + } + + if (!HasSimpleBaseClass(descriptor_, options_)) { + format( + "PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;\n" + "bool IsInitialized() const final;\n" + "\n" + "size_t ByteSizeLong() const final;\n"); + + parse_function_generator_->GenerateMethodDecls(printer); + + format( + "$uint8$* _InternalSerialize(\n" + " $uint8$* target, ::$proto_ns$::io::EpsCopyOutputStream* stream) " + "const final;\n"); + } + } + + if (options_.field_listener_options.inject_field_listener_events) { + format("static constexpr int _kInternalFieldNumber = $1$;\n", + descriptor_->field_count()); + } + + if (!HasSimpleBaseClass(descriptor_, options_)) { + format( + "int GetCachedSize() const final { return _cached_size_.Get(); }" + "\n\nprivate:\n" + "void SharedCtor();\n" + "void SharedDtor();\n" + "void SetCachedSize(int size) const$ full_final$;\n" + "void InternalSwap($classname$* other);\n"); + } + + format( + // Friend AnyMetadata so that it can call this FullMessageName() method. + "\nprivate:\n" + "friend class ::$proto_ns$::internal::AnyMetadata;\n" + "static $1$ FullMessageName() {\n" + " return \"$full_name$\";\n" + "}\n", + options_.opensource_runtime ? "::PROTOBUF_NAMESPACE_ID::StringPiece" + : "::StringPiece"); + + format( + // TODO(gerbens) Make this private! Currently people are deriving from + // protos to give access to this constructor, breaking the invariants + // we rely on. + "protected:\n" + "explicit $classname$(::$proto_ns$::Arena* arena,\n" + " bool is_message_owned = false);\n" + "private:\n"); + + if (!HasSimpleBaseClass(descriptor_, options_)) { + format( + "static void ArenaDtor(void* object);\n" + "inline void RegisterArenaDtor(::$proto_ns$::Arena* arena);\n"); + } + + format( + "public:\n" + "\n"); + + if (HasDescriptorMethods(descriptor_->file(), options_)) { + if (HasGeneratedMethods(descriptor_->file(), options_)) { + format( + "static const ClassData _class_data_;\n" + "const ::$proto_ns$::Message::ClassData*" + "GetClassData() const final;\n" + "\n"); + } + format( + "::$proto_ns$::Metadata GetMetadata() const final;\n" + "\n"); + } else { + format( + "std::string GetTypeName() const final;\n" + "\n"); + } + + format( + "// nested types ----------------------------------------------------\n" + "\n"); + + // Import all nested message classes into this class's scope with typedefs. + for (int i = 0; i < descriptor_->nested_type_count(); i++) { + const Descriptor* nested_type = descriptor_->nested_type(i); + if (!IsMapEntryMessage(nested_type)) { + format.Set("nested_full_name", ClassName(nested_type, false)); + format.Set("nested_name", ResolveKeyword(nested_type->name())); + format("typedef ${1$$nested_full_name$$}$ ${1$$nested_name$$}$;\n", + nested_type); + } + } + + if (descriptor_->nested_type_count() > 0) { + format("\n"); + } + + // Import all nested enums and their values into this class's scope with + // typedefs and constants. + for (int i = 0; i < descriptor_->enum_type_count(); i++) { + enum_generators_[i]->GenerateSymbolImports(printer); + format("\n"); + } + + format( + "// accessors -------------------------------------------------------\n" + "\n"); + + // Generate accessor methods for all fields. + GenerateFieldAccessorDeclarations(printer); + + // Declare extension identifiers. + for (int i = 0; i < descriptor_->extension_count(); i++) { + extension_generators_[i]->GenerateDeclaration(printer); + } + + + format("// @@protoc_insertion_point(class_scope:$full_name$)\n"); + + // Generate private members. + format.Outdent(); + format(" private:\n"); + format.Indent(); + // TODO(seongkim): Remove hack to track field access and remove this class. + format("class _Internal;\n"); + + for (auto field : FieldRange(descriptor_)) { + // set_has_***() generated in all oneofs. + if (!field->is_repeated() && !field->options().weak() && + field->real_containing_oneof()) { + format("void set_has_$1$();\n", FieldName(field)); + } + } + format("\n"); + + // Generate oneof function declarations + for (auto oneof : OneOfRange(descriptor_)) { + format( + "inline bool has_$1$() const;\n" + "inline void clear_has_$1$();\n\n", + oneof->name()); + } + + if (HasGeneratedMethods(descriptor_->file(), options_) && + !descriptor_->options().message_set_wire_format() && + num_required_fields_ > 1) { + format( + "// helper for ByteSizeLong()\n" + "size_t RequiredFieldsByteSizeFallback() const;\n\n"); + } + + if (HasGeneratedMethods(descriptor_->file(), options_)) { + parse_function_generator_->GenerateDataDecls(printer); + } + + // Prepare decls for _cached_size_ and _has_bits_. Their position in the + // output will be determined later. + + bool need_to_emit_cached_size = true; + const std::string cached_size_decl = + "mutable ::$proto_ns$::internal::CachedSize _cached_size_;\n"; + + const size_t sizeof_has_bits = HasBitsSize(); + const std::string has_bits_decl = + sizeof_has_bits == 0 ? "" + : StrCat("::$proto_ns$::internal::HasBits<", + sizeof_has_bits, "> _has_bits_;\n"); + + // To minimize padding, data members are divided into three sections: + // (1) members assumed to align to 8 bytes + // (2) members corresponding to message fields, re-ordered to optimize + // alignment. + // (3) members assumed to align to 4 bytes. + + // Members assumed to align to 8 bytes: + + if (descriptor_->extension_range_count() > 0) { + format( + "::$proto_ns$::internal::ExtensionSet _extensions_;\n" + "\n"); + } + + if (options_.field_listener_options.inject_field_listener_events && + descriptor_->file()->options().optimize_for() != + google::protobuf::FileOptions::LITE_RUNTIME) { + format("static ::$proto_ns$::AccessListener<$1$> _tracker_;\n", + ClassName(descriptor_)); + } + + // Generate _inlined_string_donated_ for inlined string type. + // TODO(congliu): To avoid affecting the locality of `_has_bits_`, should this + // be below or above `_has_bits_`? + if (!inlined_string_indices_.empty()) { + format("::$proto_ns$::internal::HasBits<$1$> _inlined_string_donated_;\n", + InlinedStringDonatedSize()); + } + + format( + "template friend class " + "::$proto_ns$::Arena::InternalHelper;\n" + "typedef void InternalArenaConstructable_;\n" + "typedef void DestructorSkippable_;\n"); + + if (!has_bit_indices_.empty()) { + // _has_bits_ is frequently accessed, so to reduce code size and improve + // speed, it should be close to the start of the object. Placing + // _cached_size_ together with _has_bits_ improves cache locality despite + // potential alignment padding. + format(has_bits_decl.c_str()); + format(cached_size_decl.c_str()); + need_to_emit_cached_size = false; + } + + // Field members: + + // Emit some private and static members + for (auto field : optimized_order_) { + const FieldGenerator& generator = field_generators_.get(field); + generator.GenerateStaticMembers(printer); + generator.GeneratePrivateMembers(printer); + } + + // For each oneof generate a union + for (auto oneof : OneOfRange(descriptor_)) { + std::string camel_oneof_name = UnderscoresToCamelCase(oneof->name(), true); + format("union $1$Union {\n", camel_oneof_name); + format.Indent(); + format( + // explicit empty constructor is needed when union contains + // ArenaStringPtr members for string fields. + "constexpr $1$Union() : _constinit_{} {}\n" + " ::$proto_ns$::internal::ConstantInitialized _constinit_;\n", + camel_oneof_name); + for (auto field : FieldRange(oneof)) { + if (!IsFieldStripped(field, options_)) { + field_generators_.get(field).GeneratePrivateMembers(printer); + } + } + format.Outdent(); + format("} $1$_;\n", oneof->name()); + for (auto field : FieldRange(oneof)) { + if (!IsFieldStripped(field, options_)) { + field_generators_.get(field).GenerateStaticMembers(printer); + } + } + } + + // Members assumed to align to 4 bytes: + + if (need_to_emit_cached_size) { + format(cached_size_decl.c_str()); + need_to_emit_cached_size = false; + } + + // Generate _oneof_case_. + if (descriptor_->real_oneof_decl_count() > 0) { + format( + "$uint32$ _oneof_case_[$1$];\n" + "\n", + descriptor_->real_oneof_decl_count()); + } + + if (num_weak_fields_) { + format("::$proto_ns$::internal::WeakFieldMap _weak_field_map_;\n"); + } + // Generate _any_metadata_ for the Any type. + if (IsAnyMessage(descriptor_, options_)) { + format("::$proto_ns$::internal::AnyMetadata _any_metadata_;\n"); + } + + // The TableStruct struct needs access to the private parts, in order to + // construct the offsets of all members. + format("friend struct ::$tablename$;\n"); + + format.Outdent(); + format("};"); + GOOGLE_DCHECK(!need_to_emit_cached_size); +} // NOLINT(readability/fn_size) + +void MessageGenerator::GenerateInlineMethods(io::Printer* printer) { + if (IsMapEntryMessage(descriptor_)) return; + GenerateFieldAccessorDefinitions(printer); + + // Generate oneof_case() functions. + for (auto oneof : OneOfRange(descriptor_)) { + Formatter format(printer, variables_); + format.Set("camel_oneof_name", UnderscoresToCamelCase(oneof->name(), true)); + format.Set("oneof_name", oneof->name()); + format.Set("oneof_index", oneof->index()); + format( + "inline $classname$::$camel_oneof_name$Case $classname$::" + "${1$$oneof_name$_case$}$() const {\n" + " return $classname$::$camel_oneof_name$Case(" + "_oneof_case_[$oneof_index$]);\n" + "}\n", + oneof); + } +} + +bool MessageGenerator::GenerateParseTable(io::Printer* printer, size_t offset, + size_t aux_offset) { + Formatter format(printer, variables_); + + if (!table_driven_) { + format("{ nullptr, nullptr, 0, -1, -1, -1, -1, nullptr, false },\n"); + return false; + } + + int max_field_number = 0; + for (auto field : FieldRange(descriptor_)) { + if (max_field_number < field->number()) { + max_field_number = field->number(); + } + } + + format("{\n"); + format.Indent(); + + format( + "$tablename$::entries + $1$,\n" + "$tablename$::aux + $2$,\n" + "$3$,\n", + offset, aux_offset, max_field_number); + + if (has_bit_indices_.empty()) { + // If no fields have hasbits, then _has_bits_ does not exist. + format("-1,\n"); + } else { + format("PROTOBUF_FIELD_OFFSET($classtype$, _has_bits_),\n"); + } + + if (descriptor_->real_oneof_decl_count() > 0) { + format("PROTOBUF_FIELD_OFFSET($classtype$, _oneof_case_),\n"); + } else { + format("-1, // no _oneof_case_\n"); + } + + if (descriptor_->extension_range_count() > 0) { + format("PROTOBUF_FIELD_OFFSET($classtype$, _extensions_),\n"); + } else { + format("-1, // no _extensions_\n"); + } + + // TODO(ckennelly): Consolidate this with the calculation for + // AuxiliaryParseTableField. + format( + "PROTOBUF_FIELD_OFFSET($classtype$, _internal_metadata_),\n" + "&$package_ns$::_$classname$_default_instance_,\n"); + + if (UseUnknownFieldSet(descriptor_->file(), options_)) { + format("true,\n"); + } else { + format("false,\n"); + } + + format.Outdent(); + format("},\n"); + return true; +} + +void MessageGenerator::GenerateSchema(io::Printer* printer, int offset, + int has_offset) { + Formatter format(printer, variables_); + has_offset = !has_bit_indices_.empty() || IsMapEntryMessage(descriptor_) + ? offset + has_offset + : -1; + int inlined_string_indices_offset; + if (inlined_string_indices_.empty()) { + inlined_string_indices_offset = -1; + } else { + GOOGLE_DCHECK_NE(has_offset, -1); + GOOGLE_DCHECK(!IsMapEntryMessage(descriptor_)); + inlined_string_indices_offset = has_offset + has_bit_indices_.size(); + } + + format("{ $1$, $2$, $3$, sizeof($classtype$)},\n", offset, has_offset, + inlined_string_indices_offset); +} + +namespace { + +// 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_t 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) { + // string field + if (generator.IsInlined()) { + type = internal::FieldMetadata::kInlinedType; + } else if (IsCord(field, options)) { + type = internal::FieldMetadata::kCordType; + } else if (IsStringPiece(field, options)) { + type = internal::FieldMetadata::kStringPieceType; + } + } + + if (field->real_containing_oneof()) { + return internal::FieldMetadata::CalculateType( + type, internal::FieldMetadata::kOneOf); + } else if (field->is_packed()) { + return internal::FieldMetadata::CalculateType( + type, internal::FieldMetadata::kPacked); + } else if (field->is_repeated()) { + return internal::FieldMetadata::CalculateType( + type, internal::FieldMetadata::kRepeated); + } else if (HasHasbit(field) || field->real_containing_oneof() || is_a_map) { + return internal::FieldMetadata::CalculateType( + type, internal::FieldMetadata::kPresence); + } else { + return internal::FieldMetadata::CalculateType( + type, internal::FieldMetadata::kNoPresence); + } +} + +int FindMessageIndexInFile(const Descriptor* descriptor) { + std::vector flatten = + FlattenMessagesInFile(descriptor->file()); + return std::find(flatten.begin(), flatten.end(), descriptor) - + flatten.begin(); +} + +} // namespace + +int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) { + Formatter format(printer, variables_); + if (!options_.table_driven_serialization) { + return 0; + } + + std::vector sorted = SortFieldsByNumber(descriptor_); + if (IsMapEntryMessage(descriptor_)) { + for (int i = 0; i < 2; i++) { + const FieldDescriptor* field = sorted[i]; + const FieldGenerator& generator = field_generators_.get(field); + + uint32_t tag = internal::WireFormatLite::MakeTag( + field->number(), WireFormat::WireTypeForFieldType(field->type())); + + std::map vars; + vars["classtype"] = QualifiedClassName(descriptor_, options_); + vars["field_name"] = FieldName(field); + vars["tag"] = StrCat(tag); + vars["hasbit"] = StrCat(i); + vars["type"] = StrCat(CalcFieldNum(generator, field, options_)); + vars["ptr"] = "nullptr"; + if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { + GOOGLE_CHECK(!IsMapEntryMessage(field->message_type())); + vars["ptr"] = + "::" + UniqueName("TableStruct", field->message_type(), options_) + + "::serialization_table + " + + StrCat(FindMessageIndexInFile(field->message_type())); + } + Formatter::SaveState saver(&format); + format.AddMap(vars); + format( + "{PROTOBUF_FIELD_OFFSET(" + "::$proto_ns$::internal::MapEntryHelper<$classtype$::" + "SuperType>, $field_name$_), $tag$," + "PROTOBUF_FIELD_OFFSET(" + "::$proto_ns$::internal::MapEntryHelper<$classtype$::" + "SuperType>, _has_bits_) * 8 + $hasbit$, $type$, " + "$ptr$},\n"); + } + return 2; + } + format( + "{PROTOBUF_FIELD_OFFSET($classtype$, _cached_size_)," + " 0, 0, 0, nullptr},\n"); + std::vector sorted_extensions; + sorted_extensions.reserve(descriptor_->extension_range_count()); + for (int i = 0; i < descriptor_->extension_range_count(); ++i) { + sorted_extensions.push_back(descriptor_->extension_range(i)); + } + std::sort(sorted_extensions.begin(), sorted_extensions.end(), + ExtensionRangeSorter()); + for (int i = 0, extension_idx = 0; /* no range */; i++) { + for (; extension_idx < sorted_extensions.size() && + (i == sorted.size() || + sorted_extensions[extension_idx]->start < sorted[i]->number()); + extension_idx++) { + const Descriptor::ExtensionRange* range = + sorted_extensions[extension_idx]; + format( + "{PROTOBUF_FIELD_OFFSET($classtype$, _extensions_), " + "$1$, $2$, ::$proto_ns$::internal::FieldMetadata::kSpecial, " + "reinterpret_cast(::$proto_ns$::internal::ExtensionSerializer)},\n", + range->start, range->end); + } + if (i == sorted.size()) break; + const FieldDescriptor* field = sorted[i]; + + uint32_t tag = internal::WireFormatLite::MakeTag( + field->number(), WireFormat::WireTypeForFieldType(field->type())); + if (field->is_packed()) { + tag = internal::WireFormatLite::MakeTag( + field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED); + } + + std::string classfieldname = FieldName(field); + if (field->real_containing_oneof()) { + classfieldname = field->containing_oneof()->name(); + } + format.Set("field_name", classfieldname); + std::string ptr = "nullptr"; + if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { + if (IsMapEntryMessage(field->message_type())) { + format( + "{PROTOBUF_FIELD_OFFSET($classtype$, $field_name$_), $1$, $2$, " + "::$proto_ns$::internal::FieldMetadata::kSpecial, " + "reinterpret_cast(static_cast< " + "::$proto_ns$::internal::SpecialSerializer>(" + "::$proto_ns$::internal::MapFieldSerializer< " + "::$proto_ns$::internal::MapEntryToMapField<" + "$3$>::MapFieldType, " + "$tablename$::serialization_table>))},\n", + tag, FindMessageIndexInFile(field->message_type()), + QualifiedClassName(field->message_type(), options_)); + continue; + } else if (!field->message_type()->options().message_set_wire_format()) { + // message_set doesn't have the usual table and we need to + // dispatch to generated serializer, hence ptr stays zero. + ptr = + "::" + UniqueName("TableStruct", field->message_type(), options_) + + "::serialization_table + " + + StrCat(FindMessageIndexInFile(field->message_type())); + } + } + + const FieldGenerator& generator = field_generators_.get(field); + int type = CalcFieldNum(generator, field, options_); + + if (IsLazy(field, options_, scc_analyzer_)) { + type = internal::FieldMetadata::kSpecial; + ptr = "reinterpret_cast(::" + variables_["proto_ns"] + + "::internal::LazyFieldSerializer"; + if (field->real_containing_oneof()) { + ptr += "OneOf"; + } else if (!HasHasbit(field)) { + ptr += "NoPresence"; + } + ptr += ")"; + } + + if (field->options().weak()) { + // TODO(gerbens) merge weak fields into ranges + format( + "{PROTOBUF_FIELD_OFFSET(" + "$classtype$, _weak_field_map_), $1$, $1$, " + "::$proto_ns$::internal::FieldMetadata::kSpecial, " + "reinterpret_cast(::$proto_ns$::internal::WeakFieldSerializer)},\n", + tag); + } else if (field->real_containing_oneof()) { + format.Set("oneofoffset", + sizeof(uint32_t) * field->containing_oneof()->index()); + format( + "{PROTOBUF_FIELD_OFFSET($classtype$, $field_name$_), $1$," + " PROTOBUF_FIELD_OFFSET($classtype$, _oneof_case_) + " + "$oneofoffset$, $2$, $3$},\n", + tag, type, ptr); + } else if (HasHasbit(field)) { + format.Set("hasbitsoffset", has_bit_indices_[field->index()]); + format( + "{PROTOBUF_FIELD_OFFSET($classtype$, $field_name$_), " + "$1$, PROTOBUF_FIELD_OFFSET($classtype$, _has_bits_) * 8 + " + "$hasbitsoffset$, $2$, $3$},\n", + tag, type, ptr); + } else { + format( + "{PROTOBUF_FIELD_OFFSET($classtype$, $field_name$_), " + "$1$, ~0u, $2$, $3$},\n", + tag, type, ptr); + } + } + int num_field_metadata = 1 + sorted.size() + sorted_extensions.size(); + num_field_metadata++; + std::string serializer = UseUnknownFieldSet(descriptor_->file(), options_) + ? "UnknownFieldSetSerializer" + : "UnknownFieldSerializerLite"; + format( + "{PROTOBUF_FIELD_OFFSET($classtype$, _internal_metadata_), 0, ~0u, " + "::$proto_ns$::internal::FieldMetadata::kSpecial, reinterpret_cast(::$proto_ns$::internal::$1$)},\n", + serializer); + return num_field_metadata; +} + +void MessageGenerator::GenerateClassMethods(io::Printer* printer) { + Formatter format(printer, variables_); + if (IsMapEntryMessage(descriptor_)) { + format( + "$classname$::$classname$() {}\n" + "$classname$::$classname$(::$proto_ns$::Arena* arena)\n" + " : SuperType(arena) {}\n" + "void $classname$::MergeFrom(const $classname$& other) {\n" + " MergeFromInternal(other);\n" + "}\n"); + if (HasDescriptorMethods(descriptor_->file(), options_)) { + if (!descriptor_->options().map_entry()) { + format( + "::$proto_ns$::Metadata $classname$::GetMetadata() const {\n" + "$annotate_reflection$" + " return ::$proto_ns$::internal::AssignDescriptors(\n" + " &$desc_table$_getter, &$desc_table$_once,\n" + " $file_level_metadata$[$1$]);\n" + "}\n", + index_in_file_messages_); + } else { + format( + "::$proto_ns$::Metadata $classname$::GetMetadata() const {\n" + " return ::$proto_ns$::internal::AssignDescriptors(\n" + " &$desc_table$_getter, &$desc_table$_once,\n" + " $file_level_metadata$[$1$]);\n" + "}\n", + index_in_file_messages_); + } + } + return; + } + + if (IsAnyMessage(descriptor_, options_)) { + if (HasDescriptorMethods(descriptor_->file(), options_)) { + format( + "bool $classname$::GetAnyFieldDescriptors(\n" + " const ::$proto_ns$::Message& message,\n" + " const ::$proto_ns$::FieldDescriptor** type_url_field,\n" + " const ::$proto_ns$::FieldDescriptor** value_field) {\n" + " return ::$proto_ns$::internal::GetAnyFieldDescriptors(\n" + " message, type_url_field, value_field);\n" + "}\n"); + } + format( + "bool $classname$::ParseAnyTypeUrl(\n" + " ::PROTOBUF_NAMESPACE_ID::ConstStringParam type_url,\n" + " std::string* full_type_name) {\n" + " return ::$proto_ns$::internal::ParseAnyTypeUrl(type_url,\n" + " full_type_name);\n" + "}\n" + "\n"); + } + + format( + "class $classname$::_Internal {\n" + " public:\n"); + format.Indent(); + if (!has_bit_indices_.empty()) { + format( + "using HasBits = decltype(std::declval<$classname$>()._has_bits_);\n"); + } + for (auto field : FieldRange(descriptor_)) { + field_generators_.get(field).GenerateInternalAccessorDeclarations(printer); + if (IsFieldStripped(field, options_)) { + continue; + } + if (HasHasbit(field)) { + int has_bit_index = HasBitIndex(field); + GOOGLE_CHECK_NE(has_bit_index, kNoHasbit) << field->full_name(); + format( + "static void set_has_$1$(HasBits* has_bits) {\n" + " (*has_bits)[$2$] |= $3$u;\n" + "}\n", + FieldName(field), has_bit_index / 32, (1u << (has_bit_index % 32))); + } + } + if (num_required_fields_ > 0) { + const std::vector masks_for_has_bits = RequiredFieldsBitMask(); + format( + "static bool MissingRequiredFields(const HasBits& has_bits) " + "{\n" + " return $1$;\n" + "}\n", + ConditionalToCheckBitmasks(masks_for_has_bits, false, "has_bits")); + } + + format.Outdent(); + format("};\n\n"); + for (auto field : FieldRange(descriptor_)) { + if (!IsFieldStripped(field, options_)) { + field_generators_.get(field).GenerateInternalAccessorDefinitions(printer); + } + } + + // Generate non-inline field definitions. + for (auto field : FieldRange(descriptor_)) { + if (IsFieldStripped(field, options_)) { + continue; + } + field_generators_.get(field).GenerateNonInlineAccessorDefinitions(printer); + if (IsCrossFileMaybeMap(field)) { + Formatter::SaveState saver(&format); + std::map vars; + SetCommonFieldVariables(field, &vars, options_); + if (field->real_containing_oneof()) { + SetCommonOneofFieldVariables(field, &vars); + } + format.AddMap(vars); + GenerateFieldClear(field, false, format); + } + } + + GenerateStructors(printer); + format("\n"); + + if (descriptor_->real_oneof_decl_count() > 0) { + GenerateOneofClear(printer); + format("\n"); + } + + if (HasGeneratedMethods(descriptor_->file(), options_)) { + GenerateClear(printer); + format("\n"); + + if (!HasSimpleBaseClass(descriptor_, options_)) { + parse_function_generator_->GenerateMethodImpls(printer); + format("\n"); + + parse_function_generator_->GenerateDataDefinitions(printer); + } + + GenerateSerializeWithCachedSizesToArray(printer); + format("\n"); + + GenerateByteSize(printer); + format("\n"); + + GenerateMergeFrom(printer); + format("\n"); + + GenerateClassSpecificMergeFrom(printer); + format("\n"); + + GenerateCopyFrom(printer); + format("\n"); + + GenerateIsInitialized(printer); + format("\n"); + } + + GenerateVerify(printer); + + GenerateSwap(printer); + format("\n"); + + if (options_.table_driven_serialization) { + format( + "const void* $classname$::InternalGetTable() const {\n" + " return ::$tablename$::serialization_table + $1$;\n" + "}\n" + "\n", + index_in_file_messages_); + } + if (HasDescriptorMethods(descriptor_->file(), options_)) { + if (!descriptor_->options().map_entry()) { + format( + "::$proto_ns$::Metadata $classname$::GetMetadata() const {\n" + "$annotate_reflection$" + " return ::$proto_ns$::internal::AssignDescriptors(\n" + " &$desc_table$_getter, &$desc_table$_once,\n" + " $file_level_metadata$[$1$]);\n" + "}\n", + index_in_file_messages_); + } else { + format( + "::$proto_ns$::Metadata $classname$::GetMetadata() const {\n" + " return ::$proto_ns$::internal::AssignDescriptors(\n" + " &$desc_table$_getter, &$desc_table$_once,\n" + " $file_level_metadata$[$1$]);\n" + "}\n", + index_in_file_messages_); + } + } else { + format( + "std::string $classname$::GetTypeName() const {\n" + " return \"$full_name$\";\n" + "}\n" + "\n"); + } + + if (options_.field_listener_options.inject_field_listener_events && + descriptor_->file()->options().optimize_for() != + google::protobuf::FileOptions::LITE_RUNTIME) { + format( + "::$proto_ns$::AccessListener<$classtype$> " + "$1$::_tracker_(&FullMessageName);\n", + ClassName(descriptor_)); + } +} + +size_t MessageGenerator::GenerateParseOffsets(io::Printer* printer) { + Formatter format(printer, variables_); + + if (!table_driven_) { + return 0; + } + + // Field "0" is special: We use it in our switch statement of processing + // types to handle the successful end tag case. + format("{0, 0, 0, ::$proto_ns$::internal::kInvalidMask, 0, 0},\n"); + int last_field_number = 1; + + std::vector ordered_fields = + SortFieldsByNumber(descriptor_); + + for (auto field : ordered_fields) { + Formatter::SaveState saver(&format); + GOOGLE_CHECK_GE(field->number(), last_field_number); + + for (; last_field_number < field->number(); last_field_number++) { + format( + "{ 0, 0, ::$proto_ns$::internal::kInvalidMask,\n" + " ::$proto_ns$::internal::kInvalidMask, 0, 0 },\n"); + } + last_field_number++; + + unsigned char normal_wiretype, packed_wiretype, processing_type; + normal_wiretype = WireFormat::WireTypeForFieldType(field->type()); + + if (field->is_packable()) { + packed_wiretype = WireFormatLite::WIRETYPE_LENGTH_DELIMITED; + } else { + packed_wiretype = internal::kNotPackedMask; + } + + processing_type = static_cast(field->type()); + const FieldGenerator& generator = field_generators_.get(field); + if (field->type() == FieldDescriptor::TYPE_STRING) { + switch (EffectiveStringCType(field, options_)) { + case FieldOptions::STRING: + if (generator.IsInlined()) { + processing_type = internal::TYPE_STRING_INLINED; + } + break; + case FieldOptions::CORD: + processing_type = internal::TYPE_STRING_CORD; + break; + case FieldOptions::STRING_PIECE: + processing_type = internal::TYPE_STRING_STRING_PIECE; + break; + } + } else if (field->type() == FieldDescriptor::TYPE_BYTES) { + switch (EffectiveStringCType(field, options_)) { + case FieldOptions::STRING: + if (generator.IsInlined()) { + processing_type = internal::TYPE_BYTES_INLINED; + } + break; + case FieldOptions::CORD: + processing_type = internal::TYPE_BYTES_CORD; + break; + case FieldOptions::STRING_PIECE: + processing_type = internal::TYPE_BYTES_STRING_PIECE; + break; + } + } + + processing_type |= static_cast( + field->is_repeated() ? internal::kRepeatedMask : 0); + processing_type |= static_cast( + field->real_containing_oneof() ? internal::kOneofMask : 0); + + if (field->is_map()) { + processing_type = internal::TYPE_MAP; + } + + const unsigned char tag_size = + WireFormat::TagSize(field->number(), field->type()); + + std::map vars; + if (field->real_containing_oneof()) { + vars["name"] = field->containing_oneof()->name(); + vars["presence"] = StrCat(field->containing_oneof()->index()); + } else { + vars["name"] = FieldName(field); + vars["presence"] = StrCat(has_bit_indices_[field->index()]); + } + vars["nwtype"] = StrCat(normal_wiretype); + vars["pwtype"] = StrCat(packed_wiretype); + vars["ptype"] = StrCat(processing_type); + vars["tag_size"] = StrCat(tag_size); + + format.AddMap(vars); + + format( + "{\n" + " PROTOBUF_FIELD_OFFSET($classtype$, $name$_),\n" + " static_cast<$uint32$>($presence$),\n" + " $nwtype$, $pwtype$, $ptype$, $tag_size$\n" + "},\n"); + } + + return last_field_number; +} + +size_t MessageGenerator::GenerateParseAuxTable(io::Printer* printer) { + Formatter format(printer, variables_); + + if (!table_driven_) { + return 0; + } + + std::vector ordered_fields = + SortFieldsByNumber(descriptor_); + + format("::$proto_ns$::internal::AuxiliaryParseTableField(),\n"); + int last_field_number = 1; + for (auto field : ordered_fields) { + Formatter::SaveState saver(&format); + + GOOGLE_CHECK_GE(field->number(), last_field_number); + for (; last_field_number < field->number(); last_field_number++) { + format("::$proto_ns$::internal::AuxiliaryParseTableField(),\n"); + } + + std::map vars; + SetCommonFieldVariables(field, &vars, options_); + format.AddMap(vars); + + switch (field->cpp_type()) { + case FieldDescriptor::CPPTYPE_ENUM: + if (HasPreservingUnknownEnumSemantics(field)) { + format( + "{::$proto_ns$::internal::AuxiliaryParseTableField::enum_aux{" + "nullptr}},\n"); + } else { + format( + "{::$proto_ns$::internal::AuxiliaryParseTableField::enum_aux{" + "$1$_IsValid}},\n", + ClassName(field->enum_type(), true)); + } + last_field_number++; + break; + case FieldDescriptor::CPPTYPE_MESSAGE: { + if (field->is_map()) { + format( + "{::$proto_ns$::internal::AuxiliaryParseTableField::map_" + "aux{&::$proto_ns$::internal::ParseMap<$1$>}},\n", + QualifiedClassName(field->message_type(), options_)); + last_field_number++; + break; + } + format.Set("field_classname", ClassName(field->message_type(), false)); + format.Set("default_instance", QualifiedDefaultInstanceName( + field->message_type(), options_)); + + format( + "{::$proto_ns$::internal::AuxiliaryParseTableField::message_aux{\n" + " &$default_instance$}},\n"); + last_field_number++; + break; + } + case FieldDescriptor::CPPTYPE_STRING: { + std::string default_val; + switch (EffectiveStringCType(field, options_)) { + case FieldOptions::STRING: + default_val = field->default_value_string().empty() + ? "&::" + variables_["proto_ns"] + + "::internal::fixed_address_empty_string" + : "&" + + QualifiedClassName(descriptor_, options_) + + "::" + MakeDefaultName(field); + break; + case FieldOptions::CORD: + case FieldOptions::STRING_PIECE: + default_val = + "\"" + CEscape(field->default_value_string()) + "\""; + break; + } + format( + "{::$proto_ns$::internal::AuxiliaryParseTableField::string_aux{\n" + " $1$,\n" + " \"$2$\"\n" + "}},\n", + default_val, field->full_name()); + last_field_number++; + break; + } + default: + break; + } + } + + return last_field_number; +} + +std::pair MessageGenerator::GenerateOffsets( + io::Printer* printer) { + Formatter format(printer, variables_); + + if (!has_bit_indices_.empty() || IsMapEntryMessage(descriptor_)) { + format("PROTOBUF_FIELD_OFFSET($classtype$, _has_bits_),\n"); + } else { + format("~0u, // no _has_bits_\n"); + } + format("PROTOBUF_FIELD_OFFSET($classtype$, _internal_metadata_),\n"); + if (descriptor_->extension_range_count() > 0) { + format("PROTOBUF_FIELD_OFFSET($classtype$, _extensions_),\n"); + } else { + format("~0u, // no _extensions_\n"); + } + if (descriptor_->real_oneof_decl_count() > 0) { + format("PROTOBUF_FIELD_OFFSET($classtype$, _oneof_case_[0]),\n"); + } else { + format("~0u, // no _oneof_case_\n"); + } + if (num_weak_fields_ > 0) { + format("PROTOBUF_FIELD_OFFSET($classtype$, _weak_field_map_),\n"); + } else { + format("~0u, // no _weak_field_map_\n"); + } + if (!inlined_string_indices_.empty()) { + format("PROTOBUF_FIELD_OFFSET($classtype$, _inlined_string_donated_),\n"); + } else { + format("~0u, // no _inlined_string_donated_\n"); + } + const int kNumGenericOffsets = 6; // the number of fixed offsets above + const size_t offsets = kNumGenericOffsets + descriptor_->field_count() + + descriptor_->real_oneof_decl_count(); + size_t entries = offsets; + for (auto field : FieldRange(descriptor_)) { + if (IsFieldStripped(field, options_)) { + format("~0u, // stripped\n"); + continue; + } + // TODO(sbenza): We should not have an entry in the offset table for fields + // that do not use them. + if (field->options().weak() || field->real_containing_oneof()) { + // Mark the field to prevent unintentional access through reflection. + // Don't use the top bit because that is for unused fields. + format("::$proto_ns$::internal::kInvalidFieldOffsetTag"); + } else { + format("PROTOBUF_FIELD_OFFSET($classtype$, $1$_)", FieldName(field)); + } + + // Some information about a field is in the pdproto profile. The profile is + // only available at compile time. So we embed such information in the + // offset of the field, so that the information is available when + // reflectively accessing the field at run time. + // + // Embed whether the field is used to the MSB of the offset. + if (!IsFieldUsed(field, options_)) { + format(" | 0x80000000u // unused\n"); + } + + // Embed whether the field is eagerly verified lazy or inlined string to the + // LSB of the offset. + if (IsEagerlyVerifiedLazy(field, options_, scc_analyzer_)) { + format(" | 0x1u // eagerly verified lazy\n"); + } else if (IsStringInlined(field, options_)) { + format(" | 0x1u // inlined\n"); + } + format(",\n"); + } + + int count = 0; + for (auto oneof : OneOfRange(descriptor_)) { + format("PROTOBUF_FIELD_OFFSET($classtype$, $1$_),\n", oneof->name()); + count++; + } + GOOGLE_CHECK_EQ(count, descriptor_->real_oneof_decl_count()); + + if (IsMapEntryMessage(descriptor_)) { + entries += 2; + format( + "0,\n" + "1,\n"); + } else if (!has_bit_indices_.empty()) { + entries += has_bit_indices_.size(); + for (int i = 0; i < has_bit_indices_.size(); i++) { + const std::string index = + has_bit_indices_[i] >= 0 ? StrCat(has_bit_indices_[i]) : "~0u"; + format("$1$,\n", index); + } + } + if (!inlined_string_indices_.empty()) { + entries += inlined_string_indices_.size(); + for (int inlined_string_indice : inlined_string_indices_) { + const std::string index = inlined_string_indice >= 0 + ? StrCat(inlined_string_indice) + : "~0u"; + format("$1$,\n", index); + } + } + + return std::make_pair(entries, offsets); +} + +void MessageGenerator::GenerateSharedConstructorCode(io::Printer* printer) { + if (HasSimpleBaseClass(descriptor_, options_)) return; + Formatter format(printer, variables_); + + format("inline void $classname$::SharedCtor() {\n"); + + std::vector processed(optimized_order_.size(), false); + GenerateConstructorBody(printer, processed, false); + + for (auto oneof : OneOfRange(descriptor_)) { + format("clear_has_$1$();\n", oneof->name()); + } + + format("}\n\n"); +} + +void MessageGenerator::GenerateSharedDestructorCode(io::Printer* printer) { + if (HasSimpleBaseClass(descriptor_, options_)) return; + Formatter format(printer, variables_); + + format("inline void $classname$::SharedDtor() {\n"); + format.Indent(); + format("$DCHK$(GetArenaForAllocation() == nullptr);\n"); + // Write the destructors for each field except oneof members. + // optimized_order_ does not contain oneof fields. + for (auto field : optimized_order_) { + field_generators_.get(field).GenerateDestructorCode(printer); + } + + // Generate code to destruct oneofs. Clearing should do the work. + for (auto oneof : OneOfRange(descriptor_)) { + format( + "if (has_$1$()) {\n" + " clear_$1$();\n" + "}\n", + oneof->name()); + } + + if (num_weak_fields_) { + format("_weak_field_map_.ClearAll();\n"); + } + format.Outdent(); + format( + "}\n" + "\n"); +} + +void MessageGenerator::GenerateArenaDestructorCode(io::Printer* printer) { + if (HasSimpleBaseClass(descriptor_, options_)) return; + Formatter format(printer, variables_); + + // Generate the ArenaDtor() method. Track whether any fields actually produced + // code that needs to be called. + format("void $classname$::ArenaDtor(void* object) {\n"); + format.Indent(); + + // This code is placed inside a static method, rather than an ordinary one, + // since that simplifies Arena's destructor list (ordinary function pointers + // rather than member function pointers). _this is the object being + // destructed. + format( + "$classname$* _this = reinterpret_cast< $classname$* >(object);\n" + // avoid an "unused variable" warning in case no fields have dtor code. + "(void)_this;\n"); + + bool need_registration = false; + // Process non-oneof fields first. + for (auto field : optimized_order_) { + if (field_generators_.get(field).GenerateArenaDestructorCode(printer)) { + need_registration = true; + } + } + + // Process oneof fields. + // + // Note: As of 10/5/2016, GenerateArenaDestructorCode does not emit anything + // and returns false for oneof fields. + for (auto oneof : OneOfRange(descriptor_)) { + for (auto field : FieldRange(oneof)) { + if (!IsFieldStripped(field, options_) && + field_generators_.get(field).GenerateArenaDestructorCode(printer)) { + need_registration = true; + } + } + } + + format.Outdent(); + format("}\n"); + + if (need_registration) { + format( + "inline void $classname$::RegisterArenaDtor(::$proto_ns$::Arena* " + "arena) {\n" + " if (arena != nullptr) {\n" + " arena->OwnCustomDestructor(this, &$classname$::ArenaDtor);\n" + " }\n" + "}\n"); + } else { + format( + "void $classname$::RegisterArenaDtor(::$proto_ns$::Arena*) {\n" + "}\n"); + } +} + +void MessageGenerator::GenerateConstexprConstructor(io::Printer* printer) { + Formatter format(printer, variables_); + + format( + "constexpr $classname$::$classname$(\n" + " ::$proto_ns$::internal::ConstantInitialized)"); + format.Indent(); + const char* field_sep = ":"; + const auto put_sep = [&] { + format("\n$1$ ", field_sep); + field_sep = ","; + }; + + if (!IsMapEntryMessage(descriptor_)) { + // Process non-oneof fields first. + for (auto field : optimized_order_) { + auto& gen = field_generators_.get(field); + put_sep(); + gen.GenerateConstinitInitializer(printer); + } + + if (IsAnyMessage(descriptor_, options_)) { + put_sep(); + format("_any_metadata_(&type_url_, &value_)"); + } + + if (descriptor_->real_oneof_decl_count() != 0) { + put_sep(); + format("_oneof_case_{}"); + } + } + + format.Outdent(); + format("{}\n"); +} + +void MessageGenerator::GenerateConstructorBody(io::Printer* printer, + std::vector processed, + bool copy_constructor) const { + Formatter format(printer, variables_); + + const RunMap runs = FindRuns( + optimized_order_, [copy_constructor, this](const FieldDescriptor* field) { + return (copy_constructor && IsPOD(field)) || + (!copy_constructor && + CanBeManipulatedAsRawBytes(field, options_, scc_analyzer_)); + }); + + std::string pod_template; + if (copy_constructor) { + pod_template = + "::memcpy(&$first$_, &from.$first$_,\n" + " static_cast(reinterpret_cast(&$last$_) -\n" + " reinterpret_cast(&$first$_)) + sizeof($last$_));\n"; + } else { + pod_template = + "::memset(reinterpret_cast(this) + static_cast(\n" + " reinterpret_cast(&$first$_) - " + "reinterpret_cast(this)),\n" + " 0, static_cast(reinterpret_cast(&$last$_) -\n" + " reinterpret_cast(&$first$_)) + sizeof($last$_));\n"; + } + + for (int i = 0; i < optimized_order_.size(); ++i) { + if (processed[i]) { + continue; + } + + const FieldDescriptor* field = optimized_order_[i]; + const auto it = runs.find(field); + + // We only apply the memset technique to runs of more than one field, as + // assignment is better than memset for generated code clarity. + if (it != runs.end() && it->second > 1) { + // Use a memset, then skip run_length fields. + const size_t run_length = it->second; + const std::string first_field_name = FieldName(field); + const std::string last_field_name = + FieldName(optimized_order_[i + run_length - 1]); + + format.Set("first", first_field_name); + format.Set("last", last_field_name); + + format(pod_template.c_str()); + + i += run_length - 1; + // ++i at the top of the loop. + } else { + if (copy_constructor) { + field_generators_.get(field).GenerateCopyConstructorCode(printer); + } else { + field_generators_.get(field).GenerateConstructorCode(printer); + } + } + } +} + +void MessageGenerator::GenerateStructors(io::Printer* printer) { + Formatter format(printer, variables_); + + std::string superclass; + superclass = SuperClassName(descriptor_, options_); + std::string initializer_with_arena = superclass + "(arena, is_message_owned)"; + + if (descriptor_->extension_range_count() > 0) { + initializer_with_arena += ",\n _extensions_(arena)"; + } + + // Initialize member variables with arena constructor. + for (auto field : optimized_order_) { + GOOGLE_DCHECK(!IsFieldStripped(field, options_)); + bool has_arena_constructor = field->is_repeated(); + if (!field->real_containing_oneof() && + (IsLazy(field, options_, scc_analyzer_) || + IsStringPiece(field, options_) || + (IsString(field, options_) && IsStringInlined(field, options_)))) { + has_arena_constructor = true; + } + if (has_arena_constructor) { + initializer_with_arena += + std::string(",\n ") + FieldName(field) + std::string("_(arena)"); + } + } + + if (IsAnyMessage(descriptor_, options_)) { + initializer_with_arena += ",\n _any_metadata_(&type_url_, &value_)"; + } + if (num_weak_fields_ > 0) { + initializer_with_arena += ", _weak_field_map_(arena)"; + } + + std::string initializer_null = superclass + "()"; + if (IsAnyMessage(descriptor_, options_)) { + initializer_null += ", _any_metadata_(&type_url_, &value_)"; + } + if (num_weak_fields_ > 0) { + initializer_null += ", _weak_field_map_(nullptr)"; + } + + format( + "$classname$::$classname$(::$proto_ns$::Arena* arena,\n" + " bool is_message_owned)\n" + " : $1$ {\n", + initializer_with_arena); + + if (!inlined_string_indices_.empty()) { + // Donate inline string fields. + format(" if (arena != nullptr) {\n"); + for (size_t i = 0; i < InlinedStringDonatedSize(); ++i) { + format(" _inlined_string_donated_[$1$] = ~0u;\n", i); + } + format(" }\n"); + } + + if (!HasSimpleBaseClass(descriptor_, options_)) { + format( + " SharedCtor();\n" + " if (!is_message_owned) {\n" + " RegisterArenaDtor(arena);\n" + " }\n"); + } + format( + " // @@protoc_insertion_point(arena_constructor:$full_name$)\n" + "}\n"); + + std::map vars; + SetUnknownFieldsVariable(descriptor_, options_, &vars); + format.AddMap(vars); + + // Generate the copy constructor. + if (UsingImplicitWeakFields(descriptor_->file(), options_)) { + // If we are in lite mode and using implicit weak fields, we generate a + // one-liner copy constructor that delegates to MergeFrom. This saves some + // code size and also cuts down on the complexity of implicit weak fields. + // We might eventually want to do this for all lite protos. + format( + "$classname$::$classname$(const $classname$& from)\n" + " : $classname$() {\n" + " MergeFrom(from);\n" + "}\n"); + } else { + format( + "$classname$::$classname$(const $classname$& from)\n" + " : $superclass$()"); + format.Indent(); + format.Indent(); + format.Indent(); + + // Do not copy inlined_string_donated_, because this is not an arena + // constructor. + + if (!has_bit_indices_.empty()) { + format(",\n_has_bits_(from._has_bits_)"); + } + + std::vector processed(optimized_order_.size(), false); + for (int i = 0; i < optimized_order_.size(); i++) { + auto field = optimized_order_[i]; + if (!(field->is_repeated() && !(field->is_map())) && + !IsCord(field, options_)) { + continue; + } + + processed[i] = true; + format(",\n$1$_(from.$1$_)", FieldName(field)); + } + + if (IsAnyMessage(descriptor_, options_)) { + format(",\n_any_metadata_(&type_url_, &value_)"); + } + if (num_weak_fields_ > 0) { + format(",\n_weak_field_map_(from._weak_field_map_)"); + } + + format.Outdent(); + format.Outdent(); + format(" {\n"); + + format( + "_internal_metadata_.MergeFrom<$unknown_fields_type$>(from._internal_" + "metadata_);\n"); + + if (descriptor_->extension_range_count() > 0) { + format( + "_extensions_.MergeFrom(internal_default_instance(), " + "from._extensions_);\n"); + } + + GenerateConstructorBody(printer, processed, true); + + // Copy oneof fields. Oneof field requires oneof case check. + for (auto oneof : OneOfRange(descriptor_)) { + format( + "clear_has_$1$();\n" + "switch (from.$1$_case()) {\n", + oneof->name()); + format.Indent(); + for (auto field : FieldRange(oneof)) { + format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true)); + format.Indent(); + if (!IsFieldStripped(field, options_)) { + field_generators_.get(field).GenerateMergingCode(printer); + } + format("break;\n"); + format.Outdent(); + format("}\n"); + } + format( + "case $1$_NOT_SET: {\n" + " break;\n" + "}\n", + ToUpper(oneof->name())); + format.Outdent(); + format("}\n"); + } + + format.Outdent(); + format( + " // @@protoc_insertion_point(copy_constructor:$full_name$)\n" + "}\n" + "\n"); + } + + // Generate the shared constructor code. + GenerateSharedConstructorCode(printer); + + // Generate the destructor. + if (!HasSimpleBaseClass(descriptor_, options_)) { + format( + "$classname$::~$classname$() {\n" + " // @@protoc_insertion_point(destructor:$full_name$)\n" + " if (GetArenaForAllocation() != nullptr) return;\n" + " SharedDtor();\n" + " _internal_metadata_.Delete<$unknown_fields_type$>();\n" + "}\n" + "\n"); + } else { + // For messages using simple base classes, having no destructor + // allows our vtable to share the same destructor as every other + // message with a simple base class. This works only as long as + // we have no fields needing destruction, of course. (No strings + // or extensions) + } + + // Generate the shared destructor code. + GenerateSharedDestructorCode(printer); + + // Generate the arena-specific destructor code. + GenerateArenaDestructorCode(printer); + + if (!HasSimpleBaseClass(descriptor_, options_)) { + // Generate SetCachedSize. + format( + "void $classname$::SetCachedSize(int size) const {\n" + " _cached_size_.Set(size);\n" + "}\n"); + } +} + +void MessageGenerator::GenerateSourceInProto2Namespace(io::Printer* printer) { + Formatter format(printer, variables_); + format( + "template<> " + "PROTOBUF_NOINLINE " + "$classtype$* Arena::CreateMaybeMessage< $classtype$ >(Arena* arena) {\n" + " return Arena::CreateMessageInternal< $classtype$ >(arena);\n" + "}\n"); +} + +void MessageGenerator::GenerateClear(io::Printer* printer) { + if (HasSimpleBaseClass(descriptor_, options_)) return; + Formatter format(printer, variables_); + + // The maximum number of bytes we will memset to zero without checking their + // hasbit to see if a zero-init is necessary. + const int kMaxUnconditionalPrimitiveBytesClear = 4; + + format( + "void $classname$::Clear() {\n" + "// @@protoc_insertion_point(message_clear_start:$full_name$)\n"); + format.Indent(); + + format( + // TODO(jwb): It would be better to avoid emitting this if it is not used, + // rather than emitting a workaround for the resulting warning. + "$uint32$ cached_has_bits = 0;\n" + "// Prevent compiler warnings about cached_has_bits being unused\n" + "(void) cached_has_bits;\n\n"); + + if (descriptor_->extension_range_count() > 0) { + format("_extensions_.Clear();\n"); + } + + // Collect fields into chunks. Each chunk may have an if() condition that + // checks all hasbits in the chunk and skips it if none are set. + int zero_init_bytes = 0; + for (const auto& field : optimized_order_) { + if (CanInitializeByZeroing(field)) { + zero_init_bytes += EstimateAlignmentSize(field); + } + } + bool merge_zero_init = zero_init_bytes > kMaxUnconditionalPrimitiveBytesClear; + int chunk_count = 0; + + std::vector> chunks = CollectFields( + optimized_order_, + [&](const FieldDescriptor* a, const FieldDescriptor* b) -> bool { + chunk_count++; + // This predicate guarantees that there is only a single zero-init + // (memset) per chunk, and if present it will be at the beginning. + bool same = HasByteIndex(a) == HasByteIndex(b) && + a->is_repeated() == b->is_repeated() && + (CanInitializeByZeroing(a) == CanInitializeByZeroing(b) || + (CanInitializeByZeroing(a) && + (chunk_count == 1 || merge_zero_init))); + if (!same) chunk_count = 0; + return same; + }); + + ColdChunkSkipper cold_skipper(options_, chunks, has_bit_indices_, kColdRatio); + int cached_has_word_index = -1; + + for (int chunk_index = 0; chunk_index < chunks.size(); chunk_index++) { + std::vector& chunk = chunks[chunk_index]; + cold_skipper.OnStartChunk(chunk_index, cached_has_word_index, "", printer); + + const FieldDescriptor* memset_start = nullptr; + const FieldDescriptor* memset_end = nullptr; + bool saw_non_zero_init = false; + + for (const auto& field : chunk) { + if (CanInitializeByZeroing(field)) { + GOOGLE_CHECK(!saw_non_zero_init); + if (!memset_start) memset_start = field; + memset_end = field; + } else { + saw_non_zero_init = true; + } + } + + // Whether we wrap this chunk in: + // if (cached_has_bits & 1 && + (memset_end != chunk.back() || merge_zero_init); + + if (have_outer_if) { + // Emit an if() that will let us skip the whole chunk if none are set. + uint32_t chunk_mask = GenChunkMask(chunk, has_bit_indices_); + std::string chunk_mask_str = + StrCat(strings::Hex(chunk_mask, strings::ZERO_PAD_8)); + + // Check (up to) 8 has_bits at a time if we have more than one field in + // this chunk. Due to field layout ordering, we may check + // _has_bits_[last_chunk * 8 / 32] multiple times. + GOOGLE_DCHECK_LE(2, popcnt(chunk_mask)); + GOOGLE_DCHECK_GE(8, popcnt(chunk_mask)); + + if (cached_has_word_index != HasWordIndex(chunk.front())) { + cached_has_word_index = HasWordIndex(chunk.front()); + format("cached_has_bits = _has_bits_[$1$];\n", cached_has_word_index); + } + format("if (cached_has_bits & 0x$1$u) {\n", chunk_mask_str); + format.Indent(); + } + + if (memset_start) { + if (memset_start == memset_end) { + // For clarity, do not memset a single field. + field_generators_.get(memset_start) + .GenerateMessageClearingCode(printer); + } else { + format( + "::memset(&$1$_, 0, static_cast(\n" + " reinterpret_cast(&$2$_) -\n" + " reinterpret_cast(&$1$_)) + sizeof($2$_));\n", + FieldName(memset_start), FieldName(memset_end)); + } + } + + // Clear all non-zero-initializable fields in the chunk. + for (const auto& field : chunk) { + if (CanInitializeByZeroing(field)) continue; + // It's faster to just overwrite primitive types, but we should only + // clear strings and messages if they were set. + // + // TODO(kenton): Let the CppFieldGenerator decide this somehow. + bool have_enclosing_if = + HasBitIndex(field) != kNoHasbit && + (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE || + field->cpp_type() == FieldDescriptor::CPPTYPE_STRING); + + if (have_enclosing_if) { + PrintPresenceCheck(format, field, has_bit_indices_, printer, + &cached_has_word_index); + } + + field_generators_.get(field).GenerateMessageClearingCode(printer); + + if (have_enclosing_if) { + format.Outdent(); + format("}\n"); + } + } + + if (have_outer_if) { + format.Outdent(); + format("}\n"); + } + + if (cold_skipper.OnEndChunk(chunk_index, printer)) { + // Reset here as it may have been updated in just closed if statement. + cached_has_word_index = -1; + } + } + + // Step 4: Unions. + for (auto oneof : OneOfRange(descriptor_)) { + format("clear_$1$();\n", oneof->name()); + } + + if (num_weak_fields_) { + format("_weak_field_map_.ClearAll();\n"); + } + + // We don't clear donated status. + + if (!has_bit_indices_.empty()) { + // Step 5: Everything else. + format("_has_bits_.Clear();\n"); + } + + std::map vars; + SetUnknownFieldsVariable(descriptor_, options_, &vars); + format.AddMap(vars); + format("_internal_metadata_.Clear<$unknown_fields_type$>();\n"); + + format.Outdent(); + format("}\n"); +} + +void MessageGenerator::GenerateOneofClear(io::Printer* printer) { + // Generated function clears the active field and union case (e.g. foo_case_). + int i = 0; + for (auto oneof : OneOfRange(descriptor_)) { + Formatter format(printer, variables_); + format.Set("oneofname", oneof->name()); + + format( + "void $classname$::clear_$oneofname$() {\n" + "// @@protoc_insertion_point(one_of_clear_start:$full_name$)\n"); + format.Indent(); + format("switch ($oneofname$_case()) {\n"); + format.Indent(); + for (auto field : FieldRange(oneof)) { + format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true)); + format.Indent(); + // We clear only allocated objects in oneofs + if (!IsStringOrMessage(field) || IsFieldStripped(field, options_)) { + format("// No need to clear\n"); + } else { + field_generators_.get(field).GenerateClearingCode(printer); + } + format("break;\n"); + format.Outdent(); + format("}\n"); + } + format( + "case $1$_NOT_SET: {\n" + " break;\n" + "}\n", + ToUpper(oneof->name())); + format.Outdent(); + format( + "}\n" + "_oneof_case_[$1$] = $2$_NOT_SET;\n", + i, ToUpper(oneof->name())); + format.Outdent(); + format( + "}\n" + "\n"); + i++; + } +} + +void MessageGenerator::GenerateSwap(io::Printer* printer) { + if (HasSimpleBaseClass(descriptor_, options_)) return; + Formatter format(printer, variables_); + + format("void $classname$::InternalSwap($classname$* other) {\n"); + format.Indent(); + format("using std::swap;\n"); + + if (HasGeneratedMethods(descriptor_->file(), options_)) { + if (descriptor_->extension_range_count() > 0) { + format("_extensions_.InternalSwap(&other->_extensions_);\n"); + } + + std::map vars; + SetUnknownFieldsVariable(descriptor_, options_, &vars); + format.AddMap(vars); + if (HasSingularString(descriptor_, options_)) { + format( + "auto* lhs_arena = GetArenaForAllocation();\n" + "auto* rhs_arena = other->GetArenaForAllocation();\n"); + } + format("_internal_metadata_.InternalSwap(&other->_internal_metadata_);\n"); + + if (!has_bit_indices_.empty()) { + for (int i = 0; i < HasBitsSize(); ++i) { + format("swap(_has_bits_[$1$], other->_has_bits_[$1$]);\n", i); + } + } + + // If possible, we swap several fields at once, including padding. + const RunMap runs = + FindRuns(optimized_order_, [this](const FieldDescriptor* field) { + return CanBeManipulatedAsRawBytes(field, options_, scc_analyzer_); + }); + + for (int i = 0; i < optimized_order_.size(); ++i) { + const FieldDescriptor* field = optimized_order_[i]; + const auto it = runs.find(field); + + // We only apply the memswap technique to runs of more than one field, as + // `swap(field_, other.field_)` is better than + // `memswap<...>(&field_, &other.field_)` for generated code readability. + if (it != runs.end() && it->second > 1) { + // Use a memswap, then skip run_length fields. + const size_t run_length = it->second; + const std::string first_field_name = FieldName(field); + const std::string last_field_name = + FieldName(optimized_order_[i + run_length - 1]); + + format.Set("first", first_field_name); + format.Set("last", last_field_name); + + format( + "::PROTOBUF_NAMESPACE_ID::internal::memswap<\n" + " PROTOBUF_FIELD_OFFSET($classname$, $last$_)\n" + " + sizeof($classname$::$last$_)\n" + " - PROTOBUF_FIELD_OFFSET($classname$, $first$_)>(\n" + " reinterpret_cast(&$first$_),\n" + " reinterpret_cast(&other->$first$_));\n"); + + i += run_length - 1; + // ++i at the top of the loop. + } else { + field_generators_.get(field).GenerateSwappingCode(printer); + } + } + + for (auto oneof : OneOfRange(descriptor_)) { + format("swap($1$_, other->$1$_);\n", oneof->name()); + } + + for (int i = 0; i < descriptor_->real_oneof_decl_count(); i++) { + format("swap(_oneof_case_[$1$], other->_oneof_case_[$1$]);\n", i); + } + + if (num_weak_fields_) { + format("_weak_field_map_.UnsafeArenaSwap(&other->_weak_field_map_);\n"); + } + } else { + format("GetReflection()->Swap(this, other);"); + } + + format.Outdent(); + format("}\n"); +} + +void MessageGenerator::GenerateMergeFrom(io::Printer* printer) { + Formatter format(printer, variables_); + if (!HasSimpleBaseClass(descriptor_, options_)) { + if (HasDescriptorMethods(descriptor_->file(), options_)) { + // We don't override the generalized MergeFrom (aka that which + // takes in the Message base class as a parameter); instead we just + // let the base Message::MergeFrom take care of it. The base MergeFrom + // knows how to quickly confirm the types exactly match, and if so, will + // use GetClassData() to retrieve the address of MergeImpl, which calls + // the fast MergeFrom overload. Most callers avoid all this by passing + // a "from" message that is the same type as the message being merged + // into, rather than a generic Message. + + format( + "const ::$proto_ns$::Message::ClassData " + "$classname$::_class_data_ = {\n" + " ::$proto_ns$::Message::CopyWithSizeCheck,\n" + " $classname$::MergeImpl\n" + "};\n" + "const ::$proto_ns$::Message::ClassData*" + "$classname$::GetClassData() const { return &_class_data_; }\n" + "\n" + "void $classname$::MergeImpl(::$proto_ns$::Message* to,\n" + " const ::$proto_ns$::Message& from) {\n" + " static_cast<$classname$ *>(to)->MergeFrom(\n" + " static_cast(from));\n" + "}\n" + "\n"); + } else { + // Generate CheckTypeAndMergeFrom(). + format( + "void $classname$::CheckTypeAndMergeFrom(\n" + " const ::$proto_ns$::MessageLite& from) {\n" + " MergeFrom(*::$proto_ns$::internal::DownCast(\n" + " &from));\n" + "}\n"); + } + } else { + // In the simple case, we just define ClassData that vectors back to the + // simple implementation of Copy and Merge. + format( + "const ::$proto_ns$::Message::ClassData " + "$classname$::_class_data_ = {\n" + " $superclass$::CopyImpl,\n" + " $superclass$::MergeImpl,\n" + "};\n" + "const ::$proto_ns$::Message::ClassData*" + "$classname$::GetClassData() const { return &_class_data_; }\n" + "\n" + "\n"); + } +} + +void MessageGenerator::GenerateClassSpecificMergeFrom(io::Printer* printer) { + if (HasSimpleBaseClass(descriptor_, options_)) return; + // Generate the class-specific MergeFrom, which avoids the GOOGLE_CHECK and cast. + Formatter format(printer, variables_); + format( + "void $classname$::MergeFrom(const $classname$& from) {\n" + "$annotate_mergefrom$" + "// @@protoc_insertion_point(class_specific_merge_from_start:" + "$full_name$)\n" + " $DCHK$_NE(&from, this);\n"); + format.Indent(); + + format( + "$uint32$ cached_has_bits = 0;\n" + "(void) cached_has_bits;\n\n"); + + std::vector> chunks = CollectFields( + optimized_order_, + [&](const FieldDescriptor* a, const FieldDescriptor* b) -> bool { + return HasByteIndex(a) == HasByteIndex(b); + }); + + ColdChunkSkipper cold_skipper(options_, chunks, has_bit_indices_, kColdRatio); + + // cached_has_word_index maintains that: + // cached_has_bits = from._has_bits_[cached_has_word_index] + // for cached_has_word_index >= 0 + int cached_has_word_index = -1; + + for (int chunk_index = 0; chunk_index < chunks.size(); chunk_index++) { + const std::vector& chunk = chunks[chunk_index]; + bool have_outer_if = + chunk.size() > 1 && HasByteIndex(chunk.front()) != kNoHasbit; + cold_skipper.OnStartChunk(chunk_index, cached_has_word_index, "from.", + printer); + + if (have_outer_if) { + // Emit an if() that will let us skip the whole chunk if none are set. + uint32_t chunk_mask = GenChunkMask(chunk, has_bit_indices_); + std::string chunk_mask_str = + StrCat(strings::Hex(chunk_mask, strings::ZERO_PAD_8)); + + // Check (up to) 8 has_bits at a time if we have more than one field in + // this chunk. Due to field layout ordering, we may check + // _has_bits_[last_chunk * 8 / 32] multiple times. + GOOGLE_DCHECK_LE(2, popcnt(chunk_mask)); + GOOGLE_DCHECK_GE(8, popcnt(chunk_mask)); + + if (cached_has_word_index != HasWordIndex(chunk.front())) { + cached_has_word_index = HasWordIndex(chunk.front()); + format("cached_has_bits = from._has_bits_[$1$];\n", + cached_has_word_index); + } + + format("if (cached_has_bits & 0x$1$u) {\n", chunk_mask_str); + format.Indent(); + } + + // Go back and emit merging code for each of the fields we processed. + bool deferred_has_bit_changes = false; + for (const auto field : chunk) { + const FieldGenerator& generator = field_generators_.get(field); + + if (field->is_repeated()) { + generator.GenerateMergingCode(printer); + } else if (field->is_optional() && !HasHasbit(field)) { + // Merge semantics without true field presence: primitive fields are + // merged only if non-zero (numeric) or non-empty (string). + bool have_enclosing_if = + EmitFieldNonDefaultCondition(printer, "from.", field); + generator.GenerateMergingCode(printer); + if (have_enclosing_if) { + format.Outdent(); + format("}\n"); + } + } else if (field->options().weak() || + cached_has_word_index != HasWordIndex(field)) { + // Check hasbit, not using cached bits. + GOOGLE_CHECK(HasHasbit(field)); + format("if (from._internal_has_$1$()) {\n", FieldName(field)); + format.Indent(); + generator.GenerateMergingCode(printer); + format.Outdent(); + format("}\n"); + } else { + // Check hasbit, using cached bits. + GOOGLE_CHECK(HasHasbit(field)); + int has_bit_index = has_bit_indices_[field->index()]; + const std::string mask = StrCat( + strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8)); + format("if (cached_has_bits & 0x$1$u) {\n", mask); + format.Indent(); + + if (have_outer_if && IsPOD(field)) { + // Defer hasbit modification until the end of chunk. + // This can reduce the number of loads/stores by up to 7 per 8 fields. + deferred_has_bit_changes = true; + generator.GenerateCopyConstructorCode(printer); + } else { + generator.GenerateMergingCode(printer); + } + + format.Outdent(); + format("}\n"); + } + } + + if (have_outer_if) { + if (deferred_has_bit_changes) { + // Flush the has bits for the primitives we deferred. + GOOGLE_CHECK_LE(0, cached_has_word_index); + format("_has_bits_[$1$] |= cached_has_bits;\n", cached_has_word_index); + } + + format.Outdent(); + format("}\n"); + } + + if (cold_skipper.OnEndChunk(chunk_index, printer)) { + // Reset here as it may have been updated in just closed if statement. + cached_has_word_index = -1; + } + } + + // Merge oneof fields. Oneof field requires oneof case check. + for (auto oneof : OneOfRange(descriptor_)) { + format("switch (from.$1$_case()) {\n", oneof->name()); + format.Indent(); + for (auto field : FieldRange(oneof)) { + format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true)); + format.Indent(); + if (!IsFieldStripped(field, options_)) { + field_generators_.get(field).GenerateMergingCode(printer); + } + format("break;\n"); + format.Outdent(); + format("}\n"); + } + format( + "case $1$_NOT_SET: {\n" + " break;\n" + "}\n", + ToUpper(oneof->name())); + format.Outdent(); + format("}\n"); + } + if (num_weak_fields_) { + format("_weak_field_map_.MergeFrom(from._weak_field_map_);\n"); + } + + // Merging of extensions and unknown fields is done last, to maximize + // the opportunity for tail calls. + if (descriptor_->extension_range_count() > 0) { + format( + "_extensions_.MergeFrom(internal_default_instance(), " + "from._extensions_);\n"); + } + + format( + "_internal_metadata_.MergeFrom<$unknown_fields_type$>(from._internal_" + "metadata_);\n"); + + format.Outdent(); + format("}\n"); +} + +void MessageGenerator::GenerateCopyFrom(io::Printer* printer) { + if (HasSimpleBaseClass(descriptor_, options_)) return; + Formatter format(printer, variables_); + if (HasDescriptorMethods(descriptor_->file(), options_)) { + // We don't override the generalized CopyFrom (aka that which + // takes in the Message base class as a parameter); instead we just + // let the base Message::CopyFrom take care of it. The base MergeFrom + // knows how to quickly confirm the types exactly match, and if so, will + // use GetClassData() to get the address of Message::CopyWithSizeCheck, + // which calls Clear() and then MergeFrom(), as well as making sure that + // clearing the destination message doesn't alter the size of the source, + // when in debug builds. + // Most callers avoid this by passing a "from" message that is the same + // type as the message being merged into, rather than a generic Message. + } + + // Generate the class-specific CopyFrom. + format( + "void $classname$::CopyFrom(const $classname$& from) {\n" + "// @@protoc_insertion_point(class_specific_copy_from_start:" + "$full_name$)\n"); + format.Indent(); + + format("if (&from == this) return;\n"); + + if (!options_.opensource_runtime) { + // This check is disabled in the opensource release because we're + // concerned that many users do not define NDEBUG in their release builds. + format( + "#ifndef NDEBUG\n" + "size_t from_size = from.ByteSizeLong();\n" + "#endif\n" + "Clear();\n" + "#ifndef NDEBUG\n" + "$CHK$_EQ(from_size, from.ByteSizeLong())\n" + " << \"Source of CopyFrom changed when clearing target. Either \"\n" + " \"source is a nested message in target (not allowed), or \"\n" + " \"another thread is modifying the source.\";\n" + "#endif\n"); + } else { + format("Clear();\n"); + } + format("MergeFrom(from);\n"); + + format.Outdent(); + format("}\n"); +} + +void MessageGenerator::GenerateVerify(io::Printer* printer) { +} + +void MessageGenerator::GenerateSerializeOneofFields( + io::Printer* printer, const std::vector& fields) { + Formatter format(printer, variables_); + GOOGLE_CHECK(!fields.empty()); + if (fields.size() == 1) { + GenerateSerializeOneField(printer, fields[0], -1); + return; + } + // We have multiple mutually exclusive choices. Emit a switch statement. + const OneofDescriptor* oneof = fields[0]->containing_oneof(); + format("switch ($1$_case()) {\n", oneof->name()); + format.Indent(); + for (auto field : fields) { + format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true)); + format.Indent(); + field_generators_.get(field).GenerateSerializeWithCachedSizesToArray( + printer); + format("break;\n"); + format.Outdent(); + format("}\n"); + } + format.Outdent(); + // Doing nothing is an option. + format( + " default: ;\n" + "}\n"); +} + +void MessageGenerator::GenerateSerializeOneField(io::Printer* printer, + const FieldDescriptor* field, + int cached_has_bits_index) { + Formatter format(printer, variables_); + if (!field->options().weak()) { + // For weakfields, PrintFieldComment is called during iteration. + PrintFieldComment(format, field); + } + + bool have_enclosing_if = false; + if (field->options().weak()) { + } else if (HasHasbit(field)) { + // Attempt to use the state of cached_has_bits, if possible. + int has_bit_index = HasBitIndex(field); + if (cached_has_bits_index == has_bit_index / 32) { + const std::string mask = + StrCat(strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8)); + + format("if (cached_has_bits & 0x$1$u) {\n", mask); + } else { + format("if (_internal_has_$1$()) {\n", FieldName(field)); + } + + format.Indent(); + have_enclosing_if = true; + } else if (field->is_optional() && !HasHasbit(field)) { + have_enclosing_if = EmitFieldNonDefaultCondition(printer, "this->", field); + } + + field_generators_.get(field).GenerateSerializeWithCachedSizesToArray(printer); + + if (have_enclosing_if) { + format.Outdent(); + format("}\n"); + } + format("\n"); +} + +void MessageGenerator::GenerateSerializeOneExtensionRange( + io::Printer* printer, const Descriptor::ExtensionRange* range) { + std::map vars = variables_; + vars["start"] = StrCat(range->start); + vars["end"] = StrCat(range->end); + Formatter format(printer, vars); + format("// Extension range [$start$, $end$)\n"); + format( + "target = _extensions_._InternalSerialize(\n" + "internal_default_instance(), $start$, $end$, target, stream);\n\n"); +} + +void MessageGenerator::GenerateSerializeWithCachedSizesToArray( + io::Printer* printer) { + if (HasSimpleBaseClass(descriptor_, options_)) return; + Formatter format(printer, variables_); + if (descriptor_->options().message_set_wire_format()) { + // Special-case MessageSet. + format( + "$uint8$* $classname$::_InternalSerialize(\n" + " $uint8$* target, ::$proto_ns$::io::EpsCopyOutputStream* stream) " + "const {\n" + "$annotate_serialize$" + " target = _extensions_." + "InternalSerializeMessageSetWithCachedSizesToArray(\n" // + "internal_default_instance(), target, stream);\n"); + std::map vars; + SetUnknownFieldsVariable(descriptor_, options_, &vars); + format.AddMap(vars); + format( + " target = ::$proto_ns$::internal::" + "InternalSerializeUnknownMessageSetItemsToArray(\n" + " $unknown_fields$, target, stream);\n"); + format( + " return target;\n" + "}\n"); + return; + } + + format( + "$uint8$* $classname$::_InternalSerialize(\n" + " $uint8$* target, ::$proto_ns$::io::EpsCopyOutputStream* stream) " + "const {\n" + "$annotate_serialize$"); + format.Indent(); + + format("// @@protoc_insertion_point(serialize_to_array_start:$full_name$)\n"); + + if (!ShouldSerializeInOrder(descriptor_, options_)) { + format.Outdent(); + format("#ifdef NDEBUG\n"); + format.Indent(); + } + + GenerateSerializeWithCachedSizesBody(printer); + + if (!ShouldSerializeInOrder(descriptor_, options_)) { + format.Outdent(); + format("#else // NDEBUG\n"); + format.Indent(); + + GenerateSerializeWithCachedSizesBodyShuffled(printer); + + format.Outdent(); + format("#endif // !NDEBUG\n"); + format.Indent(); + } + + format("// @@protoc_insertion_point(serialize_to_array_end:$full_name$)\n"); + + format.Outdent(); + format( + " return target;\n" + "}\n"); +} + +void MessageGenerator::GenerateSerializeWithCachedSizesBody( + io::Printer* printer) { + if (HasSimpleBaseClass(descriptor_, options_)) return; + Formatter format(printer, variables_); + // If there are multiple fields in a row from the same oneof then we + // coalesce them and emit a switch statement. This is more efficient + // because it lets the C++ compiler know this is a "at most one can happen" + // situation. If we emitted "if (has_x()) ...; if (has_y()) ..." the C++ + // compiler's emitted code might check has_y() even when has_x() is true. + class LazySerializerEmitter { + public: + LazySerializerEmitter(MessageGenerator* mg, io::Printer* printer) + : mg_(mg), + format_(printer), + eager_(IsProto3(mg->descriptor_->file())), + cached_has_bit_index_(kNoHasbit) {} + + ~LazySerializerEmitter() { Flush(); } + + // If conditions allow, try to accumulate a run of fields from the same + // oneof, and handle them at the next Flush(). + void Emit(const FieldDescriptor* field) { + if (eager_ || MustFlush(field)) { + Flush(); + } + if (!field->real_containing_oneof()) { + // TODO(ckennelly): Defer non-oneof fields similarly to oneof fields. + + if (!field->options().weak() && !field->is_repeated() && !eager_) { + // We speculatively load the entire _has_bits_[index] contents, even + // if it is for only one field. Deferring non-oneof emitting would + // allow us to determine whether this is going to be useful. + int has_bit_index = mg_->has_bit_indices_[field->index()]; + if (cached_has_bit_index_ != has_bit_index / 32) { + // Reload. + int new_index = has_bit_index / 32; + + format_("cached_has_bits = _has_bits_[$1$];\n", new_index); + + cached_has_bit_index_ = new_index; + } + } + + mg_->GenerateSerializeOneField(format_.printer(), field, + cached_has_bit_index_); + } else { + v_.push_back(field); + } + } + + void EmitIfNotNull(const FieldDescriptor* field) { + if (field != nullptr) { + Emit(field); + } + } + + void Flush() { + if (!v_.empty()) { + mg_->GenerateSerializeOneofFields(format_.printer(), v_); + v_.clear(); + } + } + + private: + // If we have multiple fields in v_ then they all must be from the same + // oneof. Would adding field to v_ break that invariant? + bool MustFlush(const FieldDescriptor* field) { + return !v_.empty() && + v_[0]->containing_oneof() != field->containing_oneof(); + } + + MessageGenerator* mg_; + Formatter format_; + const bool eager_; + std::vector v_; + + // cached_has_bit_index_ maintains that: + // cached_has_bits = from._has_bits_[cached_has_bit_index_] + // for cached_has_bit_index_ >= 0 + int cached_has_bit_index_; + }; + + class LazyExtensionRangeEmitter { + public: + LazyExtensionRangeEmitter(MessageGenerator* mg, io::Printer* printer) + : mg_(mg), format_(printer) {} + + void AddToRange(const Descriptor::ExtensionRange* range) { + if (!has_current_range_) { + current_combined_range_ = *range; + has_current_range_ = true; + } else { + current_combined_range_.start = + std::min(current_combined_range_.start, range->start); + current_combined_range_.end = + std::max(current_combined_range_.end, range->end); + } + } + + void Flush() { + if (has_current_range_) { + mg_->GenerateSerializeOneExtensionRange(format_.printer(), + ¤t_combined_range_); + } + has_current_range_ = false; + } + + private: + MessageGenerator* mg_; + Formatter format_; + bool has_current_range_ = false; + Descriptor::ExtensionRange current_combined_range_; + }; + + // We need to track the largest weak field, because weak fields are serialized + // differently than normal fields. The WeakFieldMap::FieldWriter will + // serialize all weak fields that are ordinally between the last serialized + // weak field and the current field. In order to guarantee that all weak + // fields are serialized, we need to make sure to emit the code to serialize + // the largest weak field present at some point. + class LargestWeakFieldHolder { + public: + const FieldDescriptor* Release() { + const FieldDescriptor* result = field_; + field_ = nullptr; + return result; + } + void ReplaceIfLarger(const FieldDescriptor* field) { + if (field_ == nullptr || field_->number() < field->number()) { + field_ = field; + } + } + + private: + const FieldDescriptor* field_ = nullptr; + }; + + std::vector ordered_fields = + SortFieldsByNumber(descriptor_); + + std::vector sorted_extensions; + sorted_extensions.reserve(descriptor_->extension_range_count()); + for (int i = 0; i < descriptor_->extension_range_count(); ++i) { + sorted_extensions.push_back(descriptor_->extension_range(i)); + } + std::sort(sorted_extensions.begin(), sorted_extensions.end(), + ExtensionRangeSorter()); + if (num_weak_fields_) { + format( + "::$proto_ns$::internal::WeakFieldMap::FieldWriter field_writer(" + "_weak_field_map_);\n"); + } + + format( + "$uint32$ cached_has_bits = 0;\n" + "(void) cached_has_bits;\n\n"); + + // Merge the fields and the extension ranges, both sorted by field number. + { + LazySerializerEmitter e(this, printer); + LazyExtensionRangeEmitter re(this, printer); + LargestWeakFieldHolder largest_weak_field; + int i, j; + for (i = 0, j = 0; + i < ordered_fields.size() || j < sorted_extensions.size();) { + if ((j == sorted_extensions.size()) || + (i < descriptor_->field_count() && + ordered_fields[i]->number() < sorted_extensions[j]->start)) { + const FieldDescriptor* field = ordered_fields[i++]; + if (IsFieldStripped(field, options_)) { + continue; + } + re.Flush(); + if (field->options().weak()) { + largest_weak_field.ReplaceIfLarger(field); + PrintFieldComment(format, field); + } else { + e.EmitIfNotNull(largest_weak_field.Release()); + e.Emit(field); + } + } else { + e.EmitIfNotNull(largest_weak_field.Release()); + e.Flush(); + re.AddToRange(sorted_extensions[j++]); + } + } + re.Flush(); + e.EmitIfNotNull(largest_weak_field.Release()); + } + + std::map vars; + SetUnknownFieldsVariable(descriptor_, options_, &vars); + format.AddMap(vars); + format("if (PROTOBUF_PREDICT_FALSE($have_unknown_fields$)) {\n"); + format.Indent(); + if (UseUnknownFieldSet(descriptor_->file(), options_)) { + format( + "target = " + "::$proto_ns$::internal::WireFormat::" + "InternalSerializeUnknownFieldsToArray(\n" + " $unknown_fields$, target, stream);\n"); + } else { + format( + "target = stream->WriteRaw($unknown_fields$.data(),\n" + " static_cast($unknown_fields$.size()), target);\n"); + } + format.Outdent(); + format("}\n"); +} + +void MessageGenerator::GenerateSerializeWithCachedSizesBodyShuffled( + io::Printer* printer) { + Formatter format(printer, variables_); + + std::vector ordered_fields = + SortFieldsByNumber(descriptor_); + ordered_fields.erase( + std::remove_if(ordered_fields.begin(), ordered_fields.end(), + [this](const FieldDescriptor* f) { + return !IsFieldUsed(f, options_); + }), + ordered_fields.end()); + + std::vector sorted_extensions; + sorted_extensions.reserve(descriptor_->extension_range_count()); + for (int i = 0; i < descriptor_->extension_range_count(); ++i) { + sorted_extensions.push_back(descriptor_->extension_range(i)); + } + std::sort(sorted_extensions.begin(), sorted_extensions.end(), + ExtensionRangeSorter()); + + int num_fields = ordered_fields.size() + sorted_extensions.size(); + constexpr int kLargePrime = 1000003; + GOOGLE_CHECK_LT(num_fields, kLargePrime) + << "Prime offset must be greater than the number of fields to ensure " + "those are coprime."; + + if (num_weak_fields_) { + format( + "::$proto_ns$::internal::WeakFieldMap::FieldWriter field_writer(" + "_weak_field_map_);\n"); + } + + format("for (int i = $1$; i >= 0; i-- ) {\n", num_fields - 1); + + format.Indent(); + format("switch(i) {\n"); + format.Indent(); + + int index = 0; + for (const auto* f : ordered_fields) { + format("case $1$: {\n", index++); + format.Indent(); + + GenerateSerializeOneField(printer, f, -1); + + format("break;\n"); + format.Outdent(); + format("}\n"); + } + + for (const auto* r : sorted_extensions) { + format("case $1$: {\n", index++); + format.Indent(); + + GenerateSerializeOneExtensionRange(printer, r); + + format("break;\n"); + format.Outdent(); + format("}\n"); + } + + format( + "default: {\n" + " $DCHK$(false) << \"Unexpected index: \" << i;\n" + "}\n"); + format.Outdent(); + format("}\n"); + + format.Outdent(); + format("}\n"); + + std::map vars; + SetUnknownFieldsVariable(descriptor_, options_, &vars); + format.AddMap(vars); + format("if (PROTOBUF_PREDICT_FALSE($have_unknown_fields$)) {\n"); + format.Indent(); + if (UseUnknownFieldSet(descriptor_->file(), options_)) { + format( + "target = " + "::$proto_ns$::internal::WireFormat::" + "InternalSerializeUnknownFieldsToArray(\n" + " $unknown_fields$, target, stream);\n"); + } else { + format( + "target = stream->WriteRaw($unknown_fields$.data(),\n" + " static_cast($unknown_fields$.size()), target);\n"); + } + format.Outdent(); + format("}\n"); +} + +std::vector MessageGenerator::RequiredFieldsBitMask() const { + const int array_size = HasBitsSize(); + std::vector masks(array_size, 0); + + for (auto field : FieldRange(descriptor_)) { + if (!field->is_required()) { + continue; + } + + const int has_bit_index = has_bit_indices_[field->index()]; + masks[has_bit_index / 32] |= static_cast(1) + << (has_bit_index % 32); + } + return masks; +} + +void MessageGenerator::GenerateByteSize(io::Printer* printer) { + if (HasSimpleBaseClass(descriptor_, options_)) return; + Formatter format(printer, variables_); + + if (descriptor_->options().message_set_wire_format()) { + // Special-case MessageSet. + std::map vars; + SetUnknownFieldsVariable(descriptor_, options_, &vars); + format.AddMap(vars); + format( + "size_t $classname$::ByteSizeLong() const {\n" + "$annotate_bytesize$" + "// @@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 += ::$proto_ns$::internal::\n" + " ComputeUnknownMessageSetItemsSize($unknown_fields$);\n" + " }\n" + " int cached_size = " + "::$proto_ns$::internal::ToCachedSize(total_size);\n" + " SetCachedSize(cached_size);\n" + " return total_size;\n" + "}\n"); + return; + } + + if (num_required_fields_ > 1) { + // Emit a function (rarely used, we hope) that handles the required fields + // by checking for each one individually. + format( + "size_t $classname$::RequiredFieldsByteSizeFallback() const {\n" + "// @@protoc_insertion_point(required_fields_byte_size_fallback_start:" + "$full_name$)\n"); + format.Indent(); + format("size_t total_size = 0;\n"); + for (auto field : optimized_order_) { + if (field->is_required()) { + format( + "\n" + "if (_internal_has_$1$()) {\n", + FieldName(field)); + format.Indent(); + PrintFieldComment(format, field); + field_generators_.get(field).GenerateByteSize(printer); + format.Outdent(); + format("}\n"); + } + } + format( + "\n" + "return total_size;\n"); + format.Outdent(); + format("}\n"); + } + + format( + "size_t $classname$::ByteSizeLong() const {\n" + "$annotate_bytesize$" + "// @@protoc_insertion_point(message_byte_size_start:$full_name$)\n"); + format.Indent(); + format( + "size_t total_size = 0;\n" + "\n"); + + if (descriptor_->extension_range_count() > 0) { + format( + "total_size += _extensions_.ByteSize();\n" + "\n"); + } + + std::map vars; + SetUnknownFieldsVariable(descriptor_, options_, &vars); + format.AddMap(vars); + + // Handle required fields (if any). We expect all of them to be + // present, so emit one conditional that checks for that. If they are all + // present then the fast path executes; otherwise the slow path executes. + if (num_required_fields_ > 1) { + // The fast path works if all required fields are present. + const std::vector masks_for_has_bits = RequiredFieldsBitMask(); + format("if ($1$) { // All required fields are present.\n", + ConditionalToCheckBitmasks(masks_for_has_bits)); + format.Indent(); + // Oneof fields cannot be required, so optimized_order_ contains all of the + // fields that we need to potentially emit. + for (auto field : optimized_order_) { + if (!field->is_required()) continue; + PrintFieldComment(format, field); + field_generators_.get(field).GenerateByteSize(printer); + format("\n"); + } + format.Outdent(); + format( + "} else {\n" // the slow path + " total_size += RequiredFieldsByteSizeFallback();\n" + "}\n"); + } else { + // num_required_fields_ <= 1: no need to be tricky + for (auto field : optimized_order_) { + if (!field->is_required()) continue; + PrintFieldComment(format, field); + format("if (_internal_has_$1$()) {\n", FieldName(field)); + format.Indent(); + field_generators_.get(field).GenerateByteSize(printer); + format.Outdent(); + format("}\n"); + } + } + + std::vector> chunks = CollectFields( + optimized_order_, + [&](const FieldDescriptor* a, const FieldDescriptor* b) -> bool { + return a->label() == b->label() && HasByteIndex(a) == HasByteIndex(b); + }); + + // Remove chunks with required fields. + chunks.erase(std::remove_if(chunks.begin(), chunks.end(), IsRequired), + chunks.end()); + + ColdChunkSkipper cold_skipper(options_, chunks, has_bit_indices_, kColdRatio); + int cached_has_word_index = -1; + + format( + "$uint32$ cached_has_bits = 0;\n" + "// Prevent compiler warnings about cached_has_bits being unused\n" + "(void) cached_has_bits;\n\n"); + + for (int chunk_index = 0; chunk_index < chunks.size(); chunk_index++) { + const std::vector& chunk = chunks[chunk_index]; + const bool have_outer_if = + chunk.size() > 1 && HasWordIndex(chunk[0]) != kNoHasbit; + cold_skipper.OnStartChunk(chunk_index, cached_has_word_index, "", printer); + + if (have_outer_if) { + // Emit an if() that will let us skip the whole chunk if none are set. + uint32_t chunk_mask = GenChunkMask(chunk, has_bit_indices_); + std::string chunk_mask_str = + StrCat(strings::Hex(chunk_mask, strings::ZERO_PAD_8)); + + // Check (up to) 8 has_bits at a time if we have more than one field in + // this chunk. Due to field layout ordering, we may check + // _has_bits_[last_chunk * 8 / 32] multiple times. + GOOGLE_DCHECK_LE(2, popcnt(chunk_mask)); + GOOGLE_DCHECK_GE(8, popcnt(chunk_mask)); + + if (cached_has_word_index != HasWordIndex(chunk.front())) { + cached_has_word_index = HasWordIndex(chunk.front()); + format("cached_has_bits = _has_bits_[$1$];\n", cached_has_word_index); + } + format("if (cached_has_bits & 0x$1$u) {\n", chunk_mask_str); + format.Indent(); + } + + // Go back and emit checks for each of the fields we processed. + for (int j = 0; j < chunk.size(); j++) { + const FieldDescriptor* field = chunk[j]; + const FieldGenerator& generator = field_generators_.get(field); + bool have_enclosing_if = false; + bool need_extra_newline = false; + + PrintFieldComment(format, field); + + if (field->is_repeated()) { + // No presence check is required. + need_extra_newline = true; + } else if (HasHasbit(field)) { + PrintPresenceCheck(format, field, has_bit_indices_, printer, + &cached_has_word_index); + have_enclosing_if = true; + } else { + // Without field presence: field is serialized only if it has a + // non-default value. + have_enclosing_if = + EmitFieldNonDefaultCondition(printer, "this->", field); + } + + generator.GenerateByteSize(printer); + + if (have_enclosing_if) { + format.Outdent(); + format( + "}\n" + "\n"); + } + if (need_extra_newline) { + format("\n"); + } + } + + if (have_outer_if) { + format.Outdent(); + format("}\n"); + } + + if (cold_skipper.OnEndChunk(chunk_index, printer)) { + // Reset here as it may have been updated in just closed if statement. + cached_has_word_index = -1; + } + } + + // Fields inside a oneof don't use _has_bits_ so we count them in a separate + // pass. + for (auto oneof : OneOfRange(descriptor_)) { + format("switch ($1$_case()) {\n", oneof->name()); + format.Indent(); + for (auto field : FieldRange(oneof)) { + PrintFieldComment(format, field); + format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true)); + format.Indent(); + if (!IsFieldStripped(field, options_)) { + field_generators_.get(field).GenerateByteSize(printer); + } + format("break;\n"); + format.Outdent(); + format("}\n"); + } + format( + "case $1$_NOT_SET: {\n" + " break;\n" + "}\n", + ToUpper(oneof->name())); + format.Outdent(); + format("}\n"); + } + + if (num_weak_fields_) { + // TagSize + MessageSize + format("total_size += _weak_field_map_.ByteSizeLong();\n"); + } + + if (UseUnknownFieldSet(descriptor_->file(), options_)) { + // We go out of our way to put the computation of the uncommon path of + // unknown fields in tail position. This allows for better code generation + // of this function for simple protos. + format( + "return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_);\n"); + } else { + format("if (PROTOBUF_PREDICT_FALSE($have_unknown_fields$)) {\n"); + format(" total_size += $unknown_fields$.size();\n"); + format("}\n"); + + // 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. + format( + "int cached_size = ::$proto_ns$::internal::ToCachedSize(total_size);\n" + "SetCachedSize(cached_size);\n" + "return total_size;\n"); + } + + format.Outdent(); + format("}\n"); +} + +void MessageGenerator::GenerateIsInitialized(io::Printer* printer) { + if (HasSimpleBaseClass(descriptor_, options_)) return; + Formatter format(printer, variables_); + format("bool $classname$::IsInitialized() const {\n"); + format.Indent(); + + if (descriptor_->extension_range_count() > 0) { + format( + "if (!_extensions_.IsInitialized()) {\n" + " return false;\n" + "}\n\n"); + } + + if (num_required_fields_ > 0) { + format( + "if (_Internal::MissingRequiredFields(_has_bits_))" + " return false;\n"); + } + + // Now check that all non-oneof embedded messages are initialized. + for (auto field : optimized_order_) { + field_generators_.get(field).GenerateIsInitialized(printer); + } + if (num_weak_fields_) { + // For Weak fields. + format("if (!_weak_field_map_.IsInitialized()) return false;\n"); + } + // Go through the oneof fields, emitting a switch if any might have required + // fields. + for (auto oneof : OneOfRange(descriptor_)) { + bool has_required_fields = false; + for (auto field : FieldRange(oneof)) { + if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && + !ShouldIgnoreRequiredFieldCheck(field, options_) && + scc_analyzer_->HasRequiredFields(field->message_type())) { + has_required_fields = true; + break; + } + } + + if (!has_required_fields) { + continue; + } + + format("switch ($1$_case()) {\n", oneof->name()); + format.Indent(); + for (auto field : FieldRange(oneof)) { + format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true)); + format.Indent(); + if (!IsFieldStripped(field, options_)) { + field_generators_.get(field).GenerateIsInitialized(printer); + } + format("break;\n"); + format.Outdent(); + format("}\n"); + } + format( + "case $1$_NOT_SET: {\n" + " break;\n" + "}\n", + ToUpper(oneof->name())); + format.Outdent(); + format("}\n"); + } + + format.Outdent(); + format( + " return true;\n" + "}\n"); +} + +} // namespace cpp +} // namespace compiler +} // namespace protobuf +} // namespace google + +#include diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_message_field.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_message_field.h new file mode 100644 index 0000000..2beac62 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_message_field.h @@ -0,0 +1,144 @@ +// 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. + +#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_FIELD_H__ +#define GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_FIELD_H__ + +#include +#include +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace cpp { + +class MessageFieldGenerator : public FieldGenerator { + public: + MessageFieldGenerator(const FieldDescriptor* descriptor, + const Options& options, + MessageSCCAnalyzer* scc_analyzer); + ~MessageFieldGenerator() override; + + // implements FieldGenerator --------------------------------------- + void GeneratePrivateMembers(io::Printer* printer) const override; + void GenerateAccessorDeclarations(io::Printer* printer) const override; + void GenerateInlineAccessorDefinitions(io::Printer* printer) const override; + void GenerateNonInlineAccessorDefinitions( + io::Printer* printer) const override; + void GenerateInternalAccessorDeclarations( + io::Printer* printer) const override; + void GenerateInternalAccessorDefinitions(io::Printer* printer) const override; + void GenerateClearingCode(io::Printer* printer) const override; + void GenerateMessageClearingCode(io::Printer* printer) const override; + void GenerateMergingCode(io::Printer* printer) const override; + void GenerateSwappingCode(io::Printer* printer) const override; + void GenerateDestructorCode(io::Printer* printer) const override; + void GenerateConstructorCode(io::Printer* printer) const override; + void GenerateCopyConstructorCode(io::Printer* printer) const override; + void GenerateSerializeWithCachedSizesToArray( + io::Printer* printer) const override; + void GenerateByteSize(io::Printer* printer) const override; + void GenerateIsInitialized(io::Printer* printer) const override; + void GenerateConstinitInitializer(io::Printer* printer) const override; + + protected: + const bool implicit_weak_field_; + const bool has_required_fields_; + + private: + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFieldGenerator); +}; + +class MessageOneofFieldGenerator : public MessageFieldGenerator { + public: + MessageOneofFieldGenerator(const FieldDescriptor* descriptor, + const Options& options, + MessageSCCAnalyzer* scc_analyzer); + ~MessageOneofFieldGenerator() override; + + // implements FieldGenerator --------------------------------------- + void GenerateInlineAccessorDefinitions(io::Printer* printer) const override; + void GenerateNonInlineAccessorDefinitions( + io::Printer* printer) const override; + void GenerateClearingCode(io::Printer* printer) const override; + + // MessageFieldGenerator, from which we inherit, overrides this so we need to + // override it as well. + void GenerateMessageClearingCode(io::Printer* printer) const override; + void GenerateSwappingCode(io::Printer* printer) const override; + void GenerateDestructorCode(io::Printer* printer) const override; + void GenerateConstructorCode(io::Printer* printer) const override; + void GenerateIsInitialized(io::Printer* printer) const override; + + private: + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageOneofFieldGenerator); +}; + +class RepeatedMessageFieldGenerator : public FieldGenerator { + public: + RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor, + const Options& options, + MessageSCCAnalyzer* scc_analyzer); + ~RepeatedMessageFieldGenerator() override; + + // implements FieldGenerator --------------------------------------- + void GeneratePrivateMembers(io::Printer* printer) const override; + void GenerateAccessorDeclarations(io::Printer* printer) const override; + void GenerateInlineAccessorDefinitions(io::Printer* printer) const override; + void GenerateClearingCode(io::Printer* printer) const override; + void GenerateMergingCode(io::Printer* printer) const override; + void GenerateSwappingCode(io::Printer* printer) const override; + void GenerateConstructorCode(io::Printer* printer) const override; + void GenerateCopyConstructorCode(io::Printer* printer) const override {} + void GenerateSerializeWithCachedSizesToArray( + io::Printer* printer) const override; + void GenerateByteSize(io::Printer* printer) const override; + void GenerateIsInitialized(io::Printer* printer) const override; + void GenerateConstinitInitializer(io::Printer* printer) const override; + + private: + const bool implicit_weak_field_; + const bool has_required_fields_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedMessageFieldGenerator); +}; + +} // namespace cpp +} // namespace compiler +} // namespace protobuf +} // namespace google + +#endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_FIELD_H__ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_names.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_names.h new file mode 100644 index 0000000..6bcbff0 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_names.h @@ -0,0 +1,96 @@ +// 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_COMPILER_CPP_NAMES_H__ +#define GOOGLE_PROTOBUF_COMPILER_CPP_NAMES_H__ + +#include + +#include + +namespace google { +namespace protobuf { + +class Descriptor; +class EnumDescriptor; +class EnumValueDescriptor; +class FieldDescriptor; + +namespace compiler { +namespace cpp { + +// Returns the unqualified C++ name. +// +// For example, if you had: +// package foo.bar; +// message Baz { message Qux {} } +// Then the non-qualified version would be: +// Baz_Qux +std::string ClassName(const Descriptor* descriptor); +std::string ClassName(const EnumDescriptor* enum_descriptor); + +// Returns the fully qualified C++ name. +// +// For example, if you had: +// package foo.bar; +// message Baz { message Qux {} } +// Then the qualified ClassName for Qux would be: +// ::foo::bar::Baz_Qux +std::string QualifiedClassName(const Descriptor* d); +std::string QualifiedClassName(const EnumDescriptor* d); +std::string QualifiedExtensionName(const FieldDescriptor* d); + +// 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 +// anyway, so normally this just returns field->name(). +std::string FieldName(const FieldDescriptor* field); + +// Requires that this field is in a oneof. Returns the (unqualified) case +// constant for this field. +std::string OneofCaseConstantName(const FieldDescriptor* field); +// Returns the quafilied case constant for this field. +std::string QualifiedOneofCaseConstantName(const FieldDescriptor* field); + +// Get the (unqualified) name that should be used for this enum value in C++ +// code. +std::string EnumValueName(const EnumValueDescriptor* enum_value); + +// Strips ".proto" or ".protodevel" from the end of a filename. +PROTOC_EXPORT std::string StripProto(const std::string& filename); + +} // namespace cpp +} // namespace compiler +} // namespace protobuf +} // namespace google + +#include + +#endif // GOOGLE_PROTOBUF_COMPILER_CPP_NAMES_H__ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc new file mode 100644 index 0000000..ffccf08 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc @@ -0,0 +1,505 @@ +// 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. + +#include + +#include +#include +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace cpp { + +using internal::WireFormatLite; + +namespace { + +// For encodings with fixed sizes, returns that size in bytes. Otherwise +// returns -1. +int FixedSize(FieldDescriptor::Type type) { + switch (type) { + case FieldDescriptor::TYPE_INT32: + return -1; + case FieldDescriptor::TYPE_INT64: + return -1; + case FieldDescriptor::TYPE_UINT32: + return -1; + case FieldDescriptor::TYPE_UINT64: + return -1; + case FieldDescriptor::TYPE_SINT32: + return -1; + case FieldDescriptor::TYPE_SINT64: + return -1; + case FieldDescriptor::TYPE_FIXED32: + return WireFormatLite::kFixed32Size; + case FieldDescriptor::TYPE_FIXED64: + return WireFormatLite::kFixed64Size; + case FieldDescriptor::TYPE_SFIXED32: + return WireFormatLite::kSFixed32Size; + case FieldDescriptor::TYPE_SFIXED64: + return WireFormatLite::kSFixed64Size; + case FieldDescriptor::TYPE_FLOAT: + return WireFormatLite::kFloatSize; + case FieldDescriptor::TYPE_DOUBLE: + return WireFormatLite::kDoubleSize; + + case FieldDescriptor::TYPE_BOOL: + return WireFormatLite::kBoolSize; + case FieldDescriptor::TYPE_ENUM: + return -1; + + case FieldDescriptor::TYPE_STRING: + return -1; + case FieldDescriptor::TYPE_BYTES: + return -1; + case FieldDescriptor::TYPE_GROUP: + return -1; + case FieldDescriptor::TYPE_MESSAGE: + return -1; + + // No default because we want the compiler to complain if any new + // types are added. + } + GOOGLE_LOG(FATAL) << "Can't get here."; + return -1; +} + +void SetPrimitiveVariables(const FieldDescriptor* descriptor, + std::map* variables, + const Options& options) { + SetCommonFieldVariables(descriptor, variables, options); + (*variables)["type"] = PrimitiveTypeName(options, descriptor->cpp_type()); + (*variables)["default"] = DefaultValue(options, descriptor); + (*variables)["tag"] = StrCat(internal::WireFormat::MakeTag(descriptor)); + int fixed_size = FixedSize(descriptor->type()); + if (fixed_size != -1) { + (*variables)["fixed_size"] = StrCat(fixed_size); + } + (*variables)["wire_format_field_type"] = FieldDescriptorProto_Type_Name( + static_cast(descriptor->type())); + (*variables)["full_name"] = descriptor->full_name(); +} + +} // namespace + +// =================================================================== + +PrimitiveFieldGenerator::PrimitiveFieldGenerator( + const FieldDescriptor* descriptor, const Options& options) + : FieldGenerator(descriptor, options) { + SetPrimitiveVariables(descriptor, &variables_, options); +} + +PrimitiveFieldGenerator::~PrimitiveFieldGenerator() {} + +void PrimitiveFieldGenerator::GeneratePrivateMembers( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$type$ $name$_;\n"); +} + +void PrimitiveFieldGenerator::GenerateAccessorDeclarations( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "$deprecated_attr$$type$ ${1$$name$$}$() const;\n" + "$deprecated_attr$void ${1$set_$name$$}$($type$ value);\n" + "private:\n" + "$type$ ${1$_internal_$name$$}$() const;\n" + "void ${1$_internal_set_$name$$}$($type$ value);\n" + "public:\n", + descriptor_); +} + +void PrimitiveFieldGenerator::GenerateInlineAccessorDefinitions( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "inline $type$ $classname$::_internal_$name$() const {\n" + " return $name$_;\n" + "}\n" + "inline $type$ $classname$::$name$() const {\n" + "$annotate_get$" + " // @@protoc_insertion_point(field_get:$full_name$)\n" + " return _internal_$name$();\n" + "}\n" + "inline void $classname$::_internal_set_$name$($type$ value) {\n" + " $set_hasbit$\n" + " $name$_ = value;\n" + "}\n" + "inline void $classname$::set_$name$($type$ value) {\n" + " _internal_set_$name$(value);\n" + "$annotate_set$" + " // @@protoc_insertion_point(field_set:$full_name$)\n" + "}\n"); +} + +void PrimitiveFieldGenerator::GenerateClearingCode(io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_ = $default$;\n"); +} + +void PrimitiveFieldGenerator::GenerateMergingCode(io::Printer* printer) const { + Formatter format(printer, variables_); + format("_internal_set_$name$(from._internal_$name$());\n"); +} + +void PrimitiveFieldGenerator::GenerateSwappingCode(io::Printer* printer) const { + Formatter format(printer, variables_); + format("swap($name$_, other->$name$_);\n"); +} + +void PrimitiveFieldGenerator::GenerateConstructorCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_ = $default$;\n"); +} + +void PrimitiveFieldGenerator::GenerateCopyConstructorCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_ = from.$name$_;\n"); +} + +void PrimitiveFieldGenerator::GenerateSerializeWithCachedSizesToArray( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "target = stream->EnsureSpace(target);\n" + "target = " + "::$proto_ns$::internal::WireFormatLite::Write$declared_type$ToArray(" + "$number$, this->_internal_$name$(), target);\n"); +} + +void PrimitiveFieldGenerator::GenerateByteSize(io::Printer* printer) const { + Formatter format(printer, variables_); + int fixed_size = FixedSize(descriptor_->type()); + if (fixed_size == -1) { + if (internal::WireFormat::TagSize(descriptor_->number(), + descriptor_->type()) == 1) { + // Adding one is very common and it turns out it can be done for + // free inside of WireFormatLite, so we can save an instruction here. + format( + "total_size += ::$proto_ns$::internal::WireFormatLite::" + "$declared_type$SizePlusOne(this->_internal_$name$());\n"); + } else { + format( + "total_size += $tag_size$ +\n" + " ::$proto_ns$::internal::WireFormatLite::$declared_type$Size(\n" + " this->_internal_$name$());\n"); + } + } else { + format("total_size += $tag_size$ + $fixed_size$;\n"); + } +} + +void PrimitiveFieldGenerator::GenerateConstinitInitializer( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_($default$)"); +} + +// =================================================================== + +PrimitiveOneofFieldGenerator::PrimitiveOneofFieldGenerator( + const FieldDescriptor* descriptor, const Options& options) + : PrimitiveFieldGenerator(descriptor, options) { + SetCommonOneofFieldVariables(descriptor, &variables_); +} + +PrimitiveOneofFieldGenerator::~PrimitiveOneofFieldGenerator() {} + +void PrimitiveOneofFieldGenerator::GenerateInlineAccessorDefinitions( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "inline $type$ $classname$::_internal_$name$() const {\n" + " if (_internal_has_$name$()) {\n" + " return $field_member$;\n" + " }\n" + " return $default$;\n" + "}\n" + "inline void $classname$::_internal_set_$name$($type$ value) {\n" + " if (!_internal_has_$name$()) {\n" + " clear_$oneof_name$();\n" + " set_has_$name$();\n" + " }\n" + " $field_member$ = value;\n" + "}\n" + "inline $type$ $classname$::$name$() const {\n" + "$annotate_get$" + " // @@protoc_insertion_point(field_get:$full_name$)\n" + " return _internal_$name$();\n" + "}\n" + "inline void $classname$::set_$name$($type$ value) {\n" + " _internal_set_$name$(value);\n" + "$annotate_set$" + " // @@protoc_insertion_point(field_set:$full_name$)\n" + "}\n"); +} + +void PrimitiveOneofFieldGenerator::GenerateClearingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$field_member$ = $default$;\n"); +} + +void PrimitiveOneofFieldGenerator::GenerateSwappingCode( + io::Printer* printer) const { + // Don't print any swapping code. Swapping the union will swap this field. +} + +void PrimitiveOneofFieldGenerator::GenerateConstructorCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$ns$::_$classname$_default_instance_.$name$_ = $default$;\n"); +} + +// =================================================================== + +RepeatedPrimitiveFieldGenerator::RepeatedPrimitiveFieldGenerator( + const FieldDescriptor* descriptor, const Options& options) + : FieldGenerator(descriptor, options) { + SetPrimitiveVariables(descriptor, &variables_, options); + + if (descriptor->is_packed()) { + variables_["packed_reader"] = "ReadPackedPrimitive"; + variables_["repeated_reader"] = "ReadRepeatedPrimitiveNoInline"; + } else { + variables_["packed_reader"] = "ReadPackedPrimitiveNoInline"; + variables_["repeated_reader"] = "ReadRepeatedPrimitive"; + } +} + +RepeatedPrimitiveFieldGenerator::~RepeatedPrimitiveFieldGenerator() {} + +void RepeatedPrimitiveFieldGenerator::GeneratePrivateMembers( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("::$proto_ns$::RepeatedField< $type$ > $name$_;\n"); + if (descriptor_->is_packed() && FixedSize(descriptor_->type()) == -1 && + HasGeneratedMethods(descriptor_->file(), options_)) { + format("mutable std::atomic _$name$_cached_byte_size_;\n"); + } +} + +void RepeatedPrimitiveFieldGenerator::GenerateAccessorDeclarations( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "private:\n" + "$type$ ${1$_internal_$name$$}$(int index) const;\n" + "const ::$proto_ns$::RepeatedField< $type$ >&\n" + " ${1$_internal_$name$$}$() const;\n" + "void ${1$_internal_add_$name$$}$($type$ value);\n" + "::$proto_ns$::RepeatedField< $type$ >*\n" + " ${1$_internal_mutable_$name$$}$();\n" + "public:\n" + "$deprecated_attr$$type$ ${1$$name$$}$(int index) const;\n" + "$deprecated_attr$void ${1$set_$name$$}$(int index, $type$ value);\n" + "$deprecated_attr$void ${1$add_$name$$}$($type$ value);\n" + "$deprecated_attr$const ::$proto_ns$::RepeatedField< $type$ >&\n" + " ${1$$name$$}$() const;\n" + "$deprecated_attr$::$proto_ns$::RepeatedField< $type$ >*\n" + " ${1$mutable_$name$$}$();\n", + descriptor_); +} + +void RepeatedPrimitiveFieldGenerator::GenerateInlineAccessorDefinitions( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "inline $type$ $classname$::_internal_$name$(int index) const {\n" + " return $name$_.Get(index);\n" + "}\n" + "inline $type$ $classname$::$name$(int index) const {\n" + "$annotate_get$" + " // @@protoc_insertion_point(field_get:$full_name$)\n" + " return _internal_$name$(index);\n" + "}\n" + "inline void $classname$::set_$name$(int index, $type$ value) {\n" + "$annotate_set$" + " $name$_.Set(index, value);\n" + " // @@protoc_insertion_point(field_set:$full_name$)\n" + "}\n" + "inline void $classname$::_internal_add_$name$($type$ value) {\n" + " $name$_.Add(value);\n" + "}\n" + "inline void $classname$::add_$name$($type$ value) {\n" + " _internal_add_$name$(value);\n" + "$annotate_add$" + " // @@protoc_insertion_point(field_add:$full_name$)\n" + "}\n" + "inline const ::$proto_ns$::RepeatedField< $type$ >&\n" + "$classname$::_internal_$name$() const {\n" + " return $name$_;\n" + "}\n" + "inline const ::$proto_ns$::RepeatedField< $type$ >&\n" + "$classname$::$name$() const {\n" + "$annotate_list$" + " // @@protoc_insertion_point(field_list:$full_name$)\n" + " return _internal_$name$();\n" + "}\n" + "inline ::$proto_ns$::RepeatedField< $type$ >*\n" + "$classname$::_internal_mutable_$name$() {\n" + " return &$name$_;\n" + "}\n" + "inline ::$proto_ns$::RepeatedField< $type$ >*\n" + "$classname$::mutable_$name$() {\n" + "$annotate_mutable_list$" + " // @@protoc_insertion_point(field_mutable_list:$full_name$)\n" + " return _internal_mutable_$name$();\n" + "}\n"); +} + +void RepeatedPrimitiveFieldGenerator::GenerateClearingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_.Clear();\n"); +} + +void RepeatedPrimitiveFieldGenerator::GenerateMergingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_.MergeFrom(from.$name$_);\n"); +} + +void RepeatedPrimitiveFieldGenerator::GenerateSwappingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_.InternalSwap(&other->$name$_);\n"); +} + +void RepeatedPrimitiveFieldGenerator::GenerateConstructorCode( + io::Printer* printer) const { + // Not needed for repeated fields. +} + +void RepeatedPrimitiveFieldGenerator::GenerateCopyConstructorCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_.CopyFrom(from.$name$_);\n"); +} + +void RepeatedPrimitiveFieldGenerator::GenerateSerializeWithCachedSizesToArray( + io::Printer* printer) const { + Formatter format(printer, variables_); + if (descriptor_->is_packed()) { + if (FixedSize(descriptor_->type()) == -1) { + format( + "{\n" + " int byte_size = " + "_$name$_cached_byte_size_.load(std::memory_order_relaxed);\n" + " if (byte_size > 0) {\n" + " target = stream->Write$declared_type$Packed(\n" + " $number$, _internal_$name$(), byte_size, target);\n" + " }\n" + "}\n"); + } else { + format( + "if (this->_internal_$name$_size() > 0) {\n" + " target = stream->WriteFixedPacked($number$, _internal_$name$(), " + "target);\n" + "}\n"); + } + } else { + format( + "for (int i = 0, n = this->_internal_$name$_size(); i < n; i++) {\n" + " target = stream->EnsureSpace(target);\n" + " target = ::$proto_ns$::internal::WireFormatLite::" + "Write$declared_type$ToArray($number$, this->_internal_$name$(i), " + "target);\n" + "}\n"); + } +} + +void RepeatedPrimitiveFieldGenerator::GenerateByteSize( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("{\n"); + format.Indent(); + int fixed_size = FixedSize(descriptor_->type()); + if (fixed_size == -1) { + format( + "size_t data_size = ::$proto_ns$::internal::WireFormatLite::\n" + " $declared_type$Size(this->$name$_);\n"); + } else { + format( + "unsigned int count = static_cast(this->_internal_$name$_size());\n" + "size_t data_size = $fixed_size$UL * count;\n"); + } + + if (descriptor_->is_packed()) { + format( + "if (data_size > 0) {\n" + " total_size += $tag_size$ +\n" + " ::$proto_ns$::internal::WireFormatLite::Int32Size(\n" + " static_cast<$int32$>(data_size));\n" + "}\n"); + if (FixedSize(descriptor_->type()) == -1) { + format( + "int cached_size = ::$proto_ns$::internal::ToCachedSize(data_size);\n" + "_$name$_cached_byte_size_.store(cached_size,\n" + " std::memory_order_relaxed);\n"); + } + format("total_size += data_size;\n"); + } else { + format( + "total_size += $tag_size$ *\n" + " " + "::$proto_ns$::internal::FromIntSize(this->_internal_$name$_size());\n" + "total_size += data_size;\n"); + } + format.Outdent(); + format("}\n"); +} + +void RepeatedPrimitiveFieldGenerator::GenerateConstinitInitializer( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_()"); + if (descriptor_->is_packed() && FixedSize(descriptor_->type()) == -1 && + HasGeneratedMethods(descriptor_->file(), options_)) { + format("\n, _$name$_cached_byte_size_(0)"); + } +} + +} // namespace cpp +} // namespace compiler +} // namespace protobuf +} // namespace google diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_string_field.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_string_field.cc new file mode 100644 index 0000000..607e815 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_string_field.cc @@ -0,0 +1,915 @@ +// 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. + +#include +#include +#include +#include +#include + + +namespace google { +namespace protobuf { +namespace compiler { +namespace cpp { + +namespace { + +void SetStringVariables(const FieldDescriptor* descriptor, + std::map* variables, + const Options& options) { + SetCommonFieldVariables(descriptor, variables, options); + (*variables)["default"] = DefaultValue(options, descriptor); + (*variables)["default_length"] = + StrCat(descriptor->default_value_string().length()); + std::string default_variable_string = MakeDefaultName(descriptor); + (*variables)["default_variable_name"] = default_variable_string; + + if (!descriptor->default_value_string().empty()) { + (*variables)["lazy_variable"] = + QualifiedClassName(descriptor->containing_type(), options) + + "::" + default_variable_string; + } + + (*variables)["default_string"] = + descriptor->default_value_string().empty() + ? "::" + (*variables)["proto_ns"] + + "::internal::GetEmptyStringAlreadyInited()" + : (*variables)["lazy_variable"] + ".get()"; + (*variables)["init_value"] = + descriptor->default_value_string().empty() + ? "&::" + (*variables)["proto_ns"] + + "::internal::GetEmptyStringAlreadyInited()" + : "nullptr"; + (*variables)["default_value_tag"] = + "::" + (*variables)["proto_ns"] + "::internal::ArenaStringPtr::" + + (descriptor->default_value_string().empty() ? "Empty" : "NonEmpty") + + "Default{}"; + (*variables)["default_variable_or_tag"] = + (*variables)[descriptor->default_value_string().empty() + ? "default_value_tag" + : "lazy_variable"]; + (*variables)["pointer_type"] = + descriptor->type() == FieldDescriptor::TYPE_BYTES ? "void" : "char"; + (*variables)["setter"] = + descriptor->type() == FieldDescriptor::TYPE_BYTES ? "SetBytes" : "Set"; + (*variables)["null_check"] = (*variables)["DCHK"] + "(value != nullptr);\n"; + // NOTE: Escaped here to unblock proto1->proto2 migration. + // TODO(liujisi): Extend this to apply for other conflicting methods. + (*variables)["release_name"] = + SafeFunctionName(descriptor->containing_type(), descriptor, "release_"); + (*variables)["full_name"] = descriptor->full_name(); + + if (options.opensource_runtime) { + (*variables)["string_piece"] = "::std::string"; + } else { + (*variables)["string_piece"] = "::StringPiece"; + } +} + +} // namespace + +// =================================================================== + +StringFieldGenerator::StringFieldGenerator(const FieldDescriptor* descriptor, + const Options& options) + : FieldGenerator(descriptor, options), + inlined_(IsStringInlined(descriptor, options)) { + SetStringVariables(descriptor, &variables_, options); +} + +StringFieldGenerator::~StringFieldGenerator() {} + +void StringFieldGenerator::GeneratePrivateMembers(io::Printer* printer) const { + Formatter format(printer, variables_); + if (!inlined_) { + format("::$proto_ns$::internal::ArenaStringPtr $name$_;\n"); + } else { + // `_init_inline_xxx` is used for initializing default instances. + format( + "::$proto_ns$::internal::InlinedStringField $name$_;\n" + "static std::true_type _init_inline_$name$_;\n"); + } +} + +void StringFieldGenerator::GenerateStaticMembers(io::Printer* printer) const { + Formatter format(printer, variables_); + if (!descriptor_->default_value_string().empty()) { + format( + "static const ::$proto_ns$::internal::LazyString" + " $default_variable_name$;\n"); + } +} + +void StringFieldGenerator::GenerateAccessorDeclarations( + io::Printer* printer) const { + Formatter format(printer, variables_); + // If we're using StringFieldGenerator for a field with a ctype, it's + // because that ctype isn't actually implemented. In particular, this is + // true of ctype=CORD and ctype=STRING_PIECE in the open source release. + // We aren't releasing Cord because it has too many Google-specific + // dependencies and we aren't releasing StringPiece because it's hardly + // useful outside of Google and because it would get confusing to have + // multiple instances of the StringPiece class in different libraries (PCRE + // already includes it for their C++ bindings, which came from Google). + // + // In any case, we make all the accessors private while still actually + // using a string to represent the field internally. This way, we can + // guarantee that if we do ever implement the ctype, it won't break any + // existing users who might be -- for whatever reason -- already using .proto + // files that applied the ctype. The field can still be accessed via the + // reflection interface since the reflection interface is independent of + // the string's underlying representation. + + bool unknown_ctype = descriptor_->options().ctype() != + EffectiveStringCType(descriptor_, options_); + + if (unknown_ctype) { + format.Outdent(); + format( + " private:\n" + " // Hidden due to unknown ctype option.\n"); + format.Indent(); + } + + format( + "$deprecated_attr$const std::string& ${1$$name$$}$() const;\n" + "template \n" + "$deprecated_attr$void ${1$set_$name$$}$(ArgT0&& arg0, ArgT... args);\n", + descriptor_); + format( + "$deprecated_attr$std::string* ${1$mutable_$name$$}$();\n" + "PROTOBUF_NODISCARD $deprecated_attr$std::string* " + "${1$$release_name$$}$();\n" + "$deprecated_attr$void ${1$set_allocated_$name$$}$(std::string* " + "$name$);\n", + descriptor_); + format( + "private:\n" + "const std::string& _internal_$name$() const;\n" + "inline PROTOBUF_ALWAYS_INLINE void " + "_internal_set_$name$(const std::string& value);\n" + "std::string* _internal_mutable_$name$();\n"); + if (inlined_) { + format( + "inline PROTOBUF_ALWAYS_INLINE bool _internal_$name$_donated() " + "const;\n"); + } + format("public:\n"); + + if (unknown_ctype) { + format.Outdent(); + format(" public:\n"); + format.Indent(); + } +} + +void StringFieldGenerator::GenerateInlineAccessorDefinitions( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "inline const std::string& $classname$::$name$() const {\n" + "$annotate_get$" + " // @@protoc_insertion_point(field_get:$full_name$)\n"); + if (!descriptor_->default_value_string().empty()) { + format( + " if ($name$_.IsDefault(nullptr)) return " + "$default_variable_name$.get();\n"); + } + format( + " return _internal_$name$();\n" + "}\n"); + if (!inlined_) { + format( + "template \n" + "inline PROTOBUF_ALWAYS_INLINE\n" + "void $classname$::set_$name$(ArgT0&& arg0, ArgT... args) {\n" + " $set_hasbit$\n" + " $name$_.$setter$($default_value_tag$, static_cast(arg0)," + " args..., GetArenaForAllocation());\n" + "$annotate_set$" + " // @@protoc_insertion_point(field_set:$full_name$)\n" + "}\n"); + } else { + format( + "template \n" + "inline PROTOBUF_ALWAYS_INLINE\n" + "void $classname$::set_$name$(ArgT0&& arg0, ArgT... args) {\n" + " $set_hasbit$\n" + " $name$_.$setter$(nullptr, static_cast(arg0)," + " args..., GetArenaForAllocation(), _internal_$name$_donated(), " + "&$donating_states_word$, $mask_for_undonate$);\n" + "$annotate_set$" + " // @@protoc_insertion_point(field_set:$full_name$)\n" + "}\n" + "inline bool $classname$::_internal_$name$_donated() const {\n" + " bool value = $inlined_string_donated$\n" + " return value;\n" + "}\n"); + } + format( + "inline std::string* $classname$::mutable_$name$() {\n" + " std::string* _s = _internal_mutable_$name$();\n" + "$annotate_mutable$" + " // @@protoc_insertion_point(field_mutable:$full_name$)\n" + " return _s;\n" + "}\n" + "inline const std::string& $classname$::_internal_$name$() const {\n" + " return $name$_.Get();\n" + "}\n" + "inline void $classname$::_internal_set_$name$(const std::string& " + "value) {\n" + " $set_hasbit$\n"); + if (!inlined_) { + format( + " $name$_.Set($default_value_tag$, value, GetArenaForAllocation());\n" + "}\n"); + } else { + format( + " $name$_.Set(nullptr, value, GetArenaForAllocation(),\n" + " _internal_$name$_donated(), &$donating_states_word$, " + "$mask_for_undonate$);\n" + "}\n"); + } + format( + "inline std::string* $classname$::_internal_mutable_$name$() {\n" + " $set_hasbit$\n"); + if (!inlined_) { + format( + " return $name$_.Mutable($default_variable_or_tag$, " + "GetArenaForAllocation());\n" + "}\n"); + } else { + format( + " return $name$_.Mutable($default_variable_or_tag$, " + "GetArenaForAllocation(), _internal_$name$_donated(), " + "&$donating_states_word$, $mask_for_undonate$);\n" + "}\n"); + } + format( + "inline std::string* $classname$::$release_name$() {\n" + "$annotate_release$" + " // @@protoc_insertion_point(field_release:$full_name$)\n"); + + if (HasHasbit(descriptor_)) { + format( + " if (!_internal_has_$name$()) {\n" + " return nullptr;\n" + " }\n" + " $clear_hasbit$\n"); + if (!inlined_) { + format( + " auto* p = $name$_.ReleaseNonDefault($init_value$, " + "GetArenaForAllocation());\n"); + if (descriptor_->default_value_string().empty()) { + format( + "#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING\n" + " if ($name$_.IsDefault($init_value$)) {\n" + " $name$_.Set($init_value$, \"\", GetArenaForAllocation());\n" + " }\n" + "#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING\n"); + } + format(" return p;\n"); + } else { + format( + " return $name$_.Release(nullptr, GetArenaForAllocation(), " + "_internal_$name$_donated());\n"); + } + } else { + format( + " return $name$_.Release($init_value$, GetArenaForAllocation());\n"); + } + + format( + "}\n" + "inline void $classname$::set_allocated_$name$(std::string* $name$) {\n" + " if ($name$ != nullptr) {\n" + " $set_hasbit$\n" + " } else {\n" + " $clear_hasbit$\n" + " }\n"); + if (!inlined_) { + format( + " $name$_.SetAllocated($init_value$, $name$,\n" + " GetArenaForAllocation());\n"); + if (descriptor_->default_value_string().empty()) { + format( + "#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING\n" + " if ($name$_.IsDefault($init_value$)) {\n" + " $name$_.Set($init_value$, \"\", GetArenaForAllocation());\n" + " }\n" + "#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING\n"); + } + } else { + // Currently, string fields with default value can't be inlined. + format( + " $name$_.SetAllocated(nullptr, $name$, GetArenaForAllocation(), " + "_internal_$name$_donated(), &$donating_states_word$, " + "$mask_for_undonate$);\n"); + } + format( + "$annotate_set$" + " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n" + "}\n"); +} + +void StringFieldGenerator::GenerateNonInlineAccessorDefinitions( + io::Printer* printer) const { + Formatter format(printer, variables_); + if (!descriptor_->default_value_string().empty()) { + format( + "const ::$proto_ns$::internal::LazyString " + "$classname$::$default_variable_name$" + "{{{$default$, $default_length$}}, {nullptr}};\n"); + } +} + +void StringFieldGenerator::GenerateClearingCode(io::Printer* printer) const { + Formatter format(printer, variables_); + if (descriptor_->default_value_string().empty()) { + format("$name$_.ClearToEmpty();\n"); + } else { + GOOGLE_DCHECK(!inlined_); + format( + "$name$_.ClearToDefault($lazy_variable$, GetArenaForAllocation());\n"); + } +} + +void StringFieldGenerator::GenerateMessageClearingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + // Two-dimension specialization here: supporting arenas, field presence, or + // not, and default value is the empty string or not. Complexity here ensures + // the minimal number of branches / amount of extraneous code at runtime + // (given that the below methods are inlined one-liners)! + + // If we have a hasbit, then the Clear() method of the protocol buffer + // will have checked that this field is set. If so, we can avoid redundant + // checks against the default variable. + const bool must_be_present = HasHasbit(descriptor_); + + 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. + format("$DCHK$(!$name$_.IsDefault(nullptr));\n"); + } + + if (descriptor_->default_value_string().empty()) { + if (must_be_present) { + format("$name$_.ClearNonDefaultToEmpty();\n"); + } else { + format("$name$_.ClearToEmpty();\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. + format( + "$name$_.ClearToDefault($lazy_variable$, GetArenaForAllocation());\n "); + } +} + +void StringFieldGenerator::GenerateMergingCode(io::Printer* printer) const { + Formatter format(printer, variables_); + // TODO(gpike): improve this + format("_internal_set_$name$(from._internal_$name$());\n"); +} + +void StringFieldGenerator::GenerateSwappingCode(io::Printer* printer) const { + Formatter format(printer, variables_); + if (!inlined_) { + format( + "::$proto_ns$::internal::ArenaStringPtr::InternalSwap(\n" + " $init_value$,\n" + " &$name$_, lhs_arena,\n" + " &other->$name$_, rhs_arena\n" + ");\n"); + } else { + // At this point, it's guaranteed that the two fields being swapped are on + // the same arena. + format( + "$name$_.Swap(&other->$name$_, nullptr, GetArenaForAllocation(), " + "_internal_$name$_donated(), other->_internal_$name$_donated(), " + "&$donating_states_word$, &(other->$donating_states_word$), " + "$mask_for_undonate$);\n"); + } +} + +void StringFieldGenerator::GenerateConstructorCode(io::Printer* printer) const { + Formatter format(printer, variables_); + if (inlined_ && descriptor_->default_value_string().empty()) { + // Automatic initialization will construct the string. + return; + } + GOOGLE_DCHECK(!inlined_); + format("$name$_.UnsafeSetDefault($init_value$);\n"); + if (IsString(descriptor_, options_) && + descriptor_->default_value_string().empty()) { + format( + "#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING\n" + " $name$_.Set($init_value$, \"\", GetArenaForAllocation());\n" + "#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING\n"); + } +} + +void StringFieldGenerator::GenerateCopyConstructorCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + GenerateConstructorCode(printer); + + if (HasHasbit(descriptor_)) { + format("if (from._internal_has_$name$()) {\n"); + } else { + format("if (!from._internal_$name$().empty()) {\n"); + } + + format.Indent(); + + if (!inlined_) { + format( + "$name$_.Set($default_value_tag$, from._internal_$name$(), \n" + " GetArenaForAllocation());\n"); + } else { + format( + "$name$_.Set(nullptr, from._internal_$name$(),\n" + " GetArenaForAllocation(), _internal_$name$_donated(), " + "&$donating_states_word$, $mask_for_undonate$);\n"); + } + + format.Outdent(); + format("}\n"); +} + +void StringFieldGenerator::GenerateDestructorCode(io::Printer* printer) const { + Formatter format(printer, variables_); + if (inlined_) { + // The destructor is automatically invoked. + return; + } + + format("$name$_.DestroyNoArena($init_value$);\n"); +} + +void StringFieldGenerator::GenerateSerializeWithCachedSizesToArray( + io::Printer* printer) const { + Formatter format(printer, variables_); + if (descriptor_->type() == FieldDescriptor::TYPE_STRING) { + GenerateUtf8CheckCodeForString( + descriptor_, options_, false, + "this->_internal_$name$().data(), " + "static_cast(this->_internal_$name$().length()),\n", + format); + } + format( + "target = stream->Write$declared_type$MaybeAliased(\n" + " $number$, this->_internal_$name$(), target);\n"); +} + +void StringFieldGenerator::GenerateByteSize(io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "total_size += $tag_size$ +\n" + " ::$proto_ns$::internal::WireFormatLite::$declared_type$Size(\n" + " this->_internal_$name$());\n"); +} + +void StringFieldGenerator::GenerateConstinitInitializer( + io::Printer* printer) const { + Formatter format(printer, variables_); + if (inlined_) { + format("$name$_(nullptr, false)"); + return; + } + if (descriptor_->default_value_string().empty()) { + format("$name$_(&::$proto_ns$::internal::fixed_address_empty_string)"); + } else { + format("$name$_(nullptr)"); + } +} + +// =================================================================== + +StringOneofFieldGenerator::StringOneofFieldGenerator( + const FieldDescriptor* descriptor, const Options& options) + : StringFieldGenerator(descriptor, options) { + SetCommonOneofFieldVariables(descriptor, &variables_); + variables_["field_name"] = UnderscoresToCamelCase(descriptor->name(), true); + variables_["oneof_index"] = + StrCat(descriptor->containing_oneof()->index()); +} + +StringOneofFieldGenerator::~StringOneofFieldGenerator() {} + +void StringOneofFieldGenerator::GenerateInlineAccessorDefinitions( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "inline const std::string& $classname$::$name$() const {\n" + "$annotate_get$" + " // @@protoc_insertion_point(field_get:$full_name$)\n" + " return _internal_$name$();\n" + "}\n" + "template \n" + "inline void $classname$::set_$name$(ArgT0&& arg0, ArgT... args) {\n" + " if (!_internal_has_$name$()) {\n" + " clear_$oneof_name$();\n" + " set_has_$name$();\n" + " $field_member$.UnsafeSetDefault($init_value$);\n" + " }\n" + " $field_member$.$setter$($default_value_tag$," + " static_cast(arg0), args..., GetArenaForAllocation());\n" + "$annotate_set$" + " // @@protoc_insertion_point(field_set:$full_name$)\n" + "}\n" + "inline std::string* $classname$::mutable_$name$() {\n" + " std::string* _s = _internal_mutable_$name$();\n" + "$annotate_mutable$" + " // @@protoc_insertion_point(field_mutable:$full_name$)\n" + " return _s;\n" + "}\n" + "inline const std::string& $classname$::_internal_$name$() const {\n" + " if (_internal_has_$name$()) {\n" + " return $field_member$.Get();\n" + " }\n" + " return $default_string$;\n" + "}\n" + "inline void $classname$::_internal_set_$name$(const std::string& " + "value) {\n" + " if (!_internal_has_$name$()) {\n" + " clear_$oneof_name$();\n" + " set_has_$name$();\n" + " $field_member$.UnsafeSetDefault($init_value$);\n" + " }\n" + " $field_member$.Set($default_value_tag$, value, " + "GetArenaForAllocation());\n" + "}\n"); + format( + "inline std::string* $classname$::_internal_mutable_$name$() {\n" + " if (!_internal_has_$name$()) {\n" + " clear_$oneof_name$();\n" + " set_has_$name$();\n" + " $field_member$.UnsafeSetDefault($init_value$);\n" + " }\n" + " return $field_member$.Mutable(\n" + " $default_variable_or_tag$, GetArenaForAllocation());\n" + "}\n" + "inline std::string* $classname$::$release_name$() {\n" + "$annotate_release$" + " // @@protoc_insertion_point(field_release:$full_name$)\n" + " if (_internal_has_$name$()) {\n" + " clear_has_$oneof_name$();\n" + " return $field_member$.ReleaseNonDefault($init_value$, " + "GetArenaForAllocation());\n" + " } else {\n" + " return nullptr;\n" + " }\n" + "}\n" + "inline void $classname$::set_allocated_$name$(std::string* $name$) {\n" + " if (has_$oneof_name$()) {\n" + " clear_$oneof_name$();\n" + " }\n" + " if ($name$ != nullptr) {\n" + " set_has_$name$();\n" + " $field_member$.UnsafeSetDefault($name$);\n" + " ::$proto_ns$::Arena* arena = GetArenaForAllocation();\n" + " if (arena != nullptr) {\n" + " arena->Own($name$);\n" + " }\n" + " }\n" + "$annotate_set$" + " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n" + "}\n"); +} + +void StringOneofFieldGenerator::GenerateClearingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "$field_member$.Destroy($default_value_tag$, " + "GetArenaForAllocation());\n"); +} + +void StringOneofFieldGenerator::GenerateMessageClearingCode( + io::Printer* printer) const { + return GenerateClearingCode(printer); +} + +void StringOneofFieldGenerator::GenerateSwappingCode( + io::Printer* printer) const { + // Don't print any swapping code. Swapping the union will swap this field. +} + +void StringOneofFieldGenerator::GenerateConstructorCode( + io::Printer* printer) const { + // Nothing required here. +} + +// =================================================================== + +RepeatedStringFieldGenerator::RepeatedStringFieldGenerator( + const FieldDescriptor* descriptor, const Options& options) + : FieldGenerator(descriptor, options) { + SetStringVariables(descriptor, &variables_, options); +} + +RepeatedStringFieldGenerator::~RepeatedStringFieldGenerator() {} + +void RepeatedStringFieldGenerator::GeneratePrivateMembers( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("::$proto_ns$::RepeatedPtrField $name$_;\n"); +} + +void RepeatedStringFieldGenerator::GenerateAccessorDeclarations( + io::Printer* printer) const { + Formatter format(printer, variables_); + // See comment above about unknown ctypes. + bool unknown_ctype = descriptor_->options().ctype() != + EffectiveStringCType(descriptor_, options_); + + if (unknown_ctype) { + format.Outdent(); + format( + " private:\n" + " // Hidden due to unknown ctype option.\n"); + format.Indent(); + } + + format( + "$deprecated_attr$const std::string& ${1$$name$$}$(int index) const;\n" + "$deprecated_attr$std::string* ${1$mutable_$name$$}$(int index);\n" + "$deprecated_attr$void ${1$set_$name$$}$(int index, const " + "std::string& value);\n" + "$deprecated_attr$void ${1$set_$name$$}$(int index, std::string&& " + "value);\n" + "$deprecated_attr$void ${1$set_$name$$}$(int index, const " + "char* value);\n", + descriptor_); + if (!options_.opensource_runtime) { + format( + "$deprecated_attr$void ${1$set_$name$$}$(int index, " + "StringPiece value);\n", + descriptor_); + } + format( + "$deprecated_attr$void ${1$set_$name$$}$(" + "int index, const $pointer_type$* value, size_t size);\n" + "$deprecated_attr$std::string* ${1$add_$name$$}$();\n" + "$deprecated_attr$void ${1$add_$name$$}$(const std::string& value);\n" + "$deprecated_attr$void ${1$add_$name$$}$(std::string&& value);\n" + "$deprecated_attr$void ${1$add_$name$$}$(const char* value);\n", + descriptor_); + if (!options_.opensource_runtime) { + format( + "$deprecated_attr$void ${1$add_$name$$}$(StringPiece value);\n", + descriptor_); + } + format( + "$deprecated_attr$void ${1$add_$name$$}$(const $pointer_type$* " + "value, size_t size)" + ";\n" + "$deprecated_attr$const ::$proto_ns$::RepeatedPtrField& " + "${1$$name$$}$() " + "const;\n" + "$deprecated_attr$::$proto_ns$::RepeatedPtrField* " + "${1$mutable_$name$$}$()" + ";\n" + "private:\n" + "const std::string& ${1$_internal_$name$$}$(int index) const;\n" + "std::string* _internal_add_$name$();\n" + "public:\n", + descriptor_); + + if (unknown_ctype) { + format.Outdent(); + format(" public:\n"); + format.Indent(); + } +} + +void RepeatedStringFieldGenerator::GenerateInlineAccessorDefinitions( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "inline std::string* $classname$::add_$name$() {\n" + " std::string* _s = _internal_add_$name$();\n" + "$annotate_add_mutable$" + " // @@protoc_insertion_point(field_add_mutable:$full_name$)\n" + " return _s;\n" + "}\n"); + if (options_.safe_boundary_check) { + format( + "inline const std::string& $classname$::_internal_$name$(int index) " + "const {\n" + " return $name$_.InternalCheckedGet(\n" + " index, ::$proto_ns$::internal::GetEmptyStringAlreadyInited());\n" + "}\n"); + } else { + format( + "inline const std::string& $classname$::_internal_$name$(int index) " + "const {\n" + " return $name$_.Get(index);\n" + "}\n"); + } + format( + "inline const std::string& $classname$::$name$(int index) const {\n" + "$annotate_get$" + " // @@protoc_insertion_point(field_get:$full_name$)\n" + " return _internal_$name$(index);\n" + "}\n" + "inline std::string* $classname$::mutable_$name$(int index) {\n" + "$annotate_mutable$" + " // @@protoc_insertion_point(field_mutable:$full_name$)\n" + " return $name$_.Mutable(index);\n" + "}\n" + "inline void $classname$::set_$name$(int index, const std::string& " + "value) " + "{\n" + " $name$_.Mutable(index)->assign(value);\n" + "$annotate_set$" + " // @@protoc_insertion_point(field_set:$full_name$)\n" + "}\n" + "inline void $classname$::set_$name$(int index, std::string&& value) {\n" + " $name$_.Mutable(index)->assign(std::move(value));\n" + "$annotate_set$" + " // @@protoc_insertion_point(field_set:$full_name$)\n" + "}\n" + "inline void $classname$::set_$name$(int index, const char* value) {\n" + " $null_check$" + " $name$_.Mutable(index)->assign(value);\n" + "$annotate_set$" + " // @@protoc_insertion_point(field_set_char:$full_name$)\n" + "}\n"); + if (!options_.opensource_runtime) { + format( + "inline void " + "$classname$::set_$name$(int index, StringPiece value) {\n" + " $name$_.Mutable(index)->assign(value.data(), value.size());\n" + "$annotate_set$" + " // @@protoc_insertion_point(field_set_string_piece:$full_name$)\n" + "}\n"); + } + format( + "inline void " + "$classname$::set_$name$" + "(int index, const $pointer_type$* value, size_t size) {\n" + " $name$_.Mutable(index)->assign(\n" + " reinterpret_cast(value), size);\n" + "$annotate_set$" + " // @@protoc_insertion_point(field_set_pointer:$full_name$)\n" + "}\n" + "inline std::string* $classname$::_internal_add_$name$() {\n" + " return $name$_.Add();\n" + "}\n" + "inline void $classname$::add_$name$(const std::string& value) {\n" + " $name$_.Add()->assign(value);\n" + "$annotate_add$" + " // @@protoc_insertion_point(field_add:$full_name$)\n" + "}\n" + "inline void $classname$::add_$name$(std::string&& value) {\n" + " $name$_.Add(std::move(value));\n" + "$annotate_add$" + " // @@protoc_insertion_point(field_add:$full_name$)\n" + "}\n" + "inline void $classname$::add_$name$(const char* value) {\n" + " $null_check$" + " $name$_.Add()->assign(value);\n" + "$annotate_add$" + " // @@protoc_insertion_point(field_add_char:$full_name$)\n" + "}\n"); + if (!options_.opensource_runtime) { + format( + "inline void $classname$::add_$name$(StringPiece value) {\n" + " $name$_.Add()->assign(value.data(), value.size());\n" + "$annotate_add$" + " // @@protoc_insertion_point(field_add_string_piece:$full_name$)\n" + "}\n"); + } + format( + "inline void " + "$classname$::add_$name$(const $pointer_type$* value, size_t size) {\n" + " $name$_.Add()->assign(reinterpret_cast(value), size);\n" + "$annotate_add$" + " // @@protoc_insertion_point(field_add_pointer:$full_name$)\n" + "}\n" + "inline const ::$proto_ns$::RepeatedPtrField&\n" + "$classname$::$name$() const {\n" + "$annotate_list$" + " // @@protoc_insertion_point(field_list:$full_name$)\n" + " return $name$_;\n" + "}\n" + "inline ::$proto_ns$::RepeatedPtrField*\n" + "$classname$::mutable_$name$() {\n" + "$annotate_mutable_list$" + " // @@protoc_insertion_point(field_mutable_list:$full_name$)\n" + " return &$name$_;\n" + "}\n"); +} + +void RepeatedStringFieldGenerator::GenerateClearingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_.Clear();\n"); +} + +void RepeatedStringFieldGenerator::GenerateMergingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_.MergeFrom(from.$name$_);\n"); +} + +void RepeatedStringFieldGenerator::GenerateSwappingCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_.InternalSwap(&other->$name$_);\n"); +} + +void RepeatedStringFieldGenerator::GenerateConstructorCode( + io::Printer* printer) const { + // Not needed for repeated fields. +} + +void RepeatedStringFieldGenerator::GenerateCopyConstructorCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_.CopyFrom(from.$name$_);"); +} + +void RepeatedStringFieldGenerator::GenerateSerializeWithCachedSizesToArray( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "for (int i = 0, n = this->_internal_$name$_size(); i < n; i++) {\n" + " const auto& s = this->_internal_$name$(i);\n"); + // format("for (const std::string& s : this->$name$()) {\n"); + format.Indent(); + if (descriptor_->type() == FieldDescriptor::TYPE_STRING) { + GenerateUtf8CheckCodeForString(descriptor_, options_, false, + "s.data(), static_cast(s.length()),\n", + format); + } + format.Outdent(); + format( + " target = stream->Write$declared_type$($number$, s, target);\n" + "}\n"); +} + +void RepeatedStringFieldGenerator::GenerateByteSize( + io::Printer* printer) const { + Formatter format(printer, variables_); + format( + "total_size += $tag_size$ *\n" + " ::$proto_ns$::internal::FromIntSize($name$_.size());\n" + "for (int i = 0, n = $name$_.size(); i < n; i++) {\n" + " total_size += " + "::$proto_ns$::internal::WireFormatLite::$declared_type$Size(\n" + " $name$_.Get(i));\n" + "}\n"); +} + +void RepeatedStringFieldGenerator::GenerateConstinitInitializer( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$name$_()"); +} + +} // namespace cpp +} // namespace compiler +} // namespace protobuf +} // namespace google diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_string_field.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_string_field.h new file mode 100644 index 0000000..3f05443 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_string_field.h @@ -0,0 +1,127 @@ +// 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. + +#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_STRING_FIELD_H__ +#define GOOGLE_PROTOBUF_COMPILER_CPP_STRING_FIELD_H__ + +#include +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace cpp { + +class StringFieldGenerator : public FieldGenerator { + public: + StringFieldGenerator(const FieldDescriptor* descriptor, + const Options& options); + ~StringFieldGenerator(); + + // implements FieldGenerator --------------------------------------- + void GeneratePrivateMembers(io::Printer* printer) const override; + void GenerateStaticMembers(io::Printer* printer) const override; + void GenerateAccessorDeclarations(io::Printer* printer) const override; + void GenerateInlineAccessorDefinitions(io::Printer* printer) const override; + void GenerateNonInlineAccessorDefinitions( + io::Printer* printer) const override; + void GenerateClearingCode(io::Printer* printer) const override; + void GenerateMessageClearingCode(io::Printer* printer) const override; + void GenerateMergingCode(io::Printer* printer) const override; + void GenerateSwappingCode(io::Printer* printer) const override; + void GenerateConstructorCode(io::Printer* printer) const override; + void GenerateCopyConstructorCode(io::Printer* printer) const override; + void GenerateDestructorCode(io::Printer* printer) const override; + void GenerateSerializeWithCachedSizesToArray( + io::Printer* printer) const override; + void GenerateByteSize(io::Printer* printer) const override; + void GenerateConstinitInitializer(io::Printer* printer) const override; + bool IsInlined() const override { return inlined_; } + + private: + bool inlined_; + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringFieldGenerator); +}; + +class StringOneofFieldGenerator : public StringFieldGenerator { + public: + StringOneofFieldGenerator(const FieldDescriptor* descriptor, + const Options& options); + ~StringOneofFieldGenerator(); + + // implements FieldGenerator --------------------------------------- + void GenerateInlineAccessorDefinitions(io::Printer* printer) const override; + void GenerateClearingCode(io::Printer* printer) const override; + + // StringFieldGenerator, from which we inherit, overrides this so we need to + // override it as well. + void GenerateMessageClearingCode(io::Printer* printer) const override; + void GenerateSwappingCode(io::Printer* printer) const override; + void GenerateConstructorCode(io::Printer* printer) const override; + + private: + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringOneofFieldGenerator); +}; + +class RepeatedStringFieldGenerator : public FieldGenerator { + public: + RepeatedStringFieldGenerator(const FieldDescriptor* descriptor, + const Options& options); + ~RepeatedStringFieldGenerator(); + + // implements FieldGenerator --------------------------------------- + void GeneratePrivateMembers(io::Printer* printer) const override; + void GenerateAccessorDeclarations(io::Printer* printer) const override; + void GenerateInlineAccessorDefinitions(io::Printer* printer) const override; + void GenerateClearingCode(io::Printer* printer) const override; + void GenerateMergingCode(io::Printer* printer) const override; + void GenerateSwappingCode(io::Printer* printer) const override; + void GenerateConstructorCode(io::Printer* printer) const override; + void GenerateCopyConstructorCode(io::Printer* printer) const override; + void GenerateSerializeWithCachedSizesToArray( + io::Printer* printer) const override; + void GenerateByteSize(io::Printer* printer) const override; + void GenerateConstinitInitializer(io::Printer* printer) const override; + + private: + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedStringFieldGenerator); +}; + +} // namespace cpp +} // namespace compiler +} // namespace protobuf +} // namespace google + +#endif // GOOGLE_PROTOBUF_COMPILER_CPP_STRING_FIELD_H__ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_test_large_enum_value.proto b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_test_large_enum_value.proto new file mode 100644 index 0000000..cb6ca1b --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/cpp/cpp_test_large_enum_value.proto @@ -0,0 +1,43 @@ +// 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. + +// Test that proto2 compiler can generate valid code when the enum value +// is INT_MAX. Note that this is a compile-only test and this proto is not +// referenced in any C++ code. +syntax = "proto2"; + +package protobuf_unittest; + +message TestLargeEnumValue { + enum EnumWithLargeValue { + VALUE_1 = 1; + VALUE_MAX = 0x7fffffff; + } +} diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_field_base.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_field_base.h new file mode 100644 index 0000000..f875fa1 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_field_base.h @@ -0,0 +1,111 @@ +// 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_COMPILER_CSHARP_FIELD_BASE_H__ +#define GOOGLE_PROTOBUF_COMPILER_CSHARP_FIELD_BASE_H__ + +#include +#include + +#include +#include +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace csharp { + +class FieldGeneratorBase : public SourceGeneratorBase { + public: + FieldGeneratorBase(const FieldDescriptor* descriptor, + int presenceIndex, + const Options* options); + ~FieldGeneratorBase(); + + FieldGeneratorBase(const FieldGeneratorBase&) = delete; + FieldGeneratorBase& operator=(const FieldGeneratorBase&) = delete; + + virtual void GenerateCloningCode(io::Printer* printer) = 0; + virtual void GenerateFreezingCode(io::Printer* printer); + virtual void GenerateCodecCode(io::Printer* printer); + virtual void GenerateExtensionCode(io::Printer* printer); + virtual void GenerateMembers(io::Printer* printer) = 0; + virtual void GenerateMergingCode(io::Printer* printer) = 0; + virtual void GenerateParsingCode(io::Printer* printer) = 0; + virtual void GenerateParsingCode(io::Printer* printer, bool use_parse_context); + virtual void GenerateSerializationCode(io::Printer* printer) = 0; + virtual void GenerateSerializationCode(io::Printer* printer, bool use_write_context); + virtual void GenerateSerializedSizeCode(io::Printer* printer) = 0; + + virtual void WriteHash(io::Printer* printer) = 0; + virtual void WriteEquals(io::Printer* printer) = 0; + // Currently unused, as we use reflection to generate JSON + virtual void WriteToString(io::Printer* printer) = 0; + + protected: + const FieldDescriptor* descriptor_; + const int presenceIndex_; + std::map variables_; + + void AddDeprecatedFlag(io::Printer* printer); + void AddNullCheck(io::Printer* printer); + void AddNullCheck(io::Printer* printer, const std::string& name); + + void AddPublicMemberAttributes(io::Printer* printer); + void SetCommonOneofFieldVariables( + std::map* variables); + + std::string oneof_property_name(); + std::string oneof_name(); + std::string property_name(); + std::string name(); + std::string type_name(); + std::string type_name(const FieldDescriptor* descriptor); + bool has_default_value(); + std::string default_value(); + std::string default_value(const FieldDescriptor* descriptor); + std::string number(); + std::string capitalized_type_name(); + + private: + void SetCommonFieldVariables(std::map* variables); + std::string GetStringDefaultValueInternal(const FieldDescriptor* descriptor); + std::string GetBytesDefaultValueInternal(const FieldDescriptor* descriptor); +}; + +} // namespace csharp +} // namespace compiler +} // namespace protobuf +} // namespace google + +#endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_FIELD_BASE_H__ + diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_message_field.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_message_field.cc new file mode 100644 index 0000000..034fbd9 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_message_field.cc @@ -0,0 +1,293 @@ +// 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. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace csharp { + +MessageFieldGenerator::MessageFieldGenerator(const FieldDescriptor* descriptor, + int presenceIndex, + const Options *options) + : FieldGeneratorBase(descriptor, presenceIndex, options) { + if (!SupportsPresenceApi(descriptor_)) { + variables_["has_property_check"] = name() + "_ != null"; + variables_["has_not_property_check"] = name() + "_ == null"; + } +} + +MessageFieldGenerator::~MessageFieldGenerator() { + +} + +void MessageFieldGenerator::GenerateMembers(io::Printer* printer) { + printer->Print( + variables_, + "private $type_name$ $name$_;\n"); + WritePropertyDocComment(printer, descriptor_); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ $type_name$ $property_name$ {\n" + " get { return $name$_; }\n" + " set {\n" + " $name$_ = value;\n" + " }\n" + "}\n"); + if (SupportsPresenceApi(descriptor_)) { + printer->Print( + variables_, + "///

Gets whether the $descriptor_name$ field is set\n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ bool Has$property_name$ {\n" + " get { return $name$_ != null; }\n" + "}\n"); + printer->Print( + variables_, + "/// Clears the value of the $descriptor_name$ field\n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ void Clear$property_name$() {\n" + " $name$_ = null;\n" + "}\n"); + } +} + +void MessageFieldGenerator::GenerateMergingCode(io::Printer* printer) { + printer->Print( + variables_, + "if (other.$has_property_check$) {\n" + " if ($has_not_property_check$) {\n" + " $property_name$ = new $type_name$();\n" + " }\n" + " $property_name$.MergeFrom(other.$property_name$);\n" + "}\n"); +} + +void MessageFieldGenerator::GenerateParsingCode(io::Printer* printer) { + printer->Print( + variables_, + "if ($has_not_property_check$) {\n" + " $property_name$ = new $type_name$();\n" + "}\n"); + if (descriptor_->type() == FieldDescriptor::Type::TYPE_MESSAGE) { + printer->Print(variables_, "input.ReadMessage($property_name$);\n"); + } else { + printer->Print(variables_, "input.ReadGroup($property_name$);\n"); + } +} + +void MessageFieldGenerator::GenerateSerializationCode(io::Printer* printer) { + if (descriptor_->type() == FieldDescriptor::Type::TYPE_MESSAGE) { + printer->Print( + variables_, + "if ($has_property_check$) {\n" + " output.WriteRawTag($tag_bytes$);\n" + " output.WriteMessage($property_name$);\n" + "}\n"); + } else { + printer->Print( + variables_, + "if ($has_property_check$) {\n" + " output.WriteRawTag($tag_bytes$);\n" + " output.WriteGroup($property_name$);\n" + " output.WriteRawTag($end_tag_bytes$);\n" + "}\n"); + } +} + +void MessageFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { + if (descriptor_->type() == FieldDescriptor::Type::TYPE_MESSAGE) { + printer->Print( + variables_, + "if ($has_property_check$) {\n" + " size += $tag_size$ + pb::CodedOutputStream.ComputeMessageSize($property_name$);\n" + "}\n"); + } else { + printer->Print( + variables_, + "if ($has_property_check$) {\n" + " size += $tag_size$ + pb::CodedOutputStream.ComputeGroupSize($property_name$);\n" + "}\n"); + } +} + +void MessageFieldGenerator::WriteHash(io::Printer* printer) { + printer->Print( + variables_, + "if ($has_property_check$) hash ^= $property_name$.GetHashCode();\n"); +} +void MessageFieldGenerator::WriteEquals(io::Printer* printer) { + printer->Print( + variables_, + "if (!object.Equals($property_name$, other.$property_name$)) return false;\n"); +} +void MessageFieldGenerator::WriteToString(io::Printer* printer) { + variables_["field_name"] = GetFieldName(descriptor_); + printer->Print( + variables_, + "PrintField(\"$field_name$\", has$property_name$, $name$_, writer);\n"); +} +void MessageFieldGenerator::GenerateExtensionCode(io::Printer* printer) { + WritePropertyDocComment(printer, descriptor_); + AddDeprecatedFlag(printer); + printer->Print( + variables_, + "$access_level$ static readonly pb::Extension<$extended_type$, $type_name$> $property_name$ =\n" + " new pb::Extension<$extended_type$, $type_name$>($number$, "); + GenerateCodecCode(printer); + printer->Print(");\n"); +} +void MessageFieldGenerator::GenerateCloningCode(io::Printer* printer) { + printer->Print(variables_, + "$name$_ = other.$has_property_check$ ? other.$name$_.Clone() : null;\n"); +} + +void MessageFieldGenerator::GenerateFreezingCode(io::Printer* printer) { +} + +void MessageFieldGenerator::GenerateCodecCode(io::Printer* printer) { + if (descriptor_->type() == FieldDescriptor::Type::TYPE_MESSAGE) { + printer->Print( + variables_, + "pb::FieldCodec.ForMessage($tag$, $type_name$.Parser)"); + } else { + printer->Print( + variables_, + "pb::FieldCodec.ForGroup($tag$, $end_tag$, $type_name$.Parser)"); + } +} + +MessageOneofFieldGenerator::MessageOneofFieldGenerator( + const FieldDescriptor* descriptor, + int presenceIndex, + const Options *options) + : MessageFieldGenerator(descriptor, presenceIndex, options) { + SetCommonOneofFieldVariables(&variables_); +} + +MessageOneofFieldGenerator::~MessageOneofFieldGenerator() { + +} + +void MessageOneofFieldGenerator::GenerateMembers(io::Printer* printer) { + WritePropertyDocComment(printer, descriptor_); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ $type_name$ $property_name$ {\n" + " get { return $has_property_check$ ? ($type_name$) $oneof_name$_ : null; }\n" + " set {\n" + " $oneof_name$_ = value;\n" + " $oneof_name$Case_ = value == null ? $oneof_property_name$OneofCase.None : $oneof_property_name$OneofCase.$property_name$;\n" + " }\n" + "}\n"); + if (SupportsPresenceApi(descriptor_)) { + printer->Print( + variables_, + "/// Gets whether the \"$descriptor_name$\" field is set\n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ bool Has$property_name$ {\n" + " get { return $oneof_name$Case_ == $oneof_property_name$OneofCase.$property_name$; }\n" + "}\n"); + printer->Print( + variables_, + "/// Clears the value of the oneof if it's currently set to \"$descriptor_name$\" \n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ void Clear$property_name$() {\n" + " if ($has_property_check$) {\n" + " Clear$oneof_property_name$();\n" + " }\n" + "}\n"); + } +} + +void MessageOneofFieldGenerator::GenerateMergingCode(io::Printer* printer) { + printer->Print(variables_, + "if ($property_name$ == null) {\n" + " $property_name$ = new $type_name$();\n" + "}\n" + "$property_name$.MergeFrom(other.$property_name$);\n"); +} + +void MessageOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) { + // TODO(jonskeet): We may be able to do better than this + printer->Print( + variables_, + "$type_name$ subBuilder = new $type_name$();\n" + "if ($has_property_check$) {\n" + " subBuilder.MergeFrom($property_name$);\n" + "}\n"); + if (descriptor_->type() == FieldDescriptor::Type::TYPE_MESSAGE) { + printer->Print("input.ReadMessage(subBuilder);\n"); + } else { + printer->Print("input.ReadGroup(subBuilder);\n"); + } + printer->Print(variables_, "$property_name$ = subBuilder;\n"); +} + +void MessageOneofFieldGenerator::WriteToString(io::Printer* printer) { + printer->Print( + variables_, + "PrintField(\"$descriptor_name$\", $has_property_check$, $oneof_name$_, writer);\n"); +} + +void MessageOneofFieldGenerator::GenerateCloningCode(io::Printer* printer) { + printer->Print(variables_, + "$property_name$ = other.$property_name$.Clone();\n"); +} + +} // namespace csharp +} // namespace compiler +} // namespace protobuf +} // namespace google diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_options.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_options.h new file mode 100644 index 0000000..42ff6d8 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_options.h @@ -0,0 +1,81 @@ +// 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_COMPILER_CSHARP_OPTIONS_H__ +#define GOOGLE_PROTOBUF_COMPILER_CSHARP_OPTIONS_H__ + +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace csharp { + +// Generator options (used by csharp_generator.cc): +struct Options { + Options() : + file_extension(".cs"), + base_namespace(""), + base_namespace_specified(false), + internal_access(false), + serializable(false) { + } + // Extension of the generated file. Defaults to ".cs" + std::string file_extension; + // Base namespace to use to create directory hierarchy. Defaults to "". + // This option allows the simple creation of a conventional C# file layout, + // where directories are created relative to a project-specific base + // namespace. For example, in a project with a base namespace of PetShop, a + // proto of user.proto with a C# namespace of PetShop.Model.Shared would + // generate Model/Shared/User.cs underneath the specified --csharp_out + // directory. + // + // If no base namespace is specified, all files are generated in the + // --csharp_out directory, with no subdirectories created automatically. + std::string base_namespace; + // Whether the base namespace has been explicitly specified by the user. + // This is required as the base namespace can be explicitly set to the empty + // string, meaning "create a full directory hierarchy, starting from the first + // segment of the namespace." + bool base_namespace_specified; + // Whether the generated classes should have accessibility level of "internal". + // Defaults to false that generates "public" classes. + bool internal_access; + // Whether the generated classes should have a global::System.Serializable attribute added + // Defaults to false + bool serializable; +}; + +} // namespace csharp +} // namespace compiler +} // namespace protobuf +} // namespace google + +#endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_OPTIONS_H__ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc new file mode 100644 index 0000000..9df1dd6 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc @@ -0,0 +1,349 @@ +// 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. + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace csharp { + +PrimitiveFieldGenerator::PrimitiveFieldGenerator( + const FieldDescriptor* descriptor, int presenceIndex, const Options *options) + : FieldGeneratorBase(descriptor, presenceIndex, options) { + // TODO(jonskeet): Make this cleaner... + is_value_type = descriptor->type() != FieldDescriptor::TYPE_STRING + && descriptor->type() != FieldDescriptor::TYPE_BYTES; + if (!is_value_type && !SupportsPresenceApi(descriptor_)) { + variables_["has_property_check"] = variables_["property_name"] + ".Length != 0"; + variables_["other_has_property_check"] = "other." + variables_["property_name"] + ".Length != 0"; + } +} + +PrimitiveFieldGenerator::~PrimitiveFieldGenerator() { +} + +void PrimitiveFieldGenerator::GenerateMembers(io::Printer* printer) { + + // Note: in multiple places, this code assumes that all fields + // that support presence are either nullable, or use a presence field bit. + // Fields which are oneof members are not generated here; they're generated in PrimitiveOneofFieldGenerator below. + // Extensions are not generated here either. + + + // Proto2 allows different default values to be specified. These are retained + // via static fields. They don't particularly need to be, but we don't need + // to change that. In Proto3 the default value we don't generate these + // fields, just using the literal instead. + if (IsProto2(descriptor_->file())) { + // Note: "private readonly static" isn't as idiomatic as + // "private static readonly", but changing this now would create a lot of + // churn in generated code with near-to-zero benefit. + printer->Print( + variables_, + "private readonly static $type_name$ $property_name$DefaultValue = $default_value$;\n\n"); + variables_["default_value_access"] = + variables_["property_name"] + "DefaultValue"; + } else { + variables_["default_value_access"] = variables_["default_value"]; + } + + // Declare the field itself. + printer->Print( + variables_, + "private $type_name$ $name_def_message$;\n"); + + WritePropertyDocComment(printer, descriptor_); + AddPublicMemberAttributes(printer); + + // Most of the work is done in the property: + // Declare the property itself (the same for all options) + printer->Print(variables_, "$access_level$ $type_name$ $property_name$ {\n"); + + // Specify the "getter", which may need to check for a presence field. + if (SupportsPresenceApi(descriptor_)) { + if (IsNullable(descriptor_)) { + printer->Print( + variables_, + " get { return $name$_ ?? $default_value_access$; }\n"); + } else { + printer->Print( + variables_, + // Note: it's possible that this could be rewritten as a + // conditional ?: expression, but there's no significant benefit + // to changing it. + " get { if ($has_field_check$) { return $name$_; } else { return $default_value_access$; } }\n"); + } + } else { + printer->Print( + variables_, + " get { return $name$_; }\n"); + } + + // Specify the "setter", which may need to set a field bit as well as the + // value. + printer->Print(" set {\n"); + if (presenceIndex_ != -1) { + printer->Print( + variables_, + " $set_has_field$;\n"); + } + if (is_value_type) { + printer->Print( + variables_, + " $name$_ = value;\n"); + } else { + printer->Print( + variables_, + " $name$_ = pb::ProtoPreconditions.CheckNotNull(value, \"value\");\n"); + } + printer->Print( + " }\n" + "}\n"); + + // The "HasFoo" property, where required. + if (SupportsPresenceApi(descriptor_)) { + printer->Print(variables_, + "/// Gets whether the \"$descriptor_name$\" field is set\n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ bool Has$property_name$ {\n" + " get { return "); + if (IsNullable(descriptor_)) { + printer->Print( + variables_, + "$name$_ != null; }\n}\n"); + } else { + printer->Print( + variables_, + "$has_field_check$; }\n}\n"); + } + } + + // The "ClearFoo" method, where required. + if (SupportsPresenceApi(descriptor_)) { + printer->Print(variables_, + "/// Clears the value of the \"$descriptor_name$\" field\n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ void Clear$property_name$() {\n"); + if (IsNullable(descriptor_)) { + printer->Print(variables_, " $name$_ = null;\n"); + } else { + printer->Print(variables_, " $clear_has_field$;\n"); + } + printer->Print("}\n"); + } +} + +void PrimitiveFieldGenerator::GenerateMergingCode(io::Printer* printer) { + printer->Print( + variables_, + "if ($other_has_property_check$) {\n" + " $property_name$ = other.$property_name$;\n" + "}\n"); +} + +void PrimitiveFieldGenerator::GenerateParsingCode(io::Printer* printer) { + // Note: invoke the property setter rather than writing straight to the field, + // so that we can normalize "null to empty" for strings and bytes. + printer->Print( + variables_, + "$property_name$ = input.Read$capitalized_type_name$();\n"); +} + +void PrimitiveFieldGenerator::GenerateSerializationCode(io::Printer* printer) { + printer->Print( + variables_, + "if ($has_property_check$) {\n" + " output.WriteRawTag($tag_bytes$);\n" + " output.Write$capitalized_type_name$($property_name$);\n" + "}\n"); +} + +void PrimitiveFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { + printer->Print( + variables_, + "if ($has_property_check$) {\n"); + printer->Indent(); + int fixedSize = GetFixedSize(descriptor_->type()); + if (fixedSize == -1) { + printer->Print( + variables_, + "size += $tag_size$ + pb::CodedOutputStream.Compute$capitalized_type_name$Size($property_name$);\n"); + } else { + printer->Print( + "size += $tag_size$ + $fixed_size$;\n", + "fixed_size", StrCat(fixedSize), + "tag_size", variables_["tag_size"]); + } + printer->Outdent(); + printer->Print("}\n"); +} + +void PrimitiveFieldGenerator::WriteHash(io::Printer* printer) { + const char *text = "if ($has_property_check$) hash ^= $property_name$.GetHashCode();\n"; + if (descriptor_->type() == FieldDescriptor::TYPE_FLOAT) { + text = "if ($has_property_check$) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode($property_name$);\n"; + } else if (descriptor_->type() == FieldDescriptor::TYPE_DOUBLE) { + text = "if ($has_property_check$) hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode($property_name$);\n"; + } + printer->Print(variables_, text); +} +void PrimitiveFieldGenerator::WriteEquals(io::Printer* printer) { + const char *text = "if ($property_name$ != other.$property_name$) return false;\n"; + if (descriptor_->type() == FieldDescriptor::TYPE_FLOAT) { + text = "if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals($property_name$, other.$property_name$)) return false;\n"; + } else if (descriptor_->type() == FieldDescriptor::TYPE_DOUBLE) { + text = "if (!pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.Equals($property_name$, other.$property_name$)) return false;\n"; + } + printer->Print(variables_, text); +} +void PrimitiveFieldGenerator::WriteToString(io::Printer* printer) { + printer->Print( + variables_, + "PrintField(\"$descriptor_name$\", $has_property_check$, $property_name$, writer);\n"); +} + +void PrimitiveFieldGenerator::GenerateCloningCode(io::Printer* printer) { + printer->Print(variables_, + "$name$_ = other.$name$_;\n"); +} + +void PrimitiveFieldGenerator::GenerateCodecCode(io::Printer* printer) { + printer->Print( + variables_, + "pb::FieldCodec.For$capitalized_type_name$($tag$, $default_value$)"); +} + +void PrimitiveFieldGenerator::GenerateExtensionCode(io::Printer* printer) { + WritePropertyDocComment(printer, descriptor_); + AddDeprecatedFlag(printer); + printer->Print( + variables_, + "$access_level$ static readonly pb::Extension<$extended_type$, $type_name$> $property_name$ =\n" + " new pb::Extension<$extended_type$, $type_name$>($number$, "); + GenerateCodecCode(printer); + printer->Print(");\n"); +} + +PrimitiveOneofFieldGenerator::PrimitiveOneofFieldGenerator( + const FieldDescriptor* descriptor, int presenceIndex, const Options *options) + : PrimitiveFieldGenerator(descriptor, presenceIndex, options) { + SetCommonOneofFieldVariables(&variables_); +} + +PrimitiveOneofFieldGenerator::~PrimitiveOneofFieldGenerator() { +} + +void PrimitiveOneofFieldGenerator::GenerateMembers(io::Printer* printer) { + WritePropertyDocComment(printer, descriptor_); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ $type_name$ $property_name$ {\n" + " get { return $has_property_check$ ? ($type_name$) $oneof_name$_ : $default_value$; }\n" + " set {\n"); + if (is_value_type) { + printer->Print( + variables_, + " $oneof_name$_ = value;\n"); + } else { + printer->Print( + variables_, + " $oneof_name$_ = pb::ProtoPreconditions.CheckNotNull(value, \"value\");\n"); + } + printer->Print( + variables_, + " $oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n" + " }\n" + "}\n"); + if (SupportsPresenceApi(descriptor_)) { + printer->Print( + variables_, + "/// Gets whether the \"$descriptor_name$\" field is set\n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ bool Has$property_name$ {\n" + " get { return $oneof_name$Case_ == $oneof_property_name$OneofCase.$property_name$; }\n" + "}\n"); + printer->Print( + variables_, + "/// Clears the value of the oneof if it's currently set to \"$descriptor_name$\" \n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ void Clear$property_name$() {\n" + " if ($has_property_check$) {\n" + " Clear$oneof_property_name$();\n" + " }\n" + "}\n"); + } +} + +void PrimitiveOneofFieldGenerator::GenerateMergingCode(io::Printer* printer) { + printer->Print(variables_, "$property_name$ = other.$property_name$;\n"); +} + +void PrimitiveOneofFieldGenerator::WriteToString(io::Printer* printer) { + printer->Print(variables_, + "PrintField(\"$descriptor_name$\", $has_property_check$, $oneof_name$_, writer);\n"); +} + +void PrimitiveOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) { + printer->Print( + variables_, + "$property_name$ = input.Read$capitalized_type_name$();\n"); +} + +void PrimitiveOneofFieldGenerator::GenerateCloningCode(io::Printer* printer) { + printer->Print(variables_, + "$property_name$ = other.$property_name$;\n"); +} + +} // namespace csharp +} // namespace compiler +} // namespace protobuf +} // namespace google diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_reflection_class.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_reflection_class.cc new file mode 100644 index 0000000..644fbf1 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_reflection_class.cc @@ -0,0 +1,330 @@ +// 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. + +#include + +#include +#include +#include +#include +#include +#include + + +#include +#include +#include +#include +#include +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace csharp { + +ReflectionClassGenerator::ReflectionClassGenerator(const FileDescriptor* file, + const Options* options) + : SourceGeneratorBase(options), + file_(file) { + namespace_ = GetFileNamespace(file); + reflectionClassname_ = GetReflectionClassUnqualifiedName(file); + extensionClassname_ = GetExtensionClassUnqualifiedName(file); +} + +ReflectionClassGenerator::~ReflectionClassGenerator() { +} + +void ReflectionClassGenerator::Generate(io::Printer* printer) { + WriteIntroduction(printer); + + WriteDescriptor(printer); + // Close the class declaration. + printer->Outdent(); + printer->Print("}\n"); + + if (file_->extension_count() > 0) { + printer->Print( + "/// Holder for extension identifiers generated from the top " + "level of $file_name$\n" + "$access_level$ static partial class $class_name$ {\n", + "access_level", class_access_level(), "class_name", extensionClassname_, + "file_name", file_->name()); + printer->Indent(); + for (int i = 0; i < file_->extension_count(); i++) { + std::unique_ptr generator( + CreateFieldGenerator(file_->extension(i), -1, this->options())); + generator->GenerateExtensionCode(printer); + } + printer->Outdent(); + printer->Print( + "}\n" + "\n"); + } + + // write children: Enums + if (file_->enum_type_count() > 0) { + printer->Print("#region Enums\n"); + for (int i = 0; i < file_->enum_type_count(); i++) { + EnumGenerator enumGenerator(file_->enum_type(i), this->options()); + enumGenerator.Generate(printer); + } + printer->Print("#endregion\n"); + printer->Print("\n"); + } + + // write children: Messages + if (file_->message_type_count() > 0) { + printer->Print("#region Messages\n"); + for (int i = 0; i < file_->message_type_count(); i++) { + MessageGenerator messageGenerator(file_->message_type(i), this->options()); + messageGenerator.Generate(printer); + } + printer->Print("#endregion\n"); + printer->Print("\n"); + } + + // TODO(jtattermusch): add insertion point for services. + + if (!namespace_.empty()) { + printer->Outdent(); + printer->Print("}\n"); + } + printer->Print("\n"); + printer->Print("#endregion Designer generated code\n"); +} + +void ReflectionClassGenerator::WriteIntroduction(io::Printer* printer) { + printer->Print( + "// \n" + "// Generated by the protocol buffer compiler. DO NOT EDIT!\n" + "// source: $file_name$\n" + "// \n" + "#pragma warning disable 1591, 0612, 3021\n" + "#region Designer generated code\n" + "\n" + "using pb = global::Google.Protobuf;\n" + "using pbc = global::Google.Protobuf.Collections;\n" + "using pbr = global::Google.Protobuf.Reflection;\n" + "using scg = global::System.Collections.Generic;\n", + "file_name", file_->name()); + + if (!namespace_.empty()) { + printer->Print("namespace $namespace$ {\n", "namespace", namespace_); + printer->Indent(); + printer->Print("\n"); + } + + printer->Print( + "/// Holder for reflection information generated from $file_name$\n" + "$access_level$ static partial class $reflection_class_name$ {\n" + "\n", + "file_name", file_->name(), + "access_level", class_access_level(), + "reflection_class_name", reflectionClassname_); + printer->Indent(); +} + +void ReflectionClassGenerator::WriteDescriptor(io::Printer* printer) { + printer->Print( + "#region Descriptor\n" + "/// File descriptor for $file_name$\n" + "public static pbr::FileDescriptor Descriptor {\n" + " get { return descriptor; }\n" + "}\n" + "private static pbr::FileDescriptor descriptor;\n" + "\n" + "static $reflection_class_name$() {\n", + "file_name", file_->name(), + "reflection_class_name", reflectionClassname_); + printer->Indent(); + printer->Print( + "byte[] descriptorData = global::System.Convert.FromBase64String(\n"); + printer->Indent(); + printer->Indent(); + printer->Print("string.Concat(\n"); + printer->Indent(); + + // TODO(jonskeet): Consider a C#-escaping format here instead of just Base64. + std::string base64 = FileDescriptorToBase64(file_); + while (base64.size() > 60) { + printer->Print("\"$base64$\",\n", "base64", base64.substr(0, 60)); + base64 = base64.substr(60); + } + printer->Print("\"$base64$\"));\n", "base64", base64); + printer->Outdent(); + printer->Outdent(); + printer->Outdent(); + + // ----------------------------------------------------------------- + // Invoke InternalBuildGeneratedFileFrom() to build the file. + printer->Print( + "descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,\n"); + printer->Print(" new pbr::FileDescriptor[] { "); + for (int i = 0; i < file_->dependency_count(); i++) { + printer->Print( + "$full_reflection_class_name$.Descriptor, ", + "full_reflection_class_name", + GetReflectionClassName(file_->dependency(i))); + } + printer->Print("},\n" + " new pbr::GeneratedClrTypeInfo("); + // Specify all the generated code information, recursively. + if (file_->enum_type_count() > 0) { + printer->Print("new[] {"); + for (int i = 0; i < file_->enum_type_count(); i++) { + printer->Print("typeof($type_name$), ", "type_name", GetClassName(file_->enum_type(i))); + } + printer->Print("}, "); + } + else { + printer->Print("null, "); + } + if (file_->extension_count() > 0) { + std::vector extensions; + for (int i = 0; i < file_->extension_count(); i++) { + extensions.push_back(GetFullExtensionName(file_->extension(i))); + } + printer->Print("new pb::Extension[] { $extensions$ }, ", "extensions", Join(extensions, ", ")); + } + else { + printer->Print("null, "); + } + if (file_->message_type_count() > 0) { + printer->Print("new pbr::GeneratedClrTypeInfo[] {\n"); + printer->Indent(); + printer->Indent(); + printer->Indent(); + for (int i = 0; i < file_->message_type_count(); i++) { + WriteGeneratedCodeInfo(file_->message_type(i), printer, i == file_->message_type_count() - 1); + } + printer->Outdent(); + printer->Print("\n}));\n"); + printer->Outdent(); + printer->Outdent(); + } + else { + printer->Print("null));\n"); + } + + printer->Outdent(); + printer->Print("}\n"); + printer->Print("#endregion\n\n"); +} + +// Write out the generated code for a particular message. This consists of the CLR type, property names +// corresponding to fields, names corresponding to oneofs, nested enums, and nested types. Each array part +// can be specified as null if it would be empty, to make the generated code somewhat simpler to read. +// We write a line break at the end of each generated code info, so that in the final file we'll see all +// the types, pre-ordered depth first, one per line. The indentation will be slightly unusual, +// in that it will look like a single array when it's actually constructing a tree, but it'll be easy to +// read even with multiple levels of nesting. +// The "last" parameter indicates whether this message descriptor is the last one being printed in this immediate +// context. It governs whether or not a trailing comma and newline is written after the constructor, effectively +// just controlling the formatting in the generated code. +void ReflectionClassGenerator::WriteGeneratedCodeInfo(const Descriptor* descriptor, io::Printer* printer, bool last) { + if (IsMapEntryMessage(descriptor)) { + printer->Print("null, "); + return; + } + // Generated message type + printer->Print("new pbr::GeneratedClrTypeInfo(typeof($type_name$), $type_name$.Parser, ", "type_name", GetClassName(descriptor)); + + // Fields + if (descriptor->field_count() > 0) { + std::vector fields; + fields.reserve(descriptor->field_count()); + for (int i = 0; i < descriptor->field_count(); i++) { + fields.push_back(GetPropertyName(descriptor->field(i))); + } + printer->Print("new[]{ \"$fields$\" }, ", "fields", Join(fields, "\", \"")); + } + else { + printer->Print("null, "); + } + + // Oneofs + if (descriptor->oneof_decl_count() > 0) { + std::vector oneofs; + oneofs.reserve(descriptor->oneof_decl_count()); + for (int i = 0; i < descriptor->oneof_decl_count(); i++) { + oneofs.push_back(UnderscoresToCamelCase(descriptor->oneof_decl(i)->name(), true)); + } + printer->Print("new[]{ \"$oneofs$\" }, ", "oneofs", Join(oneofs, "\", \"")); + } + else { + printer->Print("null, "); + } + + // Nested enums + if (descriptor->enum_type_count() > 0) { + std::vector enums; + enums.reserve(descriptor->enum_type_count()); + for (int i = 0; i < descriptor->enum_type_count(); i++) { + enums.push_back(GetClassName(descriptor->enum_type(i))); + } + printer->Print("new[]{ typeof($enums$) }, ", "enums", Join(enums, "), typeof(")); + } + else { + printer->Print("null, "); + } + + // Extensions + if (descriptor->extension_count() > 0) { + std::vector extensions; + for (int i = 0; i < descriptor->extension_count(); i++) { + extensions.push_back(GetFullExtensionName(descriptor->extension(i))); + } + printer->Print("new pb::Extension[] { $extensions$ }, ", "extensions", Join(extensions, ", ")); + } + else { + printer->Print("null, "); + } + + // Nested types + if (descriptor->nested_type_count() > 0) { + // Need to specify array type explicitly here, as all elements may be null. + printer->Print("new pbr::GeneratedClrTypeInfo[] { "); + for (int i = 0; i < descriptor->nested_type_count(); i++) { + WriteGeneratedCodeInfo(descriptor->nested_type(i), printer, i == descriptor->nested_type_count() - 1); + } + printer->Print("}"); + } + else { + printer->Print("null"); + } + printer->Print(last ? ")" : "),\n"); +} + +} // namespace csharp +} // namespace compiler +} // namespace protobuf +} // namespace google diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.h new file mode 100644 index 0000000..2e26570 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.h @@ -0,0 +1,79 @@ +// 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_COMPILER_CSHARP_REPEATED_ENUM_FIELD_H__ +#define GOOGLE_PROTOBUF_COMPILER_CSHARP_REPEATED_ENUM_FIELD_H__ + +#include + +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace csharp { + +// TODO(jonskeet): Refactor repeated field support; all the implementations are +// *really* similar. We should probably have a RepeatedFieldGeneratorBase. +class RepeatedEnumFieldGenerator : public FieldGeneratorBase { + public: + RepeatedEnumFieldGenerator(const FieldDescriptor* descriptor, + int presenceIndex, + const Options *options); + ~RepeatedEnumFieldGenerator(); + + RepeatedEnumFieldGenerator(const RepeatedEnumFieldGenerator&) = delete; + RepeatedEnumFieldGenerator& operator=(const RepeatedEnumFieldGenerator&) = + delete; + + virtual void GenerateCloningCode(io::Printer* printer) override; + virtual void GenerateFreezingCode(io::Printer* printer) override; + virtual void GenerateMembers(io::Printer* printer) override; + virtual void GenerateMergingCode(io::Printer* printer) override; + virtual void GenerateParsingCode(io::Printer* printer) override; + virtual void GenerateParsingCode(io::Printer* printer, bool use_parse_context) override; + virtual void GenerateSerializationCode(io::Printer* printer) override; + virtual void GenerateSerializationCode(io::Printer* printer, bool use_write_context) override; + virtual void GenerateSerializedSizeCode(io::Printer* printer) override; + virtual void GenerateExtensionCode(io::Printer* printer) override; + + virtual void WriteHash(io::Printer* printer) override; + virtual void WriteEquals(io::Printer* printer) override; + virtual void WriteToString(io::Printer* printer) override; +}; + +} // namespace csharp +} // namespace compiler +} // namespace protobuf +} // namespace google + +#endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_REPEATED_ENUM_FIELD_H__ + diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc new file mode 100644 index 0000000..578f54b --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc @@ -0,0 +1,308 @@ +// 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. + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace csharp { + +WrapperFieldGenerator::WrapperFieldGenerator(const FieldDescriptor* descriptor, + int presenceIndex, const Options *options) + : FieldGeneratorBase(descriptor, presenceIndex, options) { + variables_["has_property_check"] = name() + "_ != null"; + variables_["has_not_property_check"] = name() + "_ == null"; + const FieldDescriptor* wrapped_field = descriptor->message_type()->field(0); + is_value_type = wrapped_field->type() != FieldDescriptor::TYPE_STRING && + wrapped_field->type() != FieldDescriptor::TYPE_BYTES; + if (is_value_type) { + variables_["nonnullable_type_name"] = type_name(wrapped_field); + } +} + +WrapperFieldGenerator::~WrapperFieldGenerator() { +} + +void WrapperFieldGenerator::GenerateMembers(io::Printer* printer) { + printer->Print( + variables_, + "private static readonly pb::FieldCodec<$type_name$> _single_$name$_codec = "); + GenerateCodecCode(printer); + printer->Print( + variables_, + ";\n" + "private $type_name$ $name$_;\n"); + WritePropertyDocComment(printer, descriptor_); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ $type_name$ $property_name$ {\n" + " get { return $name$_; }\n" + " set {\n" + " $name$_ = value;\n" + " }\n" + "}\n\n"); + if (SupportsPresenceApi(descriptor_)) { + printer->Print( + variables_, + "/// Gets whether the $descriptor_name$ field is set\n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ bool Has$property_name$ {\n" + " get { return $name$_ != null; }\n" + "}\n\n"); + printer->Print( + variables_, + "/// Clears the value of the $descriptor_name$ field\n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ void Clear$property_name$() {\n" + " $name$_ = null;\n" + "}\n"); + } +} + +void WrapperFieldGenerator::GenerateMergingCode(io::Printer* printer) { + printer->Print( + variables_, + "if (other.$has_property_check$) {\n" + " if ($has_not_property_check$ || other.$property_name$ != $default_value$) {\n" + " $property_name$ = other.$property_name$;\n" + " }\n" + "}\n"); +} + +void WrapperFieldGenerator::GenerateParsingCode(io::Printer* printer) { + GenerateParsingCode(printer, true); +} + +void WrapperFieldGenerator::GenerateParsingCode(io::Printer* printer, bool use_parse_context) { + printer->Print( + variables_, + use_parse_context + ? "$type_name$ value = _single_$name$_codec.Read(ref input);\n" + "if ($has_not_property_check$ || value != $default_value$) {\n" + " $property_name$ = value;\n" + "}\n" + : "$type_name$ value = _single_$name$_codec.Read(input);\n" + "if ($has_not_property_check$ || value != $default_value$) {\n" + " $property_name$ = value;\n" + "}\n"); +} + +void WrapperFieldGenerator::GenerateSerializationCode(io::Printer* printer) { + GenerateSerializationCode(printer, true); +} + +void WrapperFieldGenerator::GenerateSerializationCode(io::Printer* printer, bool use_write_context) { + printer->Print( + variables_, + use_write_context + ? "if ($has_property_check$) {\n" + " _single_$name$_codec.WriteTagAndValue(ref output, $property_name$);\n" + "}\n" + : "if ($has_property_check$) {\n" + " _single_$name$_codec.WriteTagAndValue(output, $property_name$);\n" + "}\n"); +} + +void WrapperFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { + printer->Print( + variables_, + "if ($has_property_check$) {\n" + " size += _single_$name$_codec.CalculateSizeWithTag($property_name$);\n" + "}\n"); +} + +void WrapperFieldGenerator::WriteHash(io::Printer* printer) { + const char *text = "if ($has_property_check$) hash ^= $property_name$.GetHashCode();\n"; + if (descriptor_->message_type()->field(0)->type() == FieldDescriptor::TYPE_FLOAT) { + text = "if ($has_property_check$) hash ^= pbc::ProtobufEqualityComparers.BitwiseNullableSingleEqualityComparer.GetHashCode($property_name$);\n"; + } + else if (descriptor_->message_type()->field(0)->type() == FieldDescriptor::TYPE_DOUBLE) { + text = "if ($has_property_check$) hash ^= pbc::ProtobufEqualityComparers.BitwiseNullableDoubleEqualityComparer.GetHashCode($property_name$);\n"; + } + printer->Print(variables_, text); +} + +void WrapperFieldGenerator::WriteEquals(io::Printer* printer) { + const char *text = "if ($property_name$ != other.$property_name$) return false;\n"; + if (descriptor_->message_type()->field(0)->type() == FieldDescriptor::TYPE_FLOAT) { + text = "if (!pbc::ProtobufEqualityComparers.BitwiseNullableSingleEqualityComparer.Equals($property_name$, other.$property_name$)) return false;\n"; + } + else if (descriptor_->message_type()->field(0)->type() == FieldDescriptor::TYPE_DOUBLE) { + text = "if (!pbc::ProtobufEqualityComparers.BitwiseNullableDoubleEqualityComparer.Equals($property_name$, other.$property_name$)) return false;\n"; + } + printer->Print(variables_, text); +} + +void WrapperFieldGenerator::WriteToString(io::Printer* printer) { + // TODO: Implement if we ever actually need it... +} + +void WrapperFieldGenerator::GenerateCloningCode(io::Printer* printer) { + printer->Print(variables_, + "$property_name$ = other.$property_name$;\n"); +} + +void WrapperFieldGenerator::GenerateCodecCode(io::Printer* printer) { + if (is_value_type) { + printer->Print( + variables_, + "pb::FieldCodec.ForStructWrapper<$nonnullable_type_name$>($tag$)"); + } else { + printer->Print( + variables_, + "pb::FieldCodec.ForClassWrapper<$type_name$>($tag$)"); + } +} + +void WrapperFieldGenerator::GenerateExtensionCode(io::Printer* printer) { + WritePropertyDocComment(printer, descriptor_); + AddDeprecatedFlag(printer); + printer->Print( + variables_, + "$access_level$ static readonly pb::Extension<$extended_type$, $type_name$> $property_name$ =\n" + " new pb::Extension<$extended_type$, $type_name$>($number$, "); + GenerateCodecCode(printer); + printer->Print(");\n"); +} + +WrapperOneofFieldGenerator::WrapperOneofFieldGenerator( + const FieldDescriptor* descriptor, int presenceIndex, const Options *options) + : WrapperFieldGenerator(descriptor, presenceIndex, options) { + SetCommonOneofFieldVariables(&variables_); +} + +WrapperOneofFieldGenerator::~WrapperOneofFieldGenerator() { +} + +void WrapperOneofFieldGenerator::GenerateMembers(io::Printer* printer) { + // Note: deliberately _oneof_$name$_codec, not _$oneof_name$_codec... we have one codec per field. + printer->Print( + variables_, + "private static readonly pb::FieldCodec<$type_name$> _oneof_$name$_codec = "); + GenerateCodecCode(printer); + printer->Print(";\n"); + WritePropertyDocComment(printer, descriptor_); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ $type_name$ $property_name$ {\n" + " get { return $has_property_check$ ? ($type_name$) $oneof_name$_ : ($type_name$) null; }\n" + " set {\n" + " $oneof_name$_ = value;\n" + " $oneof_name$Case_ = value == null ? $oneof_property_name$OneofCase.None : $oneof_property_name$OneofCase.$property_name$;\n" + " }\n" + "}\n"); + if (SupportsPresenceApi(descriptor_)) { + printer->Print( + variables_, + "/// Gets whether the \"$descriptor_name$\" field is set\n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ bool Has$property_name$ {\n" + " get { return $oneof_name$Case_ == $oneof_property_name$OneofCase.$property_name$; }\n" + "}\n"); + printer->Print( + variables_, + "/// Clears the value of the oneof if it's currently set to \"$descriptor_name$\" \n"); + AddPublicMemberAttributes(printer); + printer->Print( + variables_, + "$access_level$ void Clear$property_name$() {\n" + " if ($has_property_check$) {\n" + " Clear$oneof_property_name$();\n" + " }\n" + "}\n"); + } +} + +void WrapperOneofFieldGenerator::GenerateMergingCode(io::Printer* printer) { + printer->Print(variables_, "$property_name$ = other.$property_name$;\n"); +} + +void WrapperOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) { + GenerateParsingCode(printer, true); +} + +void WrapperOneofFieldGenerator::GenerateParsingCode(io::Printer* printer, bool use_parse_context) { + printer->Print( + variables_, + use_parse_context + ? "$property_name$ = _oneof_$name$_codec.Read(ref input);\n" + : "$property_name$ = _oneof_$name$_codec.Read(input);\n"); +} + +void WrapperOneofFieldGenerator::GenerateSerializationCode(io::Printer* printer) { + GenerateSerializationCode(printer, true); +} + +void WrapperOneofFieldGenerator::GenerateSerializationCode(io::Printer* printer, bool use_write_context) { + // TODO: I suspect this is wrong... + printer->Print( + variables_, + use_write_context + ? "if ($has_property_check$) {\n" + " _oneof_$name$_codec.WriteTagAndValue(ref output, ($type_name$) $oneof_name$_);\n" + "}\n" + : "if ($has_property_check$) {\n" + " _oneof_$name$_codec.WriteTagAndValue(output, ($type_name$) $oneof_name$_);\n" + "}\n"); +} + +void WrapperOneofFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { + // TODO: I suspect this is wrong... + printer->Print( + variables_, + "if ($has_property_check$) {\n" + " size += _oneof_$name$_codec.CalculateSizeWithTag($property_name$);\n" + "}\n"); +} + +} // namespace csharp +} // namespace compiler +} // namespace protobuf +} // namespace google diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_context.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_context.h new file mode 100644 index 0000000..3fa6af1 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_context.h @@ -0,0 +1,113 @@ +// 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_COMPILER_JAVA_CONTEXT_H__ +#define GOOGLE_PROTOBUF_COMPILER_JAVA_CONTEXT_H__ + +#include +#include +#include + +#include +#include + +namespace google { +namespace protobuf { +class FileDescriptor; +class FieldDescriptor; +class OneofDescriptor; +class Descriptor; +class EnumDescriptor; +namespace compiler { +namespace java { +class ClassNameResolver; // name_resolver.h +} +} // namespace compiler +} // namespace protobuf +} // namespace google + +namespace google { +namespace protobuf { +namespace compiler { +namespace java { + +struct FieldGeneratorInfo; +struct OneofGeneratorInfo; +// A context object holds the information that is shared among all code +// generators. +class Context { + public: + Context(const FileDescriptor* file, const Options& options); + ~Context(); + + // Get the name resolver associated with this context. The resolver + // can be used to map descriptors to Java class names. + ClassNameResolver* GetNameResolver() const; + + // Get the FieldGeneratorInfo for a given field. + const FieldGeneratorInfo* GetFieldGeneratorInfo( + const FieldDescriptor* field) const; + + // Get the OneofGeneratorInfo for a given oneof. + const OneofGeneratorInfo* GetOneofGeneratorInfo( + const OneofDescriptor* oneof) const; + + const Options& options() const { return options_; } + + // Enforces all the files (including transitive dependencies) to use + // LiteRuntime. + + bool EnforceLite() const { return options_.enforce_lite; } + + // Does this message class have generated parsing, serialization, and other + // standard methods for which reflection-based fallback implementations exist? + bool HasGeneratedMethods(const Descriptor* descriptor) const; + + private: + void InitializeFieldGeneratorInfo(const FileDescriptor* file); + void InitializeFieldGeneratorInfoForMessage(const Descriptor* message); + void InitializeFieldGeneratorInfoForFields( + const std::vector& fields); + + std::unique_ptr name_resolver_; + std::map + field_generator_info_map_; + std::map + oneof_generator_info_map_; + Options options_; + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Context); +}; + +} // namespace java +} // namespace compiler +} // namespace protobuf +} // namespace google + +#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_CONTEXT_H__ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_extension.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_extension.h new file mode 100644 index 0000000..f928a78 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_extension.h @@ -0,0 +1,115 @@ +// 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. + +#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_EXTENSION_H__ +#define GOOGLE_PROTOBUF_COMPILER_JAVA_EXTENSION_H__ + +#include +#include + +#include + +namespace google { +namespace protobuf { +class FieldDescriptor; // descriptor.h +namespace compiler { +namespace java { +class Context; // context.h +class ClassNameResolver; // name_resolver.h +} // namespace java +} // namespace compiler +namespace io { +class Printer; // printer.h +} +} // namespace protobuf +} // namespace google + +namespace google { +namespace protobuf { +namespace compiler { +namespace java { + +// Generates code for an extension, which may be within the scope of some +// message or may be at file scope. This is much simpler than FieldGenerator +// since extensions are just simple identifiers with interesting types. +class ExtensionGenerator { + public: + explicit ExtensionGenerator() {} + virtual ~ExtensionGenerator() {} + + virtual void Generate(io::Printer* printer) = 0; + + // Returns an estimate of the number of bytes the printed code will compile + // to + virtual int GenerateNonNestedInitializationCode(io::Printer* printer) = 0; + + // Returns an estimate of the number of bytes the printed code will compile + // to + virtual int GenerateRegistrationCode(io::Printer* printer) = 0; + + protected: + static void InitTemplateVars( + const FieldDescriptor* descriptor, const std::string& scope, + bool immutable, ClassNameResolver* name_resolver, + std::map* vars_pointer); + + private: + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator); +}; + +class ImmutableExtensionGenerator : public ExtensionGenerator { + public: + explicit ImmutableExtensionGenerator(const FieldDescriptor* descriptor, + Context* context); + virtual ~ImmutableExtensionGenerator(); + + void Generate(io::Printer* printer) override; + int GenerateNonNestedInitializationCode(io::Printer* printer) override; + int GenerateRegistrationCode(io::Printer* printer) override; + + protected: + const FieldDescriptor* descriptor_; + ClassNameResolver* name_resolver_; + std::string scope_; + + private: + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableExtensionGenerator); +}; + +} // namespace java +} // namespace compiler +} // namespace protobuf +} // namespace google + +#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_EXTENSION_H__ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_generator.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_generator.h new file mode 100644 index 0000000..6315e7c --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_generator.h @@ -0,0 +1,76 @@ +// 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. +// +// Generates Java code for a given .proto file. + +#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_GENERATOR_H__ +#define GOOGLE_PROTOBUF_COMPILER_JAVA_GENERATOR_H__ + +#include +#include + +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace java { + +// CodeGenerator implementation which generates Java code. If you create your +// own protocol compiler binary and you want it to support Java output, you +// can do so by registering an instance of this CodeGenerator with the +// CommandLineInterface in your main() function. +class PROTOC_EXPORT JavaGenerator : public CodeGenerator { + public: + JavaGenerator(); + ~JavaGenerator(); + + // implements CodeGenerator ---------------------------------------- + bool Generate(const FileDescriptor* file, const std::string& parameter, + GeneratorContext* context, std::string* error) const override; + + uint64_t GetSupportedFeatures() const override; + + private: + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(JavaGenerator); +}; + +} // namespace java +} // namespace compiler +} // namespace protobuf +} // namespace google + +#include + +#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_GENERATOR_H__ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_helpers.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_helpers.cc new file mode 100644 index 0000000..681d597 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_helpers.cc @@ -0,0 +1,1111 @@ +// 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. + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include // for hash + +namespace google { +namespace protobuf { +namespace compiler { +namespace java { + +using internal::WireFormat; +using internal::WireFormatLite; + +const char kThickSeparator[] = + "// ===================================================================\n"; +const char kThinSeparator[] = + "// -------------------------------------------------------------------\n"; + +namespace { + +const char* kDefaultPackage = ""; + +// Names that should be avoided (in UpperCamelCase format). +// Using them will cause the compiler to generate accessors whose names +// collide with methods defined in base classes. +// Keep this list in sync with specialFieldNames in +// java/core/src/main/java/com/google/protobuf/DescriptorMessageInfoFactory.java +const char* kForbiddenWordList[] = { + // java.lang.Object: + "Class", + // com.google.protobuf.MessageLiteOrBuilder: + "DefaultInstanceForType", + // com.google.protobuf.MessageLite: + "ParserForType", + "SerializedSize", + // com.google.protobuf.MessageOrBuilder: + "AllFields", + "DescriptorForType", + "InitializationErrorString", + "UnknownFields", + // obsolete. kept for backwards compatibility of generated code + "CachedSize", +}; + +const std::unordered_set* kReservedNames = + new std::unordered_set({ + "abstract", "assert", "boolean", "break", "byte", + "case", "catch", "char", "class", "const", + "continue", "default", "do", "double", "else", + "enum", "extends", "final", "finally", "float", + "for", "goto", "if", "implements", "import", + "instanceof", "int", "interface", "long", "native", + "new", "package", "private", "protected", "public", + "return", "short", "static", "strictfp", "super", + "switch", "synchronized", "this", "throw", "throws", + "transient", "try", "void", "volatile", "while", + }); + +bool IsForbidden(const std::string& field_name) { + for (int i = 0; i < GOOGLE_ARRAYSIZE(kForbiddenWordList); ++i) { + if (UnderscoresToCamelCase(field_name, true) == kForbiddenWordList[i]) { + return true; + } + } + return false; +} + +std::string FieldName(const FieldDescriptor* field) { + std::string field_name; + // Groups are hacky: The name of the field is just the lower-cased name + // of the group type. In Java, though, we would like to retain the original + // capitalization of the type name. + if (GetType(field) == FieldDescriptor::TYPE_GROUP) { + field_name = field->message_type()->name(); + } else { + field_name = field->name(); + } + if (IsForbidden(field_name)) { + // Append a trailing "#" to indicate that the name should be decorated to + // avoid collision with other names. + field_name += "#"; + } + return field_name; +} + + +} // namespace + +void PrintGeneratedAnnotation(io::Printer* printer, char delimiter, + const std::string& annotation_file) { + if (annotation_file.empty()) { + return; + } + std::string ptemplate = + "@javax.annotation.Generated(value=\"protoc\", comments=\"annotations:"; + ptemplate.push_back(delimiter); + ptemplate.append("annotation_file"); + ptemplate.push_back(delimiter); + ptemplate.append("\")\n"); + printer->Print(ptemplate.c_str(), "annotation_file", annotation_file); +} + +void PrintEnumVerifierLogic(io::Printer* printer, + const FieldDescriptor* descriptor, + const std::map& variables, + const char* var_name, + const char* terminating_string, bool enforce_lite) { + std::string enum_verifier_string = + enforce_lite ? StrCat(var_name, ".internalGetVerifier()") + : StrCat( + "new com.google.protobuf.Internal.EnumVerifier() {\n" + " @java.lang.Override\n" + " public boolean isInRange(int number) {\n" + " return ", + var_name, + ".forNumber(number) != null;\n" + " }\n" + " }"); + printer->Print( + variables, + StrCat(enum_verifier_string, terminating_string).c_str()); +} + +std::string UnderscoresToCamelCase(const std::string& input, + bool cap_next_letter) { + GOOGLE_CHECK(!input.empty()); + std::string result; + // Note: I distrust ctype.h due to locales. + for (int i = 0; i < input.size(); i++) { + if ('a' <= input[i] && input[i] <= 'z') { + if (cap_next_letter) { + result += input[i] + ('A' - 'a'); + } else { + result += input[i]; + } + cap_next_letter = false; + } else if ('A' <= input[i] && input[i] <= 'Z') { + if (i == 0 && !cap_next_letter) { + // Force first letter to lower-case unless explicitly told to + // capitalize it. + result += input[i] + ('a' - 'A'); + } else { + // Capital letters after the first are left as-is. + result += input[i]; + } + cap_next_letter = false; + } else if ('0' <= input[i] && input[i] <= '9') { + result += input[i]; + cap_next_letter = true; + } else { + cap_next_letter = true; + } + } + // Add a trailing "_" if the name should be altered. + if (input[input.size() - 1] == '#') { + result += '_'; + } + return result; +} + +std::string ToCamelCase(const std::string& input, bool lower_first) { + bool capitalize_next = !lower_first; + std::string result; + result.reserve(input.size()); + + for (char i : input) { + if (i == '_') { + capitalize_next = true; + } else if (capitalize_next) { + result.push_back(ToUpperCh(i)); + capitalize_next = false; + } else { + result.push_back(i); + } + } + + // Lower-case the first letter. + if (lower_first && !result.empty()) { + result[0] = ToLowerCh(result[0]); + } + + return result; +} + +char ToUpperCh(char ch) { + return (ch >= 'a' && ch <= 'z') ? (ch - 'a' + 'A') : ch; +} + +char ToLowerCh(char ch) { + return (ch >= 'A' && ch <= 'Z') ? (ch - 'A' + 'a') : ch; +} + +std::string UnderscoresToCamelCase(const FieldDescriptor* field) { + return UnderscoresToCamelCase(FieldName(field), false); +} + +std::string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field) { + return UnderscoresToCamelCase(FieldName(field), true); +} + +std::string CapitalizedFieldName(const FieldDescriptor* field) { + return UnderscoresToCapitalizedCamelCase(field); +} + +std::string UnderscoresToCamelCase(const MethodDescriptor* method) { + return UnderscoresToCamelCase(method->name(), false); +} + +std::string UnderscoresToCamelCaseCheckReserved(const FieldDescriptor* field) { + std::string name = UnderscoresToCamelCase(field); + if (kReservedNames->find(name) != kReservedNames->end()) { + return name + "_"; + } + return name; +} + +bool IsForbiddenKotlin(const std::string& field_name) { + // Names that should be avoided as field names in Kotlin. + // All Kotlin hard keywords are in this list. + const std::unordered_set* kKotlinForbiddenNames = + new std::unordered_set({ + "as", "as?", "break", "class", "continue", "do", + "else", "false", "for", "fun", "if", "in", + "!in", "interface", "is", "!is", "null", "object", + "package", "return", "super", "this", "throw", "true", + "try", "typealias", "typeof", "val", "var", "when", + "while", + }); + return kKotlinForbiddenNames->find(field_name) != + kKotlinForbiddenNames->end(); +} + +std::string UniqueFileScopeIdentifier(const Descriptor* descriptor) { + return "static_" + StringReplace(descriptor->full_name(), ".", "_", true); +} + +std::string CamelCaseFieldName(const FieldDescriptor* field) { + std::string fieldName = UnderscoresToCamelCase(field); + if ('0' <= fieldName[0] && fieldName[0] <= '9') { + return '_' + fieldName; + } + return fieldName; +} + +std::string FileClassName(const FileDescriptor* file, bool immutable) { + ClassNameResolver name_resolver; + return name_resolver.GetFileClassName(file, immutable); +} + +std::string FileJavaPackage(const FileDescriptor* file, bool immutable) { + std::string result; + + if (file->options().has_java_package()) { + result = file->options().java_package(); + } else { + result = kDefaultPackage; + if (!file->package().empty()) { + if (!result.empty()) result += '.'; + result += file->package(); + } + } + + return result; +} + +std::string FileJavaPackage(const FileDescriptor* file) { + return FileJavaPackage(file, true /* immutable */); +} + +std::string JavaPackageToDir(std::string package_name) { + std::string package_dir = StringReplace(package_name, ".", "/", true); + if (!package_dir.empty()) package_dir += "/"; + return package_dir; +} + +std::string ClassName(const Descriptor* descriptor) { + ClassNameResolver name_resolver; + return name_resolver.GetClassName(descriptor, true); +} + +std::string ClassName(const EnumDescriptor* descriptor) { + ClassNameResolver name_resolver; + return name_resolver.GetClassName(descriptor, true); +} + +std::string ClassName(const ServiceDescriptor* descriptor) { + ClassNameResolver name_resolver; + return name_resolver.GetClassName(descriptor, true); +} + +std::string ClassName(const FileDescriptor* descriptor) { + ClassNameResolver name_resolver; + return name_resolver.GetClassName(descriptor, true); +} + + +std::string ExtraMessageInterfaces(const Descriptor* descriptor) { + std::string interfaces = "// @@protoc_insertion_point(message_implements:" + + descriptor->full_name() + ")"; + return interfaces; +} + + +std::string ExtraBuilderInterfaces(const Descriptor* descriptor) { + std::string interfaces = "// @@protoc_insertion_point(builder_implements:" + + descriptor->full_name() + ")"; + return interfaces; +} + +std::string ExtraMessageOrBuilderInterfaces(const Descriptor* descriptor) { + std::string interfaces = "// @@protoc_insertion_point(interface_extends:" + + descriptor->full_name() + ")"; + return interfaces; +} + +std::string FieldConstantName(const FieldDescriptor* field) { + std::string name = field->name() + "_FIELD_NUMBER"; + ToUpper(&name); + return name; +} + +FieldDescriptor::Type GetType(const FieldDescriptor* field) { + return field->type(); +} + +JavaType GetJavaType(const FieldDescriptor* field) { + switch (GetType(field)) { + case FieldDescriptor::TYPE_INT32: + case FieldDescriptor::TYPE_UINT32: + case FieldDescriptor::TYPE_SINT32: + case FieldDescriptor::TYPE_FIXED32: + case FieldDescriptor::TYPE_SFIXED32: + return JAVATYPE_INT; + + case FieldDescriptor::TYPE_INT64: + case FieldDescriptor::TYPE_UINT64: + case FieldDescriptor::TYPE_SINT64: + case FieldDescriptor::TYPE_FIXED64: + case FieldDescriptor::TYPE_SFIXED64: + return JAVATYPE_LONG; + + case FieldDescriptor::TYPE_FLOAT: + return JAVATYPE_FLOAT; + + case FieldDescriptor::TYPE_DOUBLE: + return JAVATYPE_DOUBLE; + + case FieldDescriptor::TYPE_BOOL: + return JAVATYPE_BOOLEAN; + + case FieldDescriptor::TYPE_STRING: + return JAVATYPE_STRING; + + case FieldDescriptor::TYPE_BYTES: + return JAVATYPE_BYTES; + + case FieldDescriptor::TYPE_ENUM: + return JAVATYPE_ENUM; + + case FieldDescriptor::TYPE_GROUP: + case FieldDescriptor::TYPE_MESSAGE: + return JAVATYPE_MESSAGE; + + // No default because we want the compiler to complain if any new + // types are added. + } + + GOOGLE_LOG(FATAL) << "Can't get here."; + return JAVATYPE_INT; +} + +const char* PrimitiveTypeName(JavaType type) { + switch (type) { + case JAVATYPE_INT: + return "int"; + case JAVATYPE_LONG: + return "long"; + case JAVATYPE_FLOAT: + return "float"; + case JAVATYPE_DOUBLE: + return "double"; + case JAVATYPE_BOOLEAN: + return "boolean"; + case JAVATYPE_STRING: + return "java.lang.String"; + case JAVATYPE_BYTES: + return "com.google.protobuf.ByteString"; + case JAVATYPE_ENUM: + return NULL; + case JAVATYPE_MESSAGE: + return NULL; + + // No default because we want the compiler to complain if any new + // JavaTypes are added. + } + + GOOGLE_LOG(FATAL) << "Can't get here."; + return NULL; +} + +const char* PrimitiveTypeName(const FieldDescriptor* descriptor) { + return PrimitiveTypeName(GetJavaType(descriptor)); +} + +const char* BoxedPrimitiveTypeName(JavaType type) { + switch (type) { + case JAVATYPE_INT: + return "java.lang.Integer"; + case JAVATYPE_LONG: + return "java.lang.Long"; + case JAVATYPE_FLOAT: + return "java.lang.Float"; + case JAVATYPE_DOUBLE: + return "java.lang.Double"; + case JAVATYPE_BOOLEAN: + return "java.lang.Boolean"; + case JAVATYPE_STRING: + return "java.lang.String"; + case JAVATYPE_BYTES: + return "com.google.protobuf.ByteString"; + case JAVATYPE_ENUM: + return NULL; + case JAVATYPE_MESSAGE: + return NULL; + + // No default because we want the compiler to complain if any new + // JavaTypes are added. + } + + GOOGLE_LOG(FATAL) << "Can't get here."; + return NULL; +} + +const char* BoxedPrimitiveTypeName(const FieldDescriptor* descriptor) { + return BoxedPrimitiveTypeName(GetJavaType(descriptor)); +} + +const char* KotlinTypeName(JavaType type) { + switch (type) { + case JAVATYPE_INT: + return "kotlin.Int"; + case JAVATYPE_LONG: + return "kotlin.Long"; + case JAVATYPE_FLOAT: + return "kotlin.Float"; + case JAVATYPE_DOUBLE: + return "kotlin.Double"; + case JAVATYPE_BOOLEAN: + return "kotlin.Boolean"; + case JAVATYPE_STRING: + return "kotlin.String"; + case JAVATYPE_BYTES: + return "com.google.protobuf.ByteString"; + case JAVATYPE_ENUM: + return NULL; + case JAVATYPE_MESSAGE: + return NULL; + + // No default because we want the compiler to complain if any new + // JavaTypes are added. + } + + GOOGLE_LOG(FATAL) << "Can't get here."; + return NULL; +} + +std::string GetOneofStoredType(const FieldDescriptor* field) { + const JavaType javaType = GetJavaType(field); + switch (javaType) { + case JAVATYPE_ENUM: + return "java.lang.Integer"; + case JAVATYPE_MESSAGE: + return ClassName(field->message_type()); + default: + return BoxedPrimitiveTypeName(javaType); + } +} + +const char* FieldTypeName(FieldDescriptor::Type field_type) { + switch (field_type) { + case FieldDescriptor::TYPE_INT32: + return "INT32"; + case FieldDescriptor::TYPE_UINT32: + return "UINT32"; + case FieldDescriptor::TYPE_SINT32: + return "SINT32"; + case FieldDescriptor::TYPE_FIXED32: + return "FIXED32"; + case FieldDescriptor::TYPE_SFIXED32: + return "SFIXED32"; + case FieldDescriptor::TYPE_INT64: + return "INT64"; + case FieldDescriptor::TYPE_UINT64: + return "UINT64"; + case FieldDescriptor::TYPE_SINT64: + return "SINT64"; + case FieldDescriptor::TYPE_FIXED64: + return "FIXED64"; + case FieldDescriptor::TYPE_SFIXED64: + return "SFIXED64"; + case FieldDescriptor::TYPE_FLOAT: + return "FLOAT"; + case FieldDescriptor::TYPE_DOUBLE: + return "DOUBLE"; + case FieldDescriptor::TYPE_BOOL: + return "BOOL"; + case FieldDescriptor::TYPE_STRING: + return "STRING"; + case FieldDescriptor::TYPE_BYTES: + return "BYTES"; + case FieldDescriptor::TYPE_ENUM: + return "ENUM"; + case FieldDescriptor::TYPE_GROUP: + return "GROUP"; + case FieldDescriptor::TYPE_MESSAGE: + return "MESSAGE"; + + // No default because we want the compiler to complain if any new + // types are added. + } + + GOOGLE_LOG(FATAL) << "Can't get here."; + return NULL; +} + +bool AllAscii(const std::string& text) { + for (int i = 0; i < text.size(); i++) { + if ((text[i] & 0x80) != 0) { + return false; + } + } + return true; +} + +std::string DefaultValue(const FieldDescriptor* field, bool immutable, + ClassNameResolver* name_resolver) { + // Switch on CppType since we need to know which default_value_* method + // of FieldDescriptor to call. + switch (field->cpp_type()) { + case FieldDescriptor::CPPTYPE_INT32: + return StrCat(field->default_value_int32()); + case FieldDescriptor::CPPTYPE_UINT32: + // Need to print as a signed int since Java has no unsigned. + return StrCat(static_cast(field->default_value_uint32())); + case FieldDescriptor::CPPTYPE_INT64: + return StrCat(field->default_value_int64()) + "L"; + case FieldDescriptor::CPPTYPE_UINT64: + return StrCat(static_cast(field->default_value_uint64())) + + "L"; + case FieldDescriptor::CPPTYPE_DOUBLE: { + double value = field->default_value_double(); + if (value == std::numeric_limits::infinity()) { + return "Double.POSITIVE_INFINITY"; + } else if (value == -std::numeric_limits::infinity()) { + return "Double.NEGATIVE_INFINITY"; + } else if (value != value) { + return "Double.NaN"; + } else { + return SimpleDtoa(value) + "D"; + } + } + case FieldDescriptor::CPPTYPE_FLOAT: { + float value = field->default_value_float(); + if (value == std::numeric_limits::infinity()) { + return "Float.POSITIVE_INFINITY"; + } else if (value == -std::numeric_limits::infinity()) { + return "Float.NEGATIVE_INFINITY"; + } else if (value != value) { + return "Float.NaN"; + } else { + return SimpleFtoa(value) + "F"; + } + } + case FieldDescriptor::CPPTYPE_BOOL: + return field->default_value_bool() ? "true" : "false"; + case FieldDescriptor::CPPTYPE_STRING: + if (GetType(field) == FieldDescriptor::TYPE_BYTES) { + if (field->has_default_value()) { + // See comments in Internal.java for gory details. + return strings::Substitute( + "com.google.protobuf.Internal.bytesDefaultValue(\"$0\")", + CEscape(field->default_value_string())); + } else { + return "com.google.protobuf.ByteString.EMPTY"; + } + } else { + if (AllAscii(field->default_value_string())) { + // All chars are ASCII. In this case CEscape() works fine. + return "\"" + CEscape(field->default_value_string()) + "\""; + } else { + // See comments in Internal.java for gory details. + return strings::Substitute( + "com.google.protobuf.Internal.stringDefaultValue(\"$0\")", + CEscape(field->default_value_string())); + } + } + + case FieldDescriptor::CPPTYPE_ENUM: + return name_resolver->GetClassName(field->enum_type(), immutable) + "." + + field->default_value_enum()->name(); + + case FieldDescriptor::CPPTYPE_MESSAGE: + return name_resolver->GetClassName(field->message_type(), immutable) + + ".getDefaultInstance()"; + + // No default because we want the compiler to complain if any new + // types are added. + } + + GOOGLE_LOG(FATAL) << "Can't get here."; + return ""; +} + +bool IsDefaultValueJavaDefault(const FieldDescriptor* field) { + // Switch on CppType since we need to know which default_value_* method + // of FieldDescriptor to call. + switch (field->cpp_type()) { + case FieldDescriptor::CPPTYPE_INT32: + return field->default_value_int32() == 0; + case FieldDescriptor::CPPTYPE_UINT32: + return field->default_value_uint32() == 0; + case FieldDescriptor::CPPTYPE_INT64: + return field->default_value_int64() == 0L; + case FieldDescriptor::CPPTYPE_UINT64: + return field->default_value_uint64() == 0L; + case FieldDescriptor::CPPTYPE_DOUBLE: + return field->default_value_double() == 0.0; + case FieldDescriptor::CPPTYPE_FLOAT: + return field->default_value_float() == 0.0; + case FieldDescriptor::CPPTYPE_BOOL: + return field->default_value_bool() == false; + case FieldDescriptor::CPPTYPE_ENUM: + return field->default_value_enum()->number() == 0; + case FieldDescriptor::CPPTYPE_STRING: + case FieldDescriptor::CPPTYPE_MESSAGE: + return false; + + // No default because we want the compiler to complain if any new + // types are added. + } + + GOOGLE_LOG(FATAL) << "Can't get here."; + return false; +} + +bool IsByteStringWithCustomDefaultValue(const FieldDescriptor* field) { + return GetJavaType(field) == JAVATYPE_BYTES && + field->default_value_string() != ""; +} + +const char* bit_masks[] = { + "0x00000001", "0x00000002", "0x00000004", "0x00000008", + "0x00000010", "0x00000020", "0x00000040", "0x00000080", + + "0x00000100", "0x00000200", "0x00000400", "0x00000800", + "0x00001000", "0x00002000", "0x00004000", "0x00008000", + + "0x00010000", "0x00020000", "0x00040000", "0x00080000", + "0x00100000", "0x00200000", "0x00400000", "0x00800000", + + "0x01000000", "0x02000000", "0x04000000", "0x08000000", + "0x10000000", "0x20000000", "0x40000000", "0x80000000", +}; + +std::string GetBitFieldName(int index) { + std::string varName = "bitField"; + varName += StrCat(index); + varName += "_"; + return varName; +} + +std::string GetBitFieldNameForBit(int bitIndex) { + return GetBitFieldName(bitIndex / 32); +} + +namespace { + +std::string GenerateGetBitInternal(const std::string& prefix, int bitIndex) { + std::string varName = prefix + GetBitFieldNameForBit(bitIndex); + int bitInVarIndex = bitIndex % 32; + + std::string mask = bit_masks[bitInVarIndex]; + std::string result = "((" + varName + " & " + mask + ") != 0)"; + return result; +} + +std::string GenerateSetBitInternal(const std::string& prefix, int bitIndex) { + std::string varName = prefix + GetBitFieldNameForBit(bitIndex); + int bitInVarIndex = bitIndex % 32; + + std::string mask = bit_masks[bitInVarIndex]; + std::string result = varName + " |= " + mask; + return result; +} + +} // namespace + +std::string GenerateGetBit(int bitIndex) { + return GenerateGetBitInternal("", bitIndex); +} + +std::string GenerateSetBit(int bitIndex) { + return GenerateSetBitInternal("", bitIndex); +} + +std::string GenerateClearBit(int bitIndex) { + std::string varName = GetBitFieldNameForBit(bitIndex); + int bitInVarIndex = bitIndex % 32; + + std::string mask = bit_masks[bitInVarIndex]; + std::string result = varName + " = (" + varName + " & ~" + mask + ")"; + return result; +} + +std::string GenerateGetBitFromLocal(int bitIndex) { + return GenerateGetBitInternal("from_", bitIndex); +} + +std::string GenerateSetBitToLocal(int bitIndex) { + return GenerateSetBitInternal("to_", bitIndex); +} + +std::string GenerateGetBitMutableLocal(int bitIndex) { + return GenerateGetBitInternal("mutable_", bitIndex); +} + +std::string GenerateSetBitMutableLocal(int bitIndex) { + return GenerateSetBitInternal("mutable_", bitIndex); +} + +bool IsReferenceType(JavaType type) { + switch (type) { + case JAVATYPE_INT: + return false; + case JAVATYPE_LONG: + return false; + case JAVATYPE_FLOAT: + return false; + case JAVATYPE_DOUBLE: + return false; + case JAVATYPE_BOOLEAN: + return false; + case JAVATYPE_STRING: + return true; + case JAVATYPE_BYTES: + return true; + case JAVATYPE_ENUM: + return true; + case JAVATYPE_MESSAGE: + return true; + + // No default because we want the compiler to complain if any new + // JavaTypes are added. + } + + GOOGLE_LOG(FATAL) << "Can't get here."; + return false; +} + +const char* GetCapitalizedType(const FieldDescriptor* field, bool immutable) { + switch (GetType(field)) { + case FieldDescriptor::TYPE_INT32: + return "Int32"; + case FieldDescriptor::TYPE_UINT32: + return "UInt32"; + case FieldDescriptor::TYPE_SINT32: + return "SInt32"; + case FieldDescriptor::TYPE_FIXED32: + return "Fixed32"; + case FieldDescriptor::TYPE_SFIXED32: + return "SFixed32"; + case FieldDescriptor::TYPE_INT64: + return "Int64"; + case FieldDescriptor::TYPE_UINT64: + return "UInt64"; + case FieldDescriptor::TYPE_SINT64: + return "SInt64"; + case FieldDescriptor::TYPE_FIXED64: + return "Fixed64"; + case FieldDescriptor::TYPE_SFIXED64: + return "SFixed64"; + case FieldDescriptor::TYPE_FLOAT: + return "Float"; + case FieldDescriptor::TYPE_DOUBLE: + return "Double"; + case FieldDescriptor::TYPE_BOOL: + return "Bool"; + case FieldDescriptor::TYPE_STRING: + return "String"; + case FieldDescriptor::TYPE_BYTES: { + return "Bytes"; + } + case FieldDescriptor::TYPE_ENUM: + return "Enum"; + case FieldDescriptor::TYPE_GROUP: + return "Group"; + case FieldDescriptor::TYPE_MESSAGE: + return "Message"; + + // No default because we want the compiler to complain if any new + // types are added. + } + + GOOGLE_LOG(FATAL) << "Can't get here."; + return NULL; +} + +// For encodings with fixed sizes, returns that size in bytes. Otherwise +// returns -1. +int FixedSize(FieldDescriptor::Type type) { + switch (type) { + case FieldDescriptor::TYPE_INT32: + return -1; + case FieldDescriptor::TYPE_INT64: + return -1; + case FieldDescriptor::TYPE_UINT32: + return -1; + case FieldDescriptor::TYPE_UINT64: + return -1; + case FieldDescriptor::TYPE_SINT32: + return -1; + case FieldDescriptor::TYPE_SINT64: + return -1; + case FieldDescriptor::TYPE_FIXED32: + return WireFormatLite::kFixed32Size; + case FieldDescriptor::TYPE_FIXED64: + return WireFormatLite::kFixed64Size; + case FieldDescriptor::TYPE_SFIXED32: + return WireFormatLite::kSFixed32Size; + case FieldDescriptor::TYPE_SFIXED64: + return WireFormatLite::kSFixed64Size; + case FieldDescriptor::TYPE_FLOAT: + return WireFormatLite::kFloatSize; + case FieldDescriptor::TYPE_DOUBLE: + return WireFormatLite::kDoubleSize; + + case FieldDescriptor::TYPE_BOOL: + return WireFormatLite::kBoolSize; + case FieldDescriptor::TYPE_ENUM: + return -1; + + case FieldDescriptor::TYPE_STRING: + return -1; + case FieldDescriptor::TYPE_BYTES: + return -1; + case FieldDescriptor::TYPE_GROUP: + return -1; + case FieldDescriptor::TYPE_MESSAGE: + return -1; + + // No default because we want the compiler to complain if any new + // types are added. + } + GOOGLE_LOG(FATAL) << "Can't get here."; + return -1; +} + +// Sort the fields of the given Descriptor by number into a new[]'d array +// and return it. The caller should delete the returned array. +const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor) { + const FieldDescriptor** fields = + new const FieldDescriptor*[descriptor->field_count()]; + for (int i = 0; i < descriptor->field_count(); i++) { + fields[i] = descriptor->field(i); + } + std::sort(fields, fields + descriptor->field_count(), + FieldOrderingByNumber()); + return fields; +} + +// Returns true if the message type has any required fields. If it doesn't, +// we can optimize out calls to its isInitialized() method. +// +// already_seen is used to avoid checking the same type multiple times +// (and also to protect against recursion). +bool HasRequiredFields(const Descriptor* type, + std::unordered_set* already_seen) { + if (already_seen->count(type) > 0) { + // The type is already in cache. This means that either: + // a. The type has no required fields. + // b. We are in the midst of checking if the type has required fields, + // somewhere up the stack. In this case, we know that if the type + // has any required fields, they'll be found when we return to it, + // and the whole call to HasRequiredFields() will return true. + // Therefore, we don't have to check if this type has required fields + // here. + return false; + } + already_seen->insert(type); + + // If the type has extensions, an extension with message type could contain + // required fields, so we have to be conservative and assume such an + // extension exists. + if (type->extension_range_count() > 0) return true; + + for (int i = 0; i < type->field_count(); i++) { + const FieldDescriptor* field = type->field(i); + if (field->is_required()) { + return true; + } + if (GetJavaType(field) == JAVATYPE_MESSAGE) { + if (HasRequiredFields(field->message_type(), already_seen)) { + return true; + } + } + } + + return false; +} + +bool HasRequiredFields(const Descriptor* type) { + std::unordered_set already_seen; + return HasRequiredFields(type, &already_seen); +} + +bool HasRepeatedFields(const Descriptor* descriptor) { + for (int i = 0; i < descriptor->field_count(); ++i) { + const FieldDescriptor* field = descriptor->field(i); + if (field->is_repeated()) { + return true; + } + } + return false; +} + +// Encode an unsigned 32-bit value into a sequence of UTF-16 characters. +// +// If the value is in [0x0000, 0xD7FF], we encode it with a single character +// with the same numeric value. +// +// If the value is larger than 0xD7FF, we encode its lowest 13 bits into a +// character in the range [0xE000, 0xFFFF] by combining these 13 bits with +// 0xE000 using logic-or. Then we shift the value to the right by 13 bits, and +// encode the remaining value by repeating this same process until we get to +// a value in [0x0000, 0xD7FF] where we will encode it using a character with +// the same numeric value. +// +// Note that we only use code points in [0x0000, 0xD7FF] and [0xE000, 0xFFFF]. +// There will be no surrogate pairs in the encoded character sequence. +void WriteUInt32ToUtf16CharSequence(uint32_t number, + std::vector* output) { + // For values in [0x0000, 0xD7FF], only use one char to encode it. + if (number < 0xD800) { + output->push_back(static_cast(number)); + return; + } + // Encode into multiple chars. All except the last char will be in the range + // [0xE000, 0xFFFF], and the last char will be in the range [0x0000, 0xD7FF]. + // Note that we don't use any value in range [0xD800, 0xDFFF] because they + // have to come in pairs and the encoding is just more space-efficient w/o + // them. + while (number >= 0xD800) { + // [0xE000, 0xFFFF] can represent 13 bits of info. + output->push_back(static_cast(0xE000 | (number & 0x1FFF))); + number >>= 13; + } + output->push_back(static_cast(number)); +} + +int GetExperimentalJavaFieldTypeForSingular(const FieldDescriptor* field) { + // j/c/g/protobuf/FieldType.java lists field types in a slightly different + // order from FieldDescriptor::Type so we can't do a simple cast. + // + // TODO(xiaofeng): Make j/c/g/protobuf/FieldType.java follow the same order. + int result = field->type(); + if (result == FieldDescriptor::TYPE_GROUP) { + return 17; + } else if (result < FieldDescriptor::TYPE_GROUP) { + return result - 1; + } else { + return result - 2; + } +} + +int GetExperimentalJavaFieldTypeForRepeated(const FieldDescriptor* field) { + if (field->type() == FieldDescriptor::TYPE_GROUP) { + return 49; + } else { + return GetExperimentalJavaFieldTypeForSingular(field) + 18; + } +} + +int GetExperimentalJavaFieldTypeForPacked(const FieldDescriptor* field) { + int result = field->type(); + if (result < FieldDescriptor::TYPE_STRING) { + return result + 34; + } else if (result > FieldDescriptor::TYPE_BYTES) { + return result + 30; + } else { + GOOGLE_LOG(FATAL) << field->full_name() << " can't be packed."; + return 0; + } +} + +int GetExperimentalJavaFieldType(const FieldDescriptor* field) { + static const int kMapFieldType = 50; + static const int kOneofFieldTypeOffset = 51; + static const int kRequiredBit = 0x100; + static const int kUtf8CheckBit = 0x200; + static const int kCheckInitialized = 0x400; + static const int kMapWithProto2EnumValue = 0x800; + static const int kHasHasBit = 0x1000; + int extra_bits = field->is_required() ? kRequiredBit : 0; + if (field->type() == FieldDescriptor::TYPE_STRING && CheckUtf8(field)) { + extra_bits |= kUtf8CheckBit; + } + if (field->is_required() || (GetJavaType(field) == JAVATYPE_MESSAGE && + HasRequiredFields(field->message_type()))) { + extra_bits |= kCheckInitialized; + } + if (HasHasbit(field)) { + extra_bits |= kHasHasBit; + } + + if (field->is_map()) { + if (!SupportUnknownEnumValue(field)) { + const FieldDescriptor* value = + field->message_type()->map_value(); + if (GetJavaType(value) == JAVATYPE_ENUM) { + extra_bits |= kMapWithProto2EnumValue; + } + } + return kMapFieldType | extra_bits; + } else if (field->is_packed()) { + return GetExperimentalJavaFieldTypeForPacked(field); + } else if (field->is_repeated()) { + return GetExperimentalJavaFieldTypeForRepeated(field) | extra_bits; + } else if (IsRealOneof(field)) { + return (GetExperimentalJavaFieldTypeForSingular(field) + + kOneofFieldTypeOffset) | + extra_bits; + } else { + return GetExperimentalJavaFieldTypeForSingular(field) | extra_bits; + } +} + +// Escape a UTF-16 character to be embedded in a Java string. +void EscapeUtf16ToString(uint16_t code, std::string* output) { + if (code == '\t') { + output->append("\\t"); + } else if (code == '\b') { + output->append("\\b"); + } else if (code == '\n') { + output->append("\\n"); + } else if (code == '\r') { + output->append("\\r"); + } else if (code == '\f') { + output->append("\\f"); + } else if (code == '\'') { + output->append("\\'"); + } else if (code == '\"') { + output->append("\\\""); + } else if (code == '\\') { + output->append("\\\\"); + } else if (code >= 0x20 && code <= 0x7f) { + output->push_back(static_cast(code)); + } else { + output->append(StringPrintf("\\u%04x", code)); + } +} + +} // namespace java +} // namespace compiler +} // namespace protobuf +} // namespace google diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_helpers.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_helpers.h new file mode 100644 index 0000000..28cac6a --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_helpers.h @@ -0,0 +1,459 @@ +// 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. + +#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__ +#define GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__ + +#include +#include + +#include +#include +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace java { + +// Commonly-used separator comments. Thick is a line of '=', thin is a line +// of '-'. +extern const char kThickSeparator[]; +extern const char kThinSeparator[]; + +bool IsForbiddenKotlin(const std::string& field_name); + +// If annotation_file is non-empty, prints a javax.annotation.Generated +// annotation to the given Printer. annotation_file will be referenced in the +// annotation's comments field. delimiter should be the Printer's delimiter +// character. annotation_file will be included verbatim into a Java literal +// string, so it should not contain quotes or invalid Java escape sequences; +// however, these are unlikely to appear in practice, as the value of +// annotation_file should be generated from the filename of the source file +// being annotated (which in turn must be a Java identifier plus ".java"). +void PrintGeneratedAnnotation(io::Printer* printer, char delimiter = '$', + const std::string& annotation_file = ""); + +// If a GeneratedMessageLite contains non-lite enums, then its verifier +// must be instantiated inline, rather than retrieved from the enum class. +void PrintEnumVerifierLogic(io::Printer* printer, + const FieldDescriptor* descriptor, + const std::map& variables, + const char* var_name, + const char* terminating_string, bool enforce_lite); + +// Converts a name to camel-case. If cap_first_letter is true, capitalize the +// first letter. +std::string ToCamelCase(const std::string& input, bool lower_first); + +char ToUpperCh(char ch); +char ToLowerCh(char ch); + +// Converts a name to camel-case. If cap_first_letter is true, capitalize the +// first letter. +std::string UnderscoresToCamelCase(const std::string& name, + bool cap_first_letter); +// Converts the field's name to camel-case, e.g. "foo_bar_baz" becomes +// "fooBarBaz" or "FooBarBaz", respectively. +std::string UnderscoresToCamelCase(const FieldDescriptor* field); +std::string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field); + +// Similar, but for method names. (Typically, this merely has the effect +// of lower-casing the first letter of the name.) +std::string UnderscoresToCamelCase(const MethodDescriptor* method); + +// Same as UnderscoresToCamelCase, but checks for reserved keywords +std::string UnderscoresToCamelCaseCheckReserved(const FieldDescriptor* field); + +// Similar to UnderscoresToCamelCase, but guarantees that the result is a +// complete Java identifier by adding a _ if needed. +std::string CamelCaseFieldName(const FieldDescriptor* field); + +// Get an identifier that uniquely identifies this type within the file. +// This is used to declare static variables related to this type at the +// outermost file scope. +std::string UniqueFileScopeIdentifier(const Descriptor* descriptor); + +// Gets the unqualified class name for the file. For each .proto file, there +// will be one Java class containing all the immutable messages and another +// Java class containing all the mutable messages. +// TODO(xiaofeng): remove the default value after updating client code. +std::string FileClassName(const FileDescriptor* file, bool immutable = true); + +// Returns the file's Java package name. +std::string FileJavaPackage(const FileDescriptor* file, bool immutable); + +// Returns output directory for the given package name. +std::string JavaPackageToDir(std::string package_name); + +// Comma-separate list of option-specified interfaces implemented by the +// Message, to follow the "implements" declaration of the Message definition. +std::string ExtraMessageInterfaces(const Descriptor* descriptor); +// Comma-separate list of option-specified interfaces implemented by the +// MutableMessage, to follow the "implements" declaration of the MutableMessage +// definition. +std::string ExtraMutableMessageInterfaces(const Descriptor* descriptor); +// Comma-separate list of option-specified interfaces implemented by the +// Builder, to follow the "implements" declaration of the Builder definition. +std::string ExtraBuilderInterfaces(const Descriptor* descriptor); +// Comma-separate list of option-specified interfaces extended by the +// MessageOrBuilder, to follow the "extends" declaration of the +// MessageOrBuilder definition. +std::string ExtraMessageOrBuilderInterfaces(const Descriptor* descriptor); + +// Get the unqualified Java class name for mutable messages. i.e. without +// package or outer classnames. +inline std::string ShortMutableJavaClassName(const Descriptor* descriptor) { + return descriptor->name(); +} + +// Whether the given descriptor is for one of the core descriptor protos. We +// cannot currently use the new runtime with core protos since there is a +// bootstrapping problem with obtaining their descriptors. +inline bool IsDescriptorProto(const Descriptor* descriptor) { + return descriptor->file()->name() == "net/proto2/proto/descriptor.proto" || + descriptor->file()->name() == "google/protobuf/descriptor.proto"; +} + +// Returns the stored type string used by the experimental runtime for oneof +// fields. +std::string GetOneofStoredType(const FieldDescriptor* field); + + +// Whether we should generate multiple java files for messages. +inline bool MultipleJavaFiles(const FileDescriptor* descriptor, + bool immutable) { + (void)immutable; + return descriptor->options().java_multiple_files(); +} + + +// Returns true if `descriptor` will be written to its own .java file. +// `immutable` should be set to true if we're generating for the immutable API. +template +bool IsOwnFile(const Descriptor* descriptor, bool immutable) { + return descriptor->containing_type() == NULL && + MultipleJavaFiles(descriptor->file(), immutable); +} + +template <> +inline bool IsOwnFile(const ServiceDescriptor* descriptor, bool immutable) { + return MultipleJavaFiles(descriptor->file(), immutable); +} + +// If `descriptor` describes an object with its own .java file, +// returns the name (relative to that .java file) of the file that stores +// annotation data for that descriptor. `suffix` is usually empty, but may +// (e.g.) be "OrBuilder" for some generated interfaces. +template +std::string AnnotationFileName(const Descriptor* descriptor, + const std::string& suffix) { + return descriptor->name() + suffix + ".java.pb.meta"; +} + +template +void MaybePrintGeneratedAnnotation(Context* context, io::Printer* printer, + Descriptor* descriptor, bool immutable, + const std::string& suffix = "") { + if (IsOwnFile(descriptor, immutable)) { + PrintGeneratedAnnotation(printer, '$', + context->options().annotate_code + ? AnnotationFileName(descriptor, suffix) + : ""); + } +} + +// Get the unqualified name that should be used for a field's field +// number constant. +std::string FieldConstantName(const FieldDescriptor* field); + +// Returns the type of the FieldDescriptor. +// This does nothing interesting for the open source release, but is used for +// hacks that improve compatibility with version 1 protocol buffers at Google. +FieldDescriptor::Type GetType(const FieldDescriptor* field); + +enum JavaType { + JAVATYPE_INT, + JAVATYPE_LONG, + JAVATYPE_FLOAT, + JAVATYPE_DOUBLE, + JAVATYPE_BOOLEAN, + JAVATYPE_STRING, + JAVATYPE_BYTES, + JAVATYPE_ENUM, + JAVATYPE_MESSAGE +}; + +JavaType GetJavaType(const FieldDescriptor* field); + +const char* PrimitiveTypeName(JavaType type); + +// Get the fully-qualified class name for a boxed primitive type, e.g. +// "java.lang.Integer" for JAVATYPE_INT. Returns NULL for enum and message +// types. +const char* BoxedPrimitiveTypeName(JavaType type); + +// Kotlin source does not distinguish between primitives and non-primitives, +// but does use Kotlin-specific qualified types for them. +const char* KotlinTypeName(JavaType type); + +// Get the name of the java enum constant representing this type. E.g., +// "INT32" for FieldDescriptor::TYPE_INT32. The enum constant's full +// name is "com.google.protobuf.WireFormat.FieldType.INT32". +const char* FieldTypeName(const FieldDescriptor::Type field_type); + +class ClassNameResolver; +std::string DefaultValue(const FieldDescriptor* field, bool immutable, + ClassNameResolver* name_resolver); +inline std::string ImmutableDefaultValue(const FieldDescriptor* field, + ClassNameResolver* name_resolver) { + return DefaultValue(field, true, name_resolver); +} +bool IsDefaultValueJavaDefault(const FieldDescriptor* field); +bool IsByteStringWithCustomDefaultValue(const FieldDescriptor* field); + +// Does this message class have descriptor and reflection methods? +inline bool HasDescriptorMethods(const Descriptor* /* descriptor */, + bool enforce_lite) { + return !enforce_lite; +} +inline bool HasDescriptorMethods(const EnumDescriptor* /* descriptor */, + bool enforce_lite) { + return !enforce_lite; +} +inline bool HasDescriptorMethods(const FileDescriptor* /* descriptor */, + bool enforce_lite) { + return !enforce_lite; +} + +// Should we generate generic services for this file? +inline bool HasGenericServices(const FileDescriptor* file, bool enforce_lite) { + return file->service_count() > 0 && + HasDescriptorMethods(file, enforce_lite) && + file->options().java_generic_services(); +} + +// Methods for shared bitfields. + +// Gets the name of the shared bitfield for the given index. +std::string GetBitFieldName(int index); + +// Gets the name of the shared bitfield for the given bit index. +// Effectively, GetBitFieldName(bitIndex / 32) +std::string GetBitFieldNameForBit(int bitIndex); + +// Generates the java code for the expression that returns the boolean value +// of the bit of the shared bitfields for the given bit index. +// Example: "((bitField1_ & 0x04) == 0x04)" +std::string GenerateGetBit(int bitIndex); + +// Generates the java code for the expression that sets the bit of the shared +// bitfields for the given bit index. +// Example: "bitField1_ = (bitField1_ | 0x04)" +std::string GenerateSetBit(int bitIndex); + +// Generates the java code for the expression that clears the bit of the shared +// bitfields for the given bit index. +// Example: "bitField1_ = (bitField1_ & ~0x04)" +std::string GenerateClearBit(int bitIndex); + +// Does the same as GenerateGetBit but operates on the bit field on a local +// variable. This is used by the builder to copy the value in the builder to +// the message. +// Example: "((from_bitField1_ & 0x04) == 0x04)" +std::string GenerateGetBitFromLocal(int bitIndex); + +// Does the same as GenerateSetBit but operates on the bit field on a local +// variable. This is used by the builder to copy the value in the builder to +// the message. +// Example: "to_bitField1_ = (to_bitField1_ | 0x04)" +std::string GenerateSetBitToLocal(int bitIndex); + +// Does the same as GenerateGetBit but operates on the bit field on a local +// variable. This is used by the parsing constructor to record if a repeated +// field is mutable. +// Example: "((mutable_bitField1_ & 0x04) == 0x04)" +std::string GenerateGetBitMutableLocal(int bitIndex); + +// Does the same as GenerateSetBit but operates on the bit field on a local +// variable. This is used by the parsing constructor to record if a repeated +// field is mutable. +// Example: "mutable_bitField1_ = (mutable_bitField1_ | 0x04)" +std::string GenerateSetBitMutableLocal(int bitIndex); + +// Returns whether the JavaType is a reference type. +bool IsReferenceType(JavaType type); + +// Returns the capitalized name for calling relative functions in +// CodedInputStream +const char* GetCapitalizedType(const FieldDescriptor* field, bool immutable); + +// For encodings with fixed sizes, returns that size in bytes. Otherwise +// returns -1. +int FixedSize(FieldDescriptor::Type type); + +// Comparators used to sort fields in MessageGenerator +struct FieldOrderingByNumber { + inline bool operator()(const FieldDescriptor* a, + const FieldDescriptor* b) const { + return a->number() < b->number(); + } +}; + +struct ExtensionRangeOrdering { + bool operator()(const Descriptor::ExtensionRange* a, + const Descriptor::ExtensionRange* b) const { + return a->start < b->start; + } +}; + +// Sort the fields of the given Descriptor by number into a new[]'d array +// and return it. The caller should delete the returned array. +const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor); + +// Does this message class have any packed fields? +inline bool HasPackedFields(const Descriptor* descriptor) { + for (int i = 0; i < descriptor->field_count(); i++) { + if (descriptor->field(i)->is_packed()) { + return true; + } + } + return false; +} + +// Check a message type and its sub-message types recursively to see if any of +// them has a required field. Return true if a required field is found. +bool HasRequiredFields(const Descriptor* descriptor); + +inline bool IsProto2(const FileDescriptor* descriptor) { + return descriptor->syntax() == FileDescriptor::SYNTAX_PROTO2; +} + +inline bool IsRealOneof(const FieldDescriptor* descriptor) { + return descriptor->containing_oneof() && + !descriptor->containing_oneof()->is_synthetic(); +} + +inline bool HasHazzer(const FieldDescriptor* descriptor) { + return !descriptor->is_repeated() && + (descriptor->message_type() || descriptor->has_optional_keyword() || + IsProto2(descriptor->file()) || IsRealOneof(descriptor)); +} + +inline bool HasHasbit(const FieldDescriptor* descriptor) { + // Note that currently message fields inside oneofs have hasbits. This is + // surprising, as the oneof case should avoid any need for a hasbit. But if + // you change this method to remove hasbits for oneofs, a few tests fail. + // TODO(b/124347790): remove hasbits for oneofs + return !descriptor->is_repeated() && + (descriptor->has_optional_keyword() || IsProto2(descriptor->file())); +} + +// Whether generate classes expose public PARSER instances. +inline bool ExposePublicParser(const FileDescriptor* descriptor) { + // TODO(liujisi): Mark the PARSER private in 3.1.x releases. + return descriptor->syntax() == FileDescriptor::SYNTAX_PROTO2; +} + +// Whether unknown enum values are kept (i.e., not stored in UnknownFieldSet +// but in the message and can be queried using additional getters that return +// ints. +inline bool SupportUnknownEnumValue(const FileDescriptor* descriptor) { + return descriptor->syntax() == FileDescriptor::SYNTAX_PROTO3; +} + +inline bool SupportUnknownEnumValue(const FieldDescriptor* field) { + return field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3; +} + +// Check whether a message has repeated fields. +bool HasRepeatedFields(const Descriptor* descriptor); + +inline bool IsMapEntry(const Descriptor* descriptor) { + return descriptor->options().map_entry(); +} + +inline bool IsMapField(const FieldDescriptor* descriptor) { + return descriptor->is_map(); +} + +inline bool IsAnyMessage(const Descriptor* descriptor) { + return descriptor->full_name() == "google.protobuf.Any"; +} + +inline bool IsWrappersProtoFile(const FileDescriptor* descriptor) { + return descriptor->name() == "google/protobuf/wrappers.proto"; +} + +inline bool CheckUtf8(const FieldDescriptor* descriptor) { + return descriptor->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 || + descriptor->file()->options().java_string_check_utf8(); +} + +inline std::string GeneratedCodeVersionSuffix() { + return "V3"; +} + +void WriteUInt32ToUtf16CharSequence(uint32_t number, + std::vector* output); + +inline void WriteIntToUtf16CharSequence(int value, + std::vector* output) { + WriteUInt32ToUtf16CharSequence(static_cast(value), output); +} + +// Escape a UTF-16 character so it can be embedded in a Java string literal. +void EscapeUtf16ToString(uint16_t code, std::string* output); + +// Only the lowest two bytes of the return value are used. The lowest byte +// is the integer value of a j/c/g/protobuf/FieldType enum. For the other +// byte: +// bit 0: whether the field is required. +// bit 1: whether the field requires UTF-8 validation. +// bit 2: whether the field needs isInitialized check. +// 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 +} // namespace google + +#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_kotlin_generator.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_kotlin_generator.cc new file mode 100644 index 0000000..8d262a0 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_kotlin_generator.cc @@ -0,0 +1,162 @@ +// 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. + +#include + +#include +#include +#include +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace java { + +KotlinGenerator::KotlinGenerator() {} +KotlinGenerator::~KotlinGenerator() {} + +uint64_t KotlinGenerator::GetSupportedFeatures() const { + return CodeGenerator::Feature::FEATURE_PROTO3_OPTIONAL; +} + +bool KotlinGenerator::Generate(const FileDescriptor* file, + const std::string& parameter, + GeneratorContext* context, + std::string* error) const { + // ----------------------------------------------------------------- + // parse generator options + + std::vector > options; + ParseGeneratorParameter(parameter, &options); + Options file_options; + + for (auto& option : options) { + if (option.first == "output_list_file") { + file_options.output_list_file = option.second; + } else if (option.first == "immutable") { + file_options.generate_immutable_code = true; + } else if (option.first == "mutable") { + *error = "Mutable not supported by Kotlin generator"; + return false; + } else if (option.first == "shared") { + file_options.generate_shared_code = true; + } else if (option.first == "lite") { + file_options.enforce_lite = true; + } else if (option.first == "annotate_code") { + file_options.annotate_code = true; + } else if (option.first == "annotation_list_file") { + file_options.annotation_list_file = option.second; + } else { + *error = "Unknown generator option: " + option.first; + return false; + } + } + + // By default we generate immutable code and shared code for immutable API. + if (!file_options.generate_immutable_code && + !file_options.generate_shared_code) { + file_options.generate_immutable_code = true; + file_options.generate_shared_code = true; + } + + std::vector all_files; + std::vector all_annotations; + + std::unique_ptr file_generator; + if (file_options.generate_immutable_code) { + file_generator.reset( + new FileGenerator(file, file_options, /* immutable_api = */ true)); + } + + if (!file_generator->Validate(error)) { + return false; + } + + auto open_file = [context](const std::string& filename) { + return std::unique_ptr(context->Open(filename)); + }; + std::string package_dir = JavaPackageToDir(file_generator->java_package()); + std::string kotlin_filename = package_dir; + kotlin_filename += file_generator->GetKotlinClassname(); + kotlin_filename += ".kt"; + all_files.push_back(kotlin_filename); + std::string info_full_path = kotlin_filename + ".pb.meta"; + if (file_options.annotate_code) { + all_annotations.push_back(info_full_path); + } + + // Generate main kotlin file. + auto output = open_file(kotlin_filename); + GeneratedCodeInfo annotations; + io::AnnotationProtoCollector annotation_collector( + &annotations); + io::Printer printer( + output.get(), '$', + file_options.annotate_code ? &annotation_collector : nullptr); + + file_generator->GenerateKotlinSiblings(package_dir, context, &all_files, + &all_annotations); + + if (file_options.annotate_code) { + auto info_output = open_file(info_full_path); + annotations.SerializeToZeroCopyStream(info_output.get()); + } + + // Generate output list if requested. + 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 .kt files being generated. + auto srclist_raw_output = open_file(file_options.output_list_file); + io::Printer srclist_printer(srclist_raw_output.get(), '$'); + for (auto& all_file : all_files) { + srclist_printer.Print("$filename$\n", "filename", all_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 .kt files being generated. + auto annotation_list_raw_output = + open_file(file_options.annotation_list_file); + io::Printer annotation_list_printer(annotation_list_raw_output.get(), '$'); + for (auto& all_annotation : all_annotations) { + annotation_list_printer.Print("$filename$\n", "filename", all_annotation); + } + } + + return true; +} + +} // namespace java +} // namespace compiler +} // namespace protobuf +} // namespace google diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_message_lite.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_message_lite.h new file mode 100644 index 0000000..adb0df7 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_message_lite.h @@ -0,0 +1,86 @@ +// 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: dweis@google.com (Daniel Weis) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. + +#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_LITE_H__ +#define GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_LITE_H__ + +#include +#include +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace java { + +class ImmutableMessageLiteGenerator : public MessageGenerator { + public: + ImmutableMessageLiteGenerator(const Descriptor* descriptor, Context* context); + virtual ~ImmutableMessageLiteGenerator(); + + void Generate(io::Printer* printer) override; + void GenerateInterface(io::Printer* printer) override; + void GenerateExtensionRegistrationCode(io::Printer* printer) override; + void GenerateStaticVariables(io::Printer* printer, + int* bytecode_estimate) override; + int GenerateStaticVariableInitializers(io::Printer* printer) override; + void GenerateKotlinDsl(io::Printer* printer) const override; + void GenerateKotlinMembers(io::Printer* printer) const override; + void GenerateTopLevelKotlinMembers(io::Printer* printer) const override; + + private: + void GenerateParseFromMethods(io::Printer* printer); + + void GenerateBuilder(io::Printer* printer); + void GenerateDynamicMethodNewBuilder(io::Printer* printer); + void GenerateInitializers(io::Printer* printer); + void GenerateParser(io::Printer* printer); + void GenerateConstructor(io::Printer* printer); + void GenerateDynamicMethodNewBuildMessageInfo(io::Printer* printer); + void GenerateKotlinExtensions(io::Printer* printer) const; + + Context* context_; + ClassNameResolver* name_resolver_; + FieldGeneratorMap field_generators_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableMessageLiteGenerator); +}; + +} // namespace java +} // namespace compiler +} // namespace protobuf +} // namespace google + +#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_LITE_H__ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_string_field.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_string_field.h new file mode 100644 index 0000000..efab5fe --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/java/java_string_field.h @@ -0,0 +1,160 @@ +// 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) +// Author: jonp@google.com (Jon Perlow) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. + +#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_STRING_FIELD_H__ +#define GOOGLE_PROTOBUF_COMPILER_JAVA_STRING_FIELD_H__ + +#include +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace java { +class Context; // context.h +class ClassNameResolver; // name_resolver.h +} // namespace java +} // namespace compiler +} // namespace protobuf +} // namespace google + +namespace google { +namespace protobuf { +namespace compiler { +namespace java { + +class ImmutableStringFieldGenerator : public ImmutableFieldGenerator { + public: + explicit ImmutableStringFieldGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, + int builderBitIndex, Context* context); + ~ImmutableStringFieldGenerator(); + + // implements ImmutableFieldGenerator + // --------------------------------------- + int GetNumBitsForMessage() const override; + int GetNumBitsForBuilder() const override; + void GenerateInterfaceMembers(io::Printer* printer) const override; + void GenerateMembers(io::Printer* printer) const override; + void GenerateBuilderMembers(io::Printer* printer) const override; + void GenerateInitializationCode(io::Printer* printer) const override; + void GenerateBuilderClearCode(io::Printer* printer) const override; + void GenerateMergingCode(io::Printer* printer) const override; + void GenerateBuildingCode(io::Printer* printer) const override; + void GenerateParsingCode(io::Printer* printer) const override; + void GenerateParsingDoneCode(io::Printer* printer) const override; + void GenerateSerializationCode(io::Printer* printer) const override; + void GenerateSerializedSizeCode(io::Printer* printer) const override; + void GenerateFieldBuilderInitializationCode( + io::Printer* printer) const override; + void GenerateEqualsCode(io::Printer* printer) const override; + void GenerateHashCode(io::Printer* printer) const override; + void GenerateKotlinDslMembers(io::Printer* printer) const override; + + std::string GetBoxedType() const override; + + protected: + const FieldDescriptor* descriptor_; + std::map variables_; + ClassNameResolver* name_resolver_; + + private: + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableStringFieldGenerator); +}; + +class ImmutableStringOneofFieldGenerator + : public ImmutableStringFieldGenerator { + public: + ImmutableStringOneofFieldGenerator(const FieldDescriptor* descriptor, + int messageBitIndex, int builderBitIndex, + Context* context); + ~ImmutableStringOneofFieldGenerator(); + + private: + void GenerateMembers(io::Printer* printer) const override; + void GenerateBuilderMembers(io::Printer* printer) const override; + void GenerateMergingCode(io::Printer* printer) const override; + void GenerateBuildingCode(io::Printer* printer) const override; + void GenerateParsingCode(io::Printer* printer) const override; + void GenerateSerializationCode(io::Printer* printer) const override; + void GenerateSerializedSizeCode(io::Printer* printer) const override; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableStringOneofFieldGenerator); +}; + +class RepeatedImmutableStringFieldGenerator : public ImmutableFieldGenerator { + public: + explicit RepeatedImmutableStringFieldGenerator( + const FieldDescriptor* descriptor, int messageBitIndex, + int builderBitIndex, Context* context); + ~RepeatedImmutableStringFieldGenerator() override; + + // implements ImmutableFieldGenerator --------------------------------------- + int GetNumBitsForMessage() const override; + int GetNumBitsForBuilder() const override; + void GenerateInterfaceMembers(io::Printer* printer) const override; + void GenerateMembers(io::Printer* printer) const override; + void GenerateBuilderMembers(io::Printer* printer) const override; + void GenerateInitializationCode(io::Printer* printer) const override; + void GenerateBuilderClearCode(io::Printer* printer) const override; + void GenerateMergingCode(io::Printer* printer) const override; + void GenerateBuildingCode(io::Printer* printer) const override; + void GenerateParsingCode(io::Printer* printer) const override; + void GenerateParsingDoneCode(io::Printer* printer) const override; + void GenerateSerializationCode(io::Printer* printer) const override; + void GenerateSerializedSizeCode(io::Printer* printer) const override; + void GenerateFieldBuilderInitializationCode( + io::Printer* printer) const override; + void GenerateEqualsCode(io::Printer* printer) const override; + void GenerateHashCode(io::Printer* printer) const override; + void GenerateKotlinDslMembers(io::Printer* printer) const override; + + std::string GetBoxedType() const override; + + private: + const FieldDescriptor* descriptor_; + std::map variables_; + ClassNameResolver* name_resolver_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedImmutableStringFieldGenerator); +}; + +} // namespace java +} // namespace compiler +} // namespace protobuf +} // namespace google + +#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_STRING_FIELD_H__ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/ruby/ruby_generated_code_proto2_pb.rb b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/ruby/ruby_generated_code_proto2_pb.rb new file mode 100644 index 0000000..44d3196 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/ruby/ruby_generated_code_proto2_pb.rb @@ -0,0 +1,80 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: ruby_generated_code_proto2.proto + +require 'google/protobuf' + +require 'ruby_generated_code_proto2_import_pb' + +Google::Protobuf::DescriptorPool.generated_pool.build do + add_file("ruby_generated_code_proto2.proto", :syntax => :proto2) do + add_message "A.B.C.TestMessage" do + optional :optional_int32, :int32, 1, default: 1 + optional :optional_int64, :int64, 2, default: 2 + optional :optional_uint32, :uint32, 3, default: 3 + optional :optional_uint64, :uint64, 4, default: 4 + optional :optional_bool, :bool, 5, default: true + optional :optional_double, :double, 6, default: 6 + optional :optional_float, :float, 7, default: 7 + optional :optional_string, :string, 8, default: "default str" + optional :optional_bytes, :bytes, 9, default: "\x00\x01\x02\x40\x66\x75\x62\x61\x72".force_encoding("ASCII-8BIT") + optional :optional_enum, :enum, 10, "A.B.C.TestEnum", default: 1 + optional :optional_msg, :message, 11, "A.B.C.TestMessage" + optional :optional_proto2_submessage, :message, 12, "A.B.C.TestImportedMessage" + repeated :repeated_int32, :int32, 21 + repeated :repeated_int64, :int64, 22 + repeated :repeated_uint32, :uint32, 23 + repeated :repeated_uint64, :uint64, 24 + repeated :repeated_bool, :bool, 25 + repeated :repeated_double, :double, 26 + repeated :repeated_float, :float, 27 + repeated :repeated_string, :string, 28 + repeated :repeated_bytes, :bytes, 29 + repeated :repeated_enum, :enum, 30, "A.B.C.TestEnum" + repeated :repeated_msg, :message, 31, "A.B.C.TestMessage" + required :required_int32, :int32, 41 + required :required_int64, :int64, 42 + required :required_uint32, :uint32, 43 + required :required_uint64, :uint64, 44 + required :required_bool, :bool, 45 + required :required_double, :double, 46 + required :required_float, :float, 47 + required :required_string, :string, 48 + required :required_bytes, :bytes, 49 + required :required_enum, :enum, 50, "A.B.C.TestEnum" + required :required_msg, :message, 51, "A.B.C.TestMessage" + optional :nested_message, :message, 80, "A.B.C.TestMessage.NestedMessage" + oneof :my_oneof do + optional :oneof_int32, :int32, 61 + optional :oneof_int64, :int64, 62 + optional :oneof_uint32, :uint32, 63 + optional :oneof_uint64, :uint64, 64 + optional :oneof_bool, :bool, 65 + optional :oneof_double, :double, 66 + optional :oneof_float, :float, 67 + optional :oneof_string, :string, 68 + optional :oneof_bytes, :bytes, 69 + optional :oneof_enum, :enum, 70, "A.B.C.TestEnum" + optional :oneof_msg, :message, 71, "A.B.C.TestMessage" + end + end + add_message "A.B.C.TestMessage.NestedMessage" do + optional :foo, :int32, 1 + end + add_enum "A.B.C.TestEnum" do + value :Default, 0 + value :A, 1 + value :B, 2 + value :C, 3 + end + end +end + +module A + module B + module C + TestMessage = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("A.B.C.TestMessage").msgclass + TestMessage::NestedMessage = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("A.B.C.TestMessage.NestedMessage").msgclass + TestEnum = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("A.B.C.TestEnum").enummodule + end + end +end diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_legacy.proto b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_legacy.proto new file mode 100644 index 0000000..7a0d260 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/ruby/ruby_generated_pkg_explicit_legacy.proto @@ -0,0 +1,9 @@ +syntax = "proto3"; + +package one.two.a_three.and; + +option ruby_package = "AA.BB.CC"; + +message Four { + string another_string = 1; +} diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/subprocess.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/subprocess.cc new file mode 100644 index 0000000..7e59cd7 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/compiler/subprocess.cc @@ -0,0 +1,475 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: kenton@google.com (Kenton Varda) + +#include + +#include +#include +#include + +#ifndef _WIN32 +#include +#include +#include +#include +#endif + +#include +#include +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { + +namespace { +char* portable_strdup(const char* s) { + char* ns = (char*)malloc(strlen(s) + 1); + if (ns != NULL) { + strcpy(ns, s); + } + return ns; +} +} // namespace + +#ifdef _WIN32 + +static void CloseHandleOrDie(HANDLE handle) { + if (!CloseHandle(handle)) { + GOOGLE_LOG(FATAL) << "CloseHandle: " + << Subprocess::Win32ErrorMessage(GetLastError()); + } +} + +Subprocess::Subprocess() + : process_start_error_(ERROR_SUCCESS), + child_handle_(NULL), + child_stdin_(NULL), + child_stdout_(NULL) {} + +Subprocess::~Subprocess() { + if (child_stdin_ != NULL) { + CloseHandleOrDie(child_stdin_); + } + if (child_stdout_ != NULL) { + CloseHandleOrDie(child_stdout_); + } +} + +void Subprocess::Start(const std::string& program, SearchMode search_mode) { + // Create the pipes. + HANDLE stdin_pipe_read; + HANDLE stdin_pipe_write; + HANDLE stdout_pipe_read; + HANDLE stdout_pipe_write; + + if (!CreatePipe(&stdin_pipe_read, &stdin_pipe_write, NULL, 0)) { + GOOGLE_LOG(FATAL) << "CreatePipe: " << Win32ErrorMessage(GetLastError()); + } + if (!CreatePipe(&stdout_pipe_read, &stdout_pipe_write, NULL, 0)) { + GOOGLE_LOG(FATAL) << "CreatePipe: " << Win32ErrorMessage(GetLastError()); + } + + // Make child side of the pipes inheritable. + if (!SetHandleInformation(stdin_pipe_read, HANDLE_FLAG_INHERIT, + HANDLE_FLAG_INHERIT)) { + GOOGLE_LOG(FATAL) << "SetHandleInformation: " + << Win32ErrorMessage(GetLastError()); + } + if (!SetHandleInformation(stdout_pipe_write, HANDLE_FLAG_INHERIT, + HANDLE_FLAG_INHERIT)) { + GOOGLE_LOG(FATAL) << "SetHandleInformation: " + << Win32ErrorMessage(GetLastError()); + } + + // Setup STARTUPINFO to redirect handles. + STARTUPINFOA startup_info; + ZeroMemory(&startup_info, sizeof(startup_info)); + startup_info.cb = sizeof(startup_info); + startup_info.dwFlags = STARTF_USESTDHANDLES; + startup_info.hStdInput = stdin_pipe_read; + startup_info.hStdOutput = stdout_pipe_write; + startup_info.hStdError = GetStdHandle(STD_ERROR_HANDLE); + + if (startup_info.hStdError == INVALID_HANDLE_VALUE) { + GOOGLE_LOG(FATAL) << "GetStdHandle: " << Win32ErrorMessage(GetLastError()); + } + + // Invoking cmd.exe allows for '.bat' files from the path as well as '.exe'. + // Using a malloc'ed string because CreateProcess() can mutate its second + // parameter. + char* command_line = + portable_strdup(("cmd.exe /c \"" + program + "\"").c_str()); + + // Create the process. + PROCESS_INFORMATION process_info; + + if (CreateProcessA((search_mode == SEARCH_PATH) ? NULL : program.c_str(), + (search_mode == SEARCH_PATH) ? command_line : NULL, + NULL, // process security attributes + NULL, // thread security attributes + TRUE, // inherit handles? + 0, // obscure creation flags + NULL, // environment (inherit from parent) + NULL, // current directory (inherit from parent) + &startup_info, &process_info)) { + child_handle_ = process_info.hProcess; + CloseHandleOrDie(process_info.hThread); + child_stdin_ = stdin_pipe_write; + child_stdout_ = stdout_pipe_read; + } else { + process_start_error_ = GetLastError(); + CloseHandleOrDie(stdin_pipe_write); + CloseHandleOrDie(stdout_pipe_read); + } + + CloseHandleOrDie(stdin_pipe_read); + CloseHandleOrDie(stdout_pipe_write); + free(command_line); +} + +bool Subprocess::Communicate(const Message& input, Message* output, + std::string* error) { + if (process_start_error_ != ERROR_SUCCESS) { + *error = Win32ErrorMessage(process_start_error_); + return false; + } + + GOOGLE_CHECK(child_handle_ != NULL) << "Must call Start() first."; + + std::string input_data = input.SerializeAsString(); + std::string output_data; + + int input_pos = 0; + + while (child_stdout_ != NULL) { + HANDLE handles[2]; + int handle_count = 0; + + if (child_stdin_ != NULL) { + handles[handle_count++] = child_stdin_; + } + if (child_stdout_ != NULL) { + handles[handle_count++] = child_stdout_; + } + + DWORD wait_result = + WaitForMultipleObjects(handle_count, handles, FALSE, INFINITE); + + HANDLE signaled_handle = NULL; + if (wait_result >= WAIT_OBJECT_0 && + wait_result < WAIT_OBJECT_0 + handle_count) { + signaled_handle = handles[wait_result - WAIT_OBJECT_0]; + } else if (wait_result == WAIT_FAILED) { + GOOGLE_LOG(FATAL) << "WaitForMultipleObjects: " + << Win32ErrorMessage(GetLastError()); + } else { + GOOGLE_LOG(FATAL) << "WaitForMultipleObjects: Unexpected return code: " + << wait_result; + } + + if (signaled_handle == child_stdin_) { + DWORD n; + if (!WriteFile(child_stdin_, input_data.data() + input_pos, + input_data.size() - input_pos, &n, NULL)) { + // Child closed pipe. Presumably it will report an error later. + // Pretend we're done for now. + input_pos = input_data.size(); + } else { + input_pos += n; + } + + if (input_pos == input_data.size()) { + // We're done writing. Close. + CloseHandleOrDie(child_stdin_); + child_stdin_ = NULL; + } + } else if (signaled_handle == child_stdout_) { + char buffer[4096]; + DWORD n; + + if (!ReadFile(child_stdout_, buffer, sizeof(buffer), &n, NULL)) { + // We're done reading. Close. + CloseHandleOrDie(child_stdout_); + child_stdout_ = NULL; + } else { + output_data.append(buffer, n); + } + } + } + + if (child_stdin_ != NULL) { + // Child did not finish reading input before it closed the output. + // Presumably it exited with an error. + CloseHandleOrDie(child_stdin_); + child_stdin_ = NULL; + } + + DWORD wait_result = WaitForSingleObject(child_handle_, INFINITE); + + if (wait_result == WAIT_FAILED) { + GOOGLE_LOG(FATAL) << "WaitForSingleObject: " + << Win32ErrorMessage(GetLastError()); + } else if (wait_result != WAIT_OBJECT_0) { + GOOGLE_LOG(FATAL) << "WaitForSingleObject: Unexpected return code: " + << wait_result; + } + + DWORD exit_code; + if (!GetExitCodeProcess(child_handle_, &exit_code)) { + GOOGLE_LOG(FATAL) << "GetExitCodeProcess: " + << Win32ErrorMessage(GetLastError()); + } + + CloseHandleOrDie(child_handle_); + child_handle_ = NULL; + + if (exit_code != 0) { + *error = strings::Substitute("Plugin failed with status code $0.", exit_code); + return false; + } + + if (!output->ParseFromString(output_data)) { + *error = "Plugin output is unparseable: " + CEscape(output_data); + return false; + } + + return true; +} + +std::string Subprocess::Win32ErrorMessage(DWORD error_code) { + char* message; + + // WTF? + FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, error_code, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), + (LPSTR)&message, // NOT A BUG! + 0, NULL); + + std::string result = message; + LocalFree(message); + return result; +} + +// =================================================================== + +#else // _WIN32 + +Subprocess::Subprocess() + : child_pid_(-1), child_stdin_(-1), child_stdout_(-1) {} + +Subprocess::~Subprocess() { + if (child_stdin_ != -1) { + close(child_stdin_); + } + if (child_stdout_ != -1) { + close(child_stdout_); + } +} + +void Subprocess::Start(const std::string& program, SearchMode search_mode) { + // Note that we assume that there are no other threads, thus we don't have to + // do crazy stuff like using socket pairs or avoiding libc locks. + + // [0] is read end, [1] is write end. + int stdin_pipe[2]; + int stdout_pipe[2]; + + GOOGLE_CHECK(pipe(stdin_pipe) != -1); + GOOGLE_CHECK(pipe(stdout_pipe) != -1); + + char* argv[2] = {portable_strdup(program.c_str()), NULL}; + + child_pid_ = fork(); + if (child_pid_ == -1) { + GOOGLE_LOG(FATAL) << "fork: " << strerror(errno); + } else if (child_pid_ == 0) { + // We are the child. + dup2(stdin_pipe[0], STDIN_FILENO); + dup2(stdout_pipe[1], STDOUT_FILENO); + + close(stdin_pipe[0]); + close(stdin_pipe[1]); + close(stdout_pipe[0]); + close(stdout_pipe[1]); + + switch (search_mode) { + case SEARCH_PATH: + execvp(argv[0], argv); + break; + case EXACT_NAME: + execv(argv[0], argv); + break; + } + + // Write directly to STDERR_FILENO to avoid stdio code paths that may do + // stuff that is unsafe here. + int ignored; + ignored = write(STDERR_FILENO, argv[0], strlen(argv[0])); + const char* message = + ": program not found or is not executable\n" + "Please specify a program using absolute path or make sure " + "the program is available in your PATH system variable\n"; + ignored = write(STDERR_FILENO, message, strlen(message)); + (void)ignored; + + // Must use _exit() rather than exit() to avoid flushing output buffers + // that will also be flushed by the parent. + _exit(1); + } else { + free(argv[0]); + + close(stdin_pipe[0]); + close(stdout_pipe[1]); + + child_stdin_ = stdin_pipe[1]; + child_stdout_ = stdout_pipe[0]; + } +} + +bool Subprocess::Communicate(const Message& input, Message* output, + std::string* error) { + GOOGLE_CHECK_NE(child_stdin_, -1) << "Must call Start() first."; + + // The "sighandler_t" typedef is GNU-specific, so define our own. + typedef void SignalHandler(int); + + // Make sure SIGPIPE is disabled so that if the child dies it doesn't kill us. + SignalHandler* old_pipe_handler = signal(SIGPIPE, SIG_IGN); + + std::string input_data = input.SerializeAsString(); + std::string output_data; + + int input_pos = 0; + int max_fd = std::max(child_stdin_, child_stdout_); + + while (child_stdout_ != -1) { + fd_set read_fds; + fd_set write_fds; + FD_ZERO(&read_fds); + FD_ZERO(&write_fds); + if (child_stdout_ != -1) { + FD_SET(child_stdout_, &read_fds); + } + if (child_stdin_ != -1) { + FD_SET(child_stdin_, &write_fds); + } + + if (select(max_fd + 1, &read_fds, &write_fds, NULL, NULL) < 0) { + if (errno == EINTR) { + // Interrupted by signal. Try again. + continue; + } else { + GOOGLE_LOG(FATAL) << "select: " << strerror(errno); + } + } + + if (child_stdin_ != -1 && FD_ISSET(child_stdin_, &write_fds)) { + int n = write(child_stdin_, input_data.data() + input_pos, + input_data.size() - input_pos); + if (n < 0) { + // Child closed pipe. Presumably it will report an error later. + // Pretend we're done for now. + input_pos = input_data.size(); + } else { + input_pos += n; + } + + if (input_pos == input_data.size()) { + // We're done writing. Close. + close(child_stdin_); + child_stdin_ = -1; + } + } + + if (child_stdout_ != -1 && FD_ISSET(child_stdout_, &read_fds)) { + char buffer[4096]; + int n = read(child_stdout_, buffer, sizeof(buffer)); + + if (n > 0) { + output_data.append(buffer, n); + } else { + // We're done reading. Close. + close(child_stdout_); + child_stdout_ = -1; + } + } + } + + if (child_stdin_ != -1) { + // Child did not finish reading input before it closed the output. + // Presumably it exited with an error. + close(child_stdin_); + child_stdin_ = -1; + } + + int status; + while (waitpid(child_pid_, &status, 0) == -1) { + if (errno != EINTR) { + GOOGLE_LOG(FATAL) << "waitpid: " << strerror(errno); + } + } + + // Restore SIGPIPE handling. + signal(SIGPIPE, old_pipe_handler); + + if (WIFEXITED(status)) { + if (WEXITSTATUS(status) != 0) { + int error_code = WEXITSTATUS(status); + *error = + strings::Substitute("Plugin failed with status code $0.", error_code); + return false; + } + } else if (WIFSIGNALED(status)) { + int signal = WTERMSIG(status); + *error = strings::Substitute("Plugin killed by signal $0.", signal); + return false; + } else { + *error = "Neither WEXITSTATUS nor WTERMSIG is true?"; + return false; + } + + if (!output->ParseFromString(output_data)) { + *error = "Plugin output is unparseable: " + CEscape(output_data); + return false; + } + + return true; +} + +#endif // !_WIN32 + +} // namespace compiler +} // namespace protobuf +} // namespace google diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/inlined_string_field.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/inlined_string_field.h new file mode 100644 index 0000000..e4ab359 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/inlined_string_field.h @@ -0,0 +1,384 @@ +// 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 +#include +#include +#include +#include +#include + +// Must be included last. +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif + +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. +// +// 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. +// +// InlinedStringField has a donating mechanism that allows string buffer +// allocated on arena. A string is donated means both the string container and +// the data buffer are on arena. The donating mechanism here is similar to the +// one in ArenaStringPtr with some differences: +// +// When an InlinedStringField is constructed, the donating state is true. This +// is because the string container is directly stored in the message on the +// arena: +// +// Construction: donated=true +// Arena: +// +-----------------------+ +// |Message foo: | +// | +-------------------+ | +// | |InlinedStringField:| | +// | | +-----+ | | +// | | | | | | | | +// | | +-----+ | | +// | +-------------------+ | +// +-----------------------+ +// +// When lvalue Set is called, the donating state is still true. String data will +// be allocated on the arena: +// +// Lvalue Set: donated=true +// Arena: +// +-----------------------+ +// |Message foo: | +// | +-------------------+ | +// | |InlinedStringField:| | +// | | +-----+ | | +// | | | | | | | | +// | | +|----+ | | +// | +--|----------------+ | +// | V | +// | +----------------+ | +// | |'f','o','o',... | | +// | +----------------+ | +// +-----------------------+ +// +// Some operations will undonate a donated string, including: Mutable, +// SetAllocated, Rvalue Set, and Swap with a non-donated string. +// +// For more details of the donating states transitions, go/pd-inlined-string. +class PROTOBUF_EXPORT InlinedStringField { + public: + InlinedStringField() { Init(); } + inline void Init() { new (get_mutable()) std::string(); } + // Add the dummy parameter just to make InlinedStringField(nullptr) + // unambiguous. + constexpr InlinedStringField( + const ExplicitlyConstructed* /*default_value*/, + bool /*dummy*/) + : value_{} {} + explicit InlinedStringField(const std::string& default_value); + explicit InlinedStringField(Arena* arena); + ~InlinedStringField() { Destruct(); } + + // Lvalue Set. To save space, we pack the donating states of multiple + // InlinedStringFields into an uint32_t `donating_states`. The `mask` + // indicates the position of the bit for this InlinedStringField. `donated` is + // whether this field is donated. + // + // The caller should guarantee that: + // + // `donated == ((donating_states & ~mask) != 0)` + // + // This method never changes the `donating_states`. + void Set(const std::string* default_value, ConstStringParam value, + Arena* arena, bool donated, uint32_t* /*donating_states*/, + uint32_t /*mask*/) { + (void)arena; + (void)donated; + SetNoArena(default_value, value); + } + + // Rvalue Set. If this field is donated, this method will undonate this field + // by mutating the `donating_states` according to `mask`. + void Set(const std::string* default_value, std::string&& value, Arena* arena, + bool donated, uint32_t* donating_states, uint32_t mask); + + template + void Set(FirstParam p1, const char* str, ::google::protobuf::Arena* arena, bool donated, + uint32_t* donating_states, uint32_t mask) { + Set(p1, ConstStringParam(str), arena, donated, donating_states, mask); + } + + template + void Set(FirstParam p1, const char* str, size_t size, ::google::protobuf::Arena* arena, + bool donated, uint32_t* donating_states, uint32_t mask) { + ConstStringParam sp{str, size}; // for string_view and `const string &` + Set(p1, sp, arena, donated, donating_states, mask); + } + + template + void Set(FirstParam p1, + std::reference_wrapper const_string_ref, + ::google::protobuf::Arena* arena, bool donated, uint32_t* donating_states, + uint32_t mask) { + Set(p1, const_string_ref.get(), arena, donated, donating_states, mask); + } + + template + void SetBytes(FirstParam p1, SecondParam&& p2, ::google::protobuf::Arena* arena, + bool donated, uint32_t* donating_states, uint32_t mask) { + Set(p1, static_cast(p2), arena, donated, donating_states, + mask); + } + + template + void SetBytes(FirstParam p1, const void* str, size_t size, + ::google::protobuf::Arena* arena, bool donated, uint32_t* donating_states, + uint32_t mask) { + // Must work whether ConstStringParam is string_view or `const string &` + ConstStringParam sp{static_cast(str), size}; + Set(p1, sp, arena, donated, donating_states, mask); + } + + PROTOBUF_NDEBUG_INLINE void SetNoArena(const std::string* default_value, + StringPiece value); + PROTOBUF_NDEBUG_INLINE void SetNoArena(const std::string* default_value, + std::string&& value); + + // Basic accessors. + PROTOBUF_NDEBUG_INLINE const std::string& Get() const { return GetNoArena(); } + PROTOBUF_NDEBUG_INLINE const std::string& GetNoArena() const; + + // Mutable returns a std::string* instance that is heap-allocated. If this + // field is donated, this method undonates this field by mutating the + // `donating_states` according to `mask`, and copies the content of the + // original string to the returning string. + std::string* Mutable(const LazyString& default_value, Arena* arena, + bool donated, uint32_t* donating_states, uint32_t mask); + std::string* Mutable(ArenaStringPtr::EmptyDefault, Arena* arena, bool donated, + uint32_t* donating_states, uint32_t mask); + + // Release returns a std::string* instance that is heap-allocated and is not + // Own()'d by any arena. If the field is not set, this returns nullptr. The + // caller retains ownership. Clears this field back to nullptr state. Used to + // implement release_() methods on generated classes. + PROTOBUF_NODISCARD std::string* Release(const std::string* default_value, + Arena* arena, bool donated); + PROTOBUF_NODISCARD std::string* ReleaseNonDefault( + const std::string* default_value, Arena* arena); + std::string* ReleaseNonDefaultNoArena(const std::string* default_value); + + // Takes a std::string that is heap-allocated, and takes ownership. The + // std::string's destructor is registered with the arena. Used to implement + // set_allocated_ in generated classes. + // + // If this field is donated, this method undonates this field by mutating the + // `donating_states` according to `mask`. + void SetAllocated(const std::string* default_value, std::string* value, + Arena* arena, bool donated, uint32_t* donating_states, + uint32_t mask); + + void SetAllocatedNoArena(const std::string* default_value, + std::string* value); + + // When one of `this` and `from` is donated and the other is not donated, this + // method will undonate the donated one and swap the two heap-allocated + // strings. + PROTOBUF_NDEBUG_INLINE void Swap(InlinedStringField* from, + const std::string* default_value, + Arena* arena, bool donated, + bool from_donated, uint32_t* donating_states, + uint32_t* from_donating_states, + uint32_t mask); + + // Frees storage (if not on an arena). + PROTOBUF_NDEBUG_INLINE void Destroy(const std::string* default_value, + Arena* arena) { + if (arena == nullptr) { + DestroyNoArena(default_value); + } + } + PROTOBUF_NDEBUG_INLINE void DestroyNoArena(const std::string* default_value); + + // Clears content, but keeps allocated std::string, to avoid the overhead of + // heap operations. After this returns, the content (as seen by the user) will + // always be the empty std::string. + PROTOBUF_NDEBUG_INLINE void ClearToEmpty() { ClearNonDefaultToEmpty(); } + PROTOBUF_NDEBUG_INLINE void ClearNonDefaultToEmpty() { + get_mutable()->clear(); + } + + // Clears content, but keeps allocated std::string if arena != nullptr, to + // avoid the overhead of heap operations. After this returns, the content (as + // seen by the user) will always be equal to |default_value|. + void ClearToDefault(const LazyString& default_value, Arena* arena, + bool donated); + + // Returns a mutable pointer, but doesn't initialize the string to the + // default value. + PROTOBUF_NDEBUG_INLINE std::string* MutableNoArenaNoDefault( + const std::string* /*default_value*/); + + // Generated code / reflection only! Returns a mutable pointer to the string. + PROTOBUF_NDEBUG_INLINE std::string* UnsafeMutablePointer(); + + // InlinedStringField doesn't have things like the `default_value` pointer in + // ArenaStringPtr. + bool IsDefault(const std::string* /*default_value*/) const { return false; } + + private: + void Destruct() { get_mutable()->~basic_string(); } + + PROTOBUF_NDEBUG_INLINE std::string* get_mutable(); + PROTOBUF_NDEBUG_INLINE const std::string* get_const() const; + + alignas(std::string) char value_[sizeof(std::string)]; + + std::string* MutableSlow(::google::protobuf::Arena* arena, bool donated, + uint32_t* donating_states, uint32_t mask); + + + // When constructed in an Arena, we want our destructor to be skipped. + friend class ::google::protobuf::Arena; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; +}; + +inline std::string* InlinedStringField::get_mutable() { + return reinterpret_cast(&value_); +} + +inline const std::string* InlinedStringField::get_const() const { + return reinterpret_cast(&value_); +} + +inline InlinedStringField::InlinedStringField( + const std::string& default_value) { + new (get_mutable()) std::string(default_value); +} + +inline InlinedStringField::InlinedStringField(Arena* arena) { + Init(); + if (arena != nullptr) { + arena->OwnDestructor(get_mutable()); + } +} + +inline const std::string& InlinedStringField::GetNoArena() const { + return *get_const(); +} + +inline void InlinedStringField::SetAllocatedNoArena( + const std::string* /*default_value*/, std::string* value) { + if (value == nullptr) { + // Currently, inlined string field can't have non empty default. + get_mutable()->clear(); + } else { + get_mutable()->assign(std::move(*value)); + 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 std::string* InlinedStringField::ReleaseNonDefaultNoArena( + const std::string* /*default_value*/) { + // Currently, inlined string field can't have non empty default. + auto* released = new std::string(); + get_mutable()->swap(*released); + return released; +} + +inline void InlinedStringField::SetNoArena(const std::string* /*default_value*/, + StringPiece value) { + get_mutable()->assign(value.data(), value.length()); +} + +inline void InlinedStringField::SetNoArena(const std::string* /*default_value*/, + std::string&& value) { + get_mutable()->assign(std::move(value)); +} + +inline void InlinedStringField::Swap( + InlinedStringField* from, const std::string* /*default_value*/, + Arena* arena, bool donated, bool from_donated, uint32_t* donating_states, + uint32_t* from_donating_states, uint32_t mask) { +#ifdef GOOGLE_PROTOBUF_INTERNAL_DONATE_STEAL_INLINE + // If one is donated and the other is not, undonate the donated one. + if (donated && !from_donated) { + MutableSlow(arena, donated, donating_states, mask); + } else if (!donated && from_donated) { + from->MutableSlow(arena, from_donated, from_donating_states, mask); + } + // Then, swap the two undonated strings. +#else + (void)arena; + (void)donated; + (void)from_donated; + (void)donating_states; + (void)from_donating_states; + (void)mask; +#endif + get_mutable()->swap(*from->get_mutable()); +} + +inline std::string* InlinedStringField::MutableNoArenaNoDefault( + const std::string*) { + return get_mutable(); +} + +inline std::string* InlinedStringField::UnsafeMutablePointer() { + return get_mutable(); +} + +} // namespace internal +} // namespace protobuf +} // namespace google + +#include + +#endif // GOOGLE_PROTOBUF_INLINED_STRING_FIELD_H__ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/io/io_win32.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/io/io_win32.cc new file mode 100644 index 0000000..ed8ab19 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/io/io_win32.cc @@ -0,0 +1,470 @@ +// 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: laszlocsomor@google.com (Laszlo Csomor) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. + +// Implementation for long-path-aware open/mkdir/access/etc. on Windows, as well +// as for the supporting utility functions. +// +// These functions convert the input path to an absolute Windows path +// with "\\?\" prefix, then pass that to _wopen/_wmkdir/_waccess/etc. +// (declared in ) respectively. This allows working with files/directories +// whose paths are longer than MAX_PATH (260 chars). +// +// This file is only used on Windows, it's empty on other platforms. + +#if defined(_WIN32) && !defined(_XBOX_ONE) + +// Comment this out to fall back to using the ANSI versions (open, mkdir, ...) +// instead of the Unicode ones (_wopen, _wmkdir, ...). Doing so can be useful to +// debug failing tests if that's caused by the long path support. +#define SUPPORT_LONGPATHS + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN 1 +#endif + +#include + +#include +#include +#include +#include + +namespace google { +namespace protobuf { +namespace io { +namespace win32 { +namespace { + +using std::string; +using std::wstring; + +template +struct CharTraits { + static bool is_alpha(char_type ch); +}; + +template <> +struct CharTraits { + static bool is_alpha(char ch) { return isalpha(ch); } +}; + +template <> +struct CharTraits { + static bool is_alpha(wchar_t ch) { return iswalpha(ch); } +}; + +template +bool null_or_empty(const char_type* s) { + return s == nullptr || *s == 0; +} + +// Returns true if the path starts with a drive letter, e.g. "c:". +// Note that this won't check for the "\" after the drive letter, so this also +// returns true for "c:foo" (which is "c:\${PWD}\foo"). +// This check requires that a path not have a longpath prefix ("\\?\"). +template +bool has_drive_letter(const char_type* ch) { + return CharTraits::is_alpha(ch[0]) && ch[1] == ':'; +} + +// Returns true if the path starts with a longpath prefix ("\\?\"). +template +bool has_longpath_prefix(const char_type* path) { + return path[0] == '\\' && path[1] == '\\' && path[2] == '?' && + path[3] == '\\'; +} + +template +bool is_separator(char_type c) { + return c == '/' || c == '\\'; +} + +// Returns true if the path starts with a drive specifier (e.g. "c:\"). +template +bool is_path_absolute(const char_type* path) { + return has_drive_letter(path) && is_separator(path[2]); +} + +template +bool is_drive_relative(const char_type* path) { + return has_drive_letter(path) && (path[2] == 0 || !is_separator(path[2])); +} + +wstring join_paths(const wstring& path1, const wstring& path2) { + if (path1.empty() || is_path_absolute(path2.c_str()) || + has_longpath_prefix(path2.c_str())) { + return path2; + } + if (path2.empty()) { + return path1; + } + + if (is_separator(path1[path1.size() - 1])) { + return is_separator(path2[0]) ? (path1 + path2.substr(1)) + : (path1 + path2); + } else { + return is_separator(path2[0]) ? (path1 + path2) + : (path1 + L'\\' + path2); + } +} + +wstring normalize(wstring path) { + if (has_longpath_prefix(path.c_str())) { + path = path.substr(4); + } + + static const wstring dot(L"."); + static const wstring dotdot(L".."); + const WCHAR* p = path.c_str(); + + std::vector segments; + int segment_start = -1; + // Find the path segments in `path` (separated by "/"). + for (int i = 0;; ++i) { + if (!is_separator(p[i]) && p[i] != L'\0') { + // The current character does not end a segment, so start one unless it's + // already started. + if (segment_start < 0) { + segment_start = i; + } + } else if (segment_start >= 0 && i > segment_start) { + // The current character is "/" or "\0", so this ends a segment. + // Add that to `segments` if there's anything to add; handle "." and "..". + wstring segment(p, segment_start, i - segment_start); + segment_start = -1; + if (segment == dotdot) { + if (!segments.empty() && + (!has_drive_letter(segments[0].c_str()) || segments.size() > 1)) { + segments.pop_back(); + } + } else if (segment != dot && !segment.empty()) { + segments.push_back(segment); + } + } + if (p[i] == L'\0') { + break; + } + } + + // Handle the case when `path` is just a drive specifier (or some degenerate + // form of it, e.g. "c:\.."). + if (segments.size() == 1 && segments[0].size() == 2 && + has_drive_letter(segments[0].c_str())) { + return segments[0] + L'\\'; + } + + // Join all segments. + bool first = true; + std::wstringstream result; + for (int i = 0; i < segments.size(); ++i) { + if (!first) { + result << L'\\'; + } + first = false; + result << segments[i]; + } + // Preserve trailing separator if the input contained it. + if (!path.empty() && is_separator(p[path.size() - 1])) { + result << L'\\'; + } + return result.str(); +} + +bool as_windows_path(const char* path, wstring* result) { + if (null_or_empty(path)) { + result->clear(); + return true; + } + wstring wpath; + if (!strings::utf8_to_wcs(path, &wpath)) { + return false; + } + if (has_longpath_prefix(wpath.c_str())) { + *result = wpath; + return true; + } + if (is_separator(path[0]) || is_drive_relative(path)) { + return false; + } + + + if (!is_path_absolute(wpath.c_str())) { + int size = ::GetCurrentDirectoryW(0, nullptr); + if (size == 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) { + return false; + } + std::unique_ptr wcwd(new WCHAR[size]); + ::GetCurrentDirectoryW(size, wcwd.get()); + wpath = join_paths(wcwd.get(), wpath); + } + wpath = normalize(wpath); + if (!has_longpath_prefix(wpath.c_str())) { + // Add the "\\?\" prefix unconditionally. This way we prevent the Win32 API + // from processing the path and "helpfully" removing trailing dots from the + // path, for example. + // See https://github.com/bazelbuild/bazel/issues/2935 + wpath = wstring(L"\\\\?\\") + wpath; + } + *result = wpath; + return true; +} + +} // namespace + +int open(const char* path, int flags, int mode) { +#ifdef SUPPORT_LONGPATHS + wstring wpath; + if (!as_windows_path(path, &wpath)) { + errno = ENOENT; + return -1; + } + return ::_wopen(wpath.c_str(), flags, mode); +#else + return ::_open(path, flags, mode); +#endif +} + +int mkdir(const char* path, int /*_mode*/) { +#ifdef SUPPORT_LONGPATHS + wstring wpath; + if (!as_windows_path(path, &wpath)) { + errno = ENOENT; + return -1; + } + return ::_wmkdir(wpath.c_str()); +#else // not SUPPORT_LONGPATHS + return ::_mkdir(path); +#endif // not SUPPORT_LONGPATHS +} + +int access(const char* path, int mode) { +#ifdef SUPPORT_LONGPATHS + wstring wpath; + if (!as_windows_path(path, &wpath)) { + errno = ENOENT; + return -1; + } + return ::_waccess(wpath.c_str(), mode); +#else + return ::_access(path, mode); +#endif +} + +int chdir(const char* path) { +#ifdef SUPPORT_LONGPATHS + wstring wpath; + if (!as_windows_path(path, &wpath)) { + errno = ENOENT; + return -1; + } + return ::_wchdir(wpath.c_str()); +#else + return ::_chdir(path); +#endif +} + +int stat(const char* path, struct _stat* buffer) { +#ifdef SUPPORT_LONGPATHS + wstring wpath; + if (!as_windows_path(path, &wpath)) { + errno = ENOENT; + return -1; + } + return ::_wstat(wpath.c_str(), buffer); +#else // not SUPPORT_LONGPATHS + return ::_stat(path, buffer); +#endif // not SUPPORT_LONGPATHS +} + +FILE* fopen(const char* path, const char* mode) { +#ifdef SUPPORT_LONGPATHS + if (null_or_empty(path)) { + errno = EINVAL; + return nullptr; + } + wstring wpath; + if (!as_windows_path(path, &wpath)) { + errno = ENOENT; + return nullptr; + } + wstring wmode; + if (!strings::utf8_to_wcs(mode, &wmode)) { + errno = EINVAL; + return nullptr; + } + return ::_wfopen(wpath.c_str(), wmode.c_str()); +#else + return ::fopen(path, mode); +#endif +} + +int close(int fd) { return ::_close(fd); } + +int dup(int fd) { return ::_dup(fd); } + +int dup2(int fd1, int fd2) { return ::_dup2(fd1, fd2); } + +int read(int fd, void* buffer, size_t size) { + return ::_read(fd, buffer, size); +} + +int setmode(int fd, int mode) { return ::_setmode(fd, mode); } + +int write(int fd, const void* buffer, size_t size) { + return ::_write(fd, buffer, size); +} + +wstring testonly_utf8_to_winpath(const char* path) { + wstring wpath; + return as_windows_path(path, &wpath) ? wpath : wstring(); +} + +ExpandWildcardsResult ExpandWildcards( + const string& path, std::function consume) { + if (path.find_first_of("*?") == string::npos) { + // There are no wildcards in the path, we don't need to expand it. + consume(path); + return ExpandWildcardsResult::kSuccess; + } + + wstring wpath; + if (!as_windows_path(path.c_str(), &wpath)) { + return ExpandWildcardsResult::kErrorInputPathConversion; + } + + static const wstring kDot = L"."; + static const wstring kDotDot = L".."; + WIN32_FIND_DATAW metadata; + HANDLE handle = ::FindFirstFileW(wpath.c_str(), &metadata); + if (handle == INVALID_HANDLE_VALUE) { + // The pattern does not match any files (or directories). + return ExpandWildcardsResult::kErrorNoMatchingFile; + } + + string::size_type pos = path.find_last_of("\\/"); + string dirname; + if (pos != string::npos) { + dirname = path.substr(0, pos + 1); + } + + ExpandWildcardsResult matched = ExpandWildcardsResult::kErrorNoMatchingFile; + do { + // Ignore ".", "..", and directories. + if ((metadata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0 && + kDot != metadata.cFileName && kDotDot != metadata.cFileName) { + matched = ExpandWildcardsResult::kSuccess; + string filename; + if (!strings::wcs_to_utf8(metadata.cFileName, &filename)) { + return ExpandWildcardsResult::kErrorOutputPathConversion; + } + + if (dirname.empty()) { + consume(filename); + } else { + consume(dirname + filename); + } + } + } while (::FindNextFileW(handle, &metadata)); + FindClose(handle); + return matched; +} + +namespace strings { + +bool wcs_to_mbs(const WCHAR* s, string* out, bool outUtf8) { + if (null_or_empty(s)) { + out->clear(); + return true; + } + BOOL usedDefaultChar = FALSE; + SetLastError(0); + int size = WideCharToMultiByte( + outUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, nullptr, 0, nullptr, + outUtf8 ? nullptr : &usedDefaultChar); + if ((size == 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) + || usedDefaultChar) { + return false; + } + std::unique_ptr astr(new CHAR[size]); + WideCharToMultiByte( + outUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, astr.get(), size, nullptr, nullptr); + out->assign(astr.get()); + return true; +} + +bool mbs_to_wcs(const char* s, wstring* out, bool inUtf8) { + if (null_or_empty(s)) { + out->clear(); + return true; + } + + SetLastError(0); + int size = + MultiByteToWideChar(inUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, nullptr, 0); + if (size == 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) { + return false; + } + std::unique_ptr wstr(new WCHAR[size]); + MultiByteToWideChar( + inUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, wstr.get(), size + 1); + out->assign(wstr.get()); + return true; +} + +bool utf8_to_wcs(const char* input, wstring* out) { + return mbs_to_wcs(input, out, true); +} + +bool wcs_to_utf8(const wchar_t* input, string* out) { + return wcs_to_mbs(input, out, true); +} + +} // namespace strings +} // namespace win32 +} // namespace io +} // namespace protobuf +} // namespace google + +#endif // defined(_WIN32) diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/io/tokenizer.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/io/tokenizer.h new file mode 100644 index 0000000..f7b693e --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/io/tokenizer.h @@ -0,0 +1,440 @@ +// 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. +// +// Class for parsing tokenized text from a ZeroCopyInputStream. + +#ifndef GOOGLE_PROTOBUF_IO_TOKENIZER_H__ +#define GOOGLE_PROTOBUF_IO_TOKENIZER_H__ + + +#include +#include + +#include +#include +#include + +namespace google { +namespace protobuf { +namespace io { + +class ZeroCopyInputStream; // zero_copy_stream.h + +// Defined in this file. +class ErrorCollector; +class Tokenizer; + +// By "column number", the proto compiler refers to a count of the number +// of bytes before a given byte, except that a tab character advances to +// the next multiple of 8 bytes. Note in particular that column numbers +// are zero-based, while many user interfaces use one-based column numbers. +typedef int ColumnNumber; + +// Abstract interface for an object which collects the errors that occur +// during parsing. A typical implementation might simply print the errors +// to stdout. +class PROTOBUF_EXPORT ErrorCollector { + public: + inline ErrorCollector() {} + virtual ~ErrorCollector(); + + // Indicates that there was an error in the input at the given line and + // column numbers. The numbers are zero-based, so you may want to add + // 1 to each before printing them. + virtual void AddError(int line, ColumnNumber column, + const std::string& message) = 0; + + // Indicates that there was a warning in the input at the given line and + // column numbers. The numbers are zero-based, so you may want to add + // 1 to each before printing them. + virtual void AddWarning(int /* line */, ColumnNumber /* column */, + const std::string& /* message */) {} + + private: + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ErrorCollector); +}; + +// This class converts a stream of raw text into a stream of tokens for +// the protocol definition parser to parse. The tokens recognized are +// similar to those that make up the C language; see the TokenType enum for +// precise descriptions. Whitespace and comments are skipped. By default, +// C- and C++-style comments are recognized, but other styles can be used by +// calling set_comment_style(). +class PROTOBUF_EXPORT Tokenizer { + public: + // Construct a Tokenizer that reads and tokenizes text from the given + // input stream and writes errors to the given error_collector. + // The caller keeps ownership of input and error_collector. + Tokenizer(ZeroCopyInputStream* input, ErrorCollector* error_collector); + ~Tokenizer(); + + enum TokenType { + TYPE_START, // Next() has not yet been called. + TYPE_END, // End of input reached. "text" is empty. + + TYPE_IDENTIFIER, // A sequence of letters, digits, and underscores, not + // starting with a digit. It is an error for a number + // to be followed by an identifier with no space in + // between. + TYPE_INTEGER, // A sequence of digits representing an integer. Normally + // the digits are decimal, but a prefix of "0x" indicates + // a hex number and a leading zero indicates octal, just + // like with C numeric literals. A leading negative sign + // is NOT included in the token; it's up to the parser to + // interpret the unary minus operator on its own. + TYPE_FLOAT, // A floating point literal, with a fractional part and/or + // an exponent. Always in decimal. Again, never + // negative. + TYPE_STRING, // A quoted sequence of escaped characters. Either single + // or double quotes can be used, but they must match. + // A string literal cannot cross a line break. + TYPE_SYMBOL, // Any other printable character, like '!' or '+'. + // Symbols are always a single character, so "!+$%" is + // four tokens. + TYPE_WHITESPACE, // A sequence of whitespace. This token type is only + // produced if report_whitespace() is true. It is not + // reported for whitespace within comments or strings. + TYPE_NEWLINE, // A newline (\n). This token type is only + // produced if report_whitespace() is true and + // report_newlines() is true. It is not reported for + // newlines in comments or strings. + }; + + // Structure representing a token read from the token stream. + struct Token { + TokenType type; + std::string text; // The exact text of the token as it appeared in + // the input. e.g. tokens of TYPE_STRING will still + // be escaped and in quotes. + + // "line" and "column" specify the position of the first character of + // the token within the input stream. They are zero-based. + int line; + ColumnNumber column; + ColumnNumber end_column; + }; + + // Get the current token. This is updated when Next() is called. Before + // the first call to Next(), current() has type TYPE_START and no contents. + const Token& current(); + + // Return the previous token -- i.e. what current() returned before the + // previous call to Next(). + const Token& previous(); + + // Advance to the next token. Returns false if the end of the input is + // reached. + bool Next(); + + // Like Next(), but also collects comments which appear between the previous + // and next tokens. + // + // Comments which appear to be attached to the previous token are stored + // in *prev_tailing_comments. Comments which appear to be attached to the + // next token are stored in *next_leading_comments. Comments appearing in + // between which do not appear to be attached to either will be added to + // detached_comments. Any of these parameters can be NULL to simply discard + // the comments. + // + // A series of line comments appearing on consecutive lines, with no other + // tokens appearing on those lines, will be treated as a single comment. + // + // Only the comment content is returned; comment markers (e.g. //) are + // stripped out. For block comments, leading whitespace and an asterisk will + // be stripped from the beginning of each line other than the first. Newlines + // are included in the output. + // + // Examples: + // + // optional int32 foo = 1; // Comment attached to foo. + // // Comment attached to bar. + // optional int32 bar = 2; + // + // optional string baz = 3; + // // Comment attached to baz. + // // Another line attached to baz. + // + // // Comment attached to qux. + // // + // // Another line attached to qux. + // optional double qux = 4; + // + // // Detached comment. This is not attached to qux or corge + // // because there are blank lines separating it from both. + // + // optional string corge = 5; + // /* Block comment attached + // * to corge. Leading asterisks + // * will be removed. */ + // /* Block comment attached to + // * grault. */ + // optional int32 grault = 6; + bool NextWithComments(std::string* prev_trailing_comments, + std::vector* detached_comments, + std::string* next_leading_comments); + + // Parse helpers --------------------------------------------------- + + // Parses a TYPE_FLOAT token. This never fails, so long as the text actually + // comes from a TYPE_FLOAT token parsed by Tokenizer. If it doesn't, the + // result is undefined (possibly an assert failure). + static double ParseFloat(const std::string& text); + + // Parses a TYPE_STRING token. This never fails, so long as the text actually + // comes from a TYPE_STRING token parsed by Tokenizer. If it doesn't, the + // result is undefined (possibly an assert failure). + static void ParseString(const std::string& text, std::string* output); + + // Identical to ParseString, but appends to output. + static void ParseStringAppend(const std::string& text, std::string* output); + + // Parses a TYPE_INTEGER token. Returns false if the result would be + // greater than max_value. Otherwise, returns true and sets *output to the + // result. If the text is not from a Token of type TYPE_INTEGER originally + // parsed by a Tokenizer, the result is undefined (possibly an assert + // failure). + static bool ParseInteger(const std::string& text, uint64_t max_value, + uint64_t* output); + + // Options --------------------------------------------------------- + + // Set true to allow floats to be suffixed with the letter 'f'. Tokens + // which would otherwise be integers but which have the 'f' suffix will be + // forced to be interpreted as floats. For all other purposes, the 'f' is + // ignored. + void set_allow_f_after_float(bool value) { allow_f_after_float_ = value; } + + // Valid values for set_comment_style(). + enum CommentStyle { + // Line comments begin with "//", block comments are delimited by "/*" and + // "*/". + CPP_COMMENT_STYLE, + // Line comments begin with "#". No way to write block comments. + SH_COMMENT_STYLE + }; + + // Sets the comment style. + void set_comment_style(CommentStyle style) { comment_style_ = style; } + + // Whether to require whitespace between a number and a field name. + // Default is true. Do not use this; for Google-internal cleanup only. + void set_require_space_after_number(bool require) { + require_space_after_number_ = require; + } + + // Whether to allow string literals to span multiple lines. Default is false. + // Do not use this; for Google-internal cleanup only. + void set_allow_multiline_strings(bool allow) { + allow_multiline_strings_ = allow; + } + + // If true, whitespace tokens are reported by Next(). + // Note: `set_report_whitespace(false)` implies `set_report_newlines(false)`. + bool report_whitespace() const; + void set_report_whitespace(bool report); + + // If true, newline tokens are reported by Next(). + // Note: `set_report_newlines(true)` implies `set_report_whitespace(true)`. + bool report_newlines() const; + void set_report_newlines(bool report); + + // External helper: validate an identifier. + static bool IsIdentifier(const std::string& text); + + // ----------------------------------------------------------------- + private: + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Tokenizer); + + Token current_; // Returned by current(). + Token previous_; // Returned by previous(). + + ZeroCopyInputStream* input_; + ErrorCollector* error_collector_; + + char current_char_; // == buffer_[buffer_pos_], updated by NextChar(). + const char* buffer_; // Current buffer returned from input_. + int buffer_size_; // Size of buffer_. + int buffer_pos_; // Current position within the buffer. + bool read_error_; // Did we previously encounter a read error? + + // Line and column number of current_char_ within the whole input stream. + int line_; + ColumnNumber column_; + + // String to which text should be appended as we advance through it. + // Call RecordTo(&str) to start recording and StopRecording() to stop. + // E.g. StartToken() calls RecordTo(¤t_.text). record_start_ is the + // position within the current buffer where recording started. + std::string* record_target_; + int record_start_; + + // Options. + bool allow_f_after_float_; + CommentStyle comment_style_; + bool require_space_after_number_; + bool allow_multiline_strings_; + bool report_whitespace_ = false; + bool report_newlines_ = false; + + // Since we count columns we need to interpret tabs somehow. We'll take + // the standard 8-character definition for lack of any way to do better. + // This must match the documentation of ColumnNumber. + static const int kTabWidth = 8; + + // ----------------------------------------------------------------- + // Helper methods. + + // Consume this character and advance to the next one. + void NextChar(); + + // Read a new buffer from the input. + void Refresh(); + + inline void RecordTo(std::string* target); + inline void StopRecording(); + + // Called when the current character is the first character of a new + // token (not including whitespace or comments). + inline void StartToken(); + // Called when the current character is the first character after the + // end of the last token. After this returns, current_.text will + // contain all text consumed since StartToken() was called. + inline void EndToken(); + + // Convenience method to add an error at the current line and column. + void AddError(const std::string& message) { + error_collector_->AddError(line_, column_, message); + } + + // ----------------------------------------------------------------- + // The following four methods are used to consume tokens of specific + // types. They are actually used to consume all characters *after* + // the first, since the calling function consumes the first character + // in order to decide what kind of token is being read. + + // Read and consume a string, ending when the given delimiter is + // consumed. + void ConsumeString(char delimiter); + + // Read and consume a number, returning TYPE_FLOAT or TYPE_INTEGER + // depending on what was read. This needs to know if the first + // character was a zero in order to correctly recognize hex and octal + // numbers. + // It also needs to know if the first character was a . to parse floating + // point correctly. + TokenType ConsumeNumber(bool started_with_zero, bool started_with_dot); + + // Consume the rest of a line. + void ConsumeLineComment(std::string* content); + // Consume until "*/". + void ConsumeBlockComment(std::string* content); + + enum NextCommentStatus { + // Started a line comment. + LINE_COMMENT, + + // Started a block comment. + BLOCK_COMMENT, + + // Consumed a slash, then realized it wasn't a comment. current_ has + // been filled in with a slash token. The caller should return it. + SLASH_NOT_COMMENT, + + // We do not appear to be starting a comment here. + NO_COMMENT + }; + + // If we're at the start of a new comment, consume it and return what kind + // of comment it is. + NextCommentStatus TryConsumeCommentStart(); + + // If we're looking at a TYPE_WHITESPACE token and `report_whitespace_` is + // true, consume it and return true. + bool TryConsumeWhitespace(); + + // If we're looking at a TYPE_NEWLINE token and `report_newlines_` is true, + // consume it and return true. + bool TryConsumeNewline(); + + // ----------------------------------------------------------------- + // These helper methods make the parsing code more readable. The + // "character classes" referred to are defined at the top of the .cc file. + // Basically it is a C++ class with one method: + // static bool InClass(char c); + // The method returns true if c is a member of this "class", like "Letter" + // or "Digit". + + // Returns true if the current character is of the given character + // class, but does not consume anything. + template + inline bool LookingAt(); + + // If the current character is in the given class, consume it and return + // true. Otherwise return false. + // e.g. TryConsumeOne() + template + inline bool TryConsumeOne(); + + // Like above, but try to consume the specific character indicated. + inline bool TryConsume(char c); + + // Consume zero or more of the given character class. + template + inline void ConsumeZeroOrMore(); + + // Consume one or more of the given character class or log the given + // error message. + // e.g. ConsumeOneOrMore("Expected digits."); + template + inline void ConsumeOneOrMore(const char* error); +}; + +// inline methods ==================================================== +inline const Tokenizer::Token& Tokenizer::current() { return current_; } + +inline const Tokenizer::Token& Tokenizer::previous() { return previous_; } + +inline void Tokenizer::ParseString(const std::string& text, + std::string* output) { + output->clear(); + ParseStringAppend(text, output); +} + +} // namespace io +} // namespace protobuf +} // namespace google + +#include + +#endif // GOOGLE_PROTOBUF_IO_TOKENIZER_H__ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/io/zero_copy_stream.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/io/zero_copy_stream.cc new file mode 100644 index 0000000..f81555e --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/io/zero_copy_stream.cc @@ -0,0 +1,55 @@ +// 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. + +#include + +#include +#include + +namespace google { +namespace protobuf { +namespace io { + + +bool ZeroCopyOutputStream::WriteAliasedRaw(const void* /* data */, + int /* size */) { + GOOGLE_LOG(FATAL) << "This ZeroCopyOutputStream doesn't support aliasing. " + "Reaching here usually means a ZeroCopyOutputStream " + "implementation bug."; + return false; +} + +} // namespace io +} // namespace protobuf +} // namespace google diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/io/zero_copy_stream.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/io/zero_copy_stream.h new file mode 100644 index 0000000..d3bd6da --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/io/zero_copy_stream.h @@ -0,0 +1,253 @@ +// 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 contains the ZeroCopyInputStream and ZeroCopyOutputStream +// interfaces, which represent abstract I/O streams to and from which +// protocol buffers can be read and written. For a few simple +// implementations of these interfaces, see zero_copy_stream_impl.h. +// +// These interfaces are different from classic I/O streams in that they +// try to minimize the amount of data copying that needs to be done. +// To accomplish this, responsibility for allocating buffers is moved to +// the stream object, rather than being the responsibility of the caller. +// So, the stream can return a buffer which actually points directly into +// the final data structure where the bytes are to be stored, and the caller +// can interact directly with that buffer, eliminating an intermediate copy +// operation. +// +// As an example, consider the common case in which you are reading bytes +// from an array that is already in memory (or perhaps an mmap()ed file). +// With classic I/O streams, you would do something like: +// char buffer[BUFFER_SIZE]; +// input->Read(buffer, BUFFER_SIZE); +// DoSomething(buffer, BUFFER_SIZE); +// Then, the stream basically just calls memcpy() to copy the data from +// the array into your buffer. With a ZeroCopyInputStream, you would do +// this instead: +// const void* buffer; +// int size; +// input->Next(&buffer, &size); +// DoSomething(buffer, size); +// Here, no copy is performed. The input stream returns a pointer directly +// into the backing array, and the caller ends up reading directly from it. +// +// If you want to be able to read the old-fashion way, you can create +// a CodedInputStream or CodedOutputStream wrapping these objects and use +// their ReadRaw()/WriteRaw() methods. These will, of course, add a copy +// step, but Coded*Stream will handle buffering so at least it will be +// reasonably efficient. +// +// ZeroCopyInputStream example: +// // Read in a file and print its contents to stdout. +// int fd = open("myfile", O_RDONLY); +// ZeroCopyInputStream* input = new FileInputStream(fd); +// +// const void* buffer; +// int size; +// while (input->Next(&buffer, &size)) { +// cout.write(buffer, size); +// } +// +// delete input; +// close(fd); +// +// ZeroCopyOutputStream example: +// // Copy the contents of "infile" to "outfile", using plain read() for +// // "infile" but a ZeroCopyOutputStream for "outfile". +// int infd = open("infile", O_RDONLY); +// int outfd = open("outfile", O_WRONLY); +// ZeroCopyOutputStream* output = new FileOutputStream(outfd); +// +// void* buffer; +// int size; +// while (output->Next(&buffer, &size)) { +// int bytes = read(infd, buffer, size); +// if (bytes < size) { +// // Reached EOF. +// output->BackUp(size - bytes); +// break; +// } +// } +// +// delete output; +// close(infd); +// close(outfd); + +#ifndef GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_H__ +#define GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_H__ + + +#include + +#include +#include + + +namespace google { +namespace protobuf { +namespace io { + +// Defined in this file. +class ZeroCopyInputStream; +class ZeroCopyOutputStream; + +// Abstract interface similar to an input stream but designed to minimize +// copying. +class PROTOBUF_EXPORT ZeroCopyInputStream { + public: + ZeroCopyInputStream() {} + virtual ~ZeroCopyInputStream() {} + + // Obtains a chunk of data from the stream. + // + // Preconditions: + // * "size" and "data" are not NULL. + // + // Postconditions: + // * If the returned value is false, there is no more data to return or + // an error occurred. All errors are permanent. + // * Otherwise, "size" points to the actual number of bytes read and "data" + // points to a pointer to a buffer containing these bytes. + // * Ownership of this buffer remains with the stream, and the buffer + // remains valid only until some other method of the stream is called + // or the stream is destroyed. + // * It is legal for the returned buffer to have zero size, as long + // as repeatedly calling Next() eventually yields a buffer with non-zero + // size. + virtual bool Next(const void** data, int* size) = 0; + + // Backs up a number of bytes, so that the next call to Next() returns + // data again that was already returned by the last call to Next(). This + // is useful when writing procedures that are only supposed to read up + // to a certain point in the input, then return. If Next() returns a + // buffer that goes beyond what you wanted to read, you can use BackUp() + // to return to the point where you intended to finish. + // + // Preconditions: + // * The last method called must have been Next(). + // * count must be less than or equal to the size of the last buffer + // returned by Next(). + // + // Postconditions: + // * The last "count" bytes of the last buffer returned by Next() will be + // pushed back into the stream. Subsequent calls to Next() will return + // the same data again before producing new data. + virtual void BackUp(int count) = 0; + + // Skips a number of bytes. Returns false if the end of the stream is + // reached or some input error occurred. In the end-of-stream case, the + // stream is advanced to the end of the stream (so ByteCount() will return + // the total size of the stream). + virtual bool Skip(int count) = 0; + + // Returns the total number of bytes read since this object was created. + virtual int64_t ByteCount() const = 0; + + + private: + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ZeroCopyInputStream); +}; + +// Abstract interface similar to an output stream but designed to minimize +// copying. +class PROTOBUF_EXPORT ZeroCopyOutputStream { + public: + ZeroCopyOutputStream() {} + virtual ~ZeroCopyOutputStream() {} + + // Obtains a buffer into which data can be written. Any data written + // into this buffer will eventually (maybe instantly, maybe later on) + // be written to the output. + // + // Preconditions: + // * "size" and "data" are not NULL. + // + // Postconditions: + // * If the returned value is false, an error occurred. All errors are + // permanent. + // * Otherwise, "size" points to the actual number of bytes in the buffer + // and "data" points to the buffer. + // * Ownership of this buffer remains with the stream, and the buffer + // remains valid only until some other method of the stream is called + // or the stream is destroyed. + // * Any data which the caller stores in this buffer will eventually be + // written to the output (unless BackUp() is called). + // * It is legal for the returned buffer to have zero size, as long + // as repeatedly calling Next() eventually yields a buffer with non-zero + // size. + virtual bool Next(void** data, int* size) = 0; + + // Backs up a number of bytes, so that the end of the last buffer returned + // by Next() is not actually written. This is needed when you finish + // writing all the data you want to write, but the last buffer was bigger + // than you needed. You don't want to write a bunch of garbage after the + // end of your data, so you use BackUp() to back up. + // + // Preconditions: + // * The last method called must have been Next(). + // * count must be less than or equal to the size of the last buffer + // returned by Next(). + // * The caller must not have written anything to the last "count" bytes + // of that buffer. + // + // Postconditions: + // * The last "count" bytes of the last buffer returned by Next() will be + // ignored. + virtual void BackUp(int count) = 0; + + // Returns the total number of bytes written since this object was created. + virtual int64_t ByteCount() const = 0; + + // Write a given chunk of data to the output. Some output streams may + // implement this in a way that avoids copying. Check AllowsAliasing() before + // calling WriteAliasedRaw(). It will GOOGLE_CHECK fail if WriteAliasedRaw() is + // called on a stream that does not allow aliasing. + // + // NOTE: It is caller's responsibility to ensure that the chunk of memory + // remains live until all of the data has been consumed from the stream. + virtual bool WriteAliasedRaw(const void* data, int size); + virtual bool AllowsAliasing() const { return false; } + + + private: + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ZeroCopyOutputStream); +}; + +} // namespace io +} // namespace protobuf +} // namespace google + +#include + +#endif // GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_H__ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/lite_arena_unittest.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/lite_arena_unittest.cc new file mode 100644 index 0000000..d68c6c9 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/lite_arena_unittest.cc @@ -0,0 +1,90 @@ +// 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. + +#include +#include +#include + +namespace google { +namespace protobuf { +namespace { + +class LiteArenaTest : public testing::Test { + protected: + LiteArenaTest() { + ArenaOptions options; + options.start_block_size = 128 * 1024; + options.max_block_size = 128 * 1024; + arena_.reset(new Arena(options)); + // Trigger the allocation of the first arena block, so that further use of + // the arena will not require any heap allocations. + Arena::CreateArray(arena_.get(), 1); + } + + std::unique_ptr arena_; +}; + +TEST_F(LiteArenaTest, MapNoHeapAllocation) { + std::string data; + data.reserve(128 * 1024); + + { + // TODO(teboring): Enable no heap check when ArenaStringPtr is used in + // Map. + // internal::NoHeapChecker no_heap; + + protobuf_unittest::TestArenaMapLite* from = + Arena::CreateMessage(arena_.get()); + MapLiteTestUtil::SetArenaMapFields(from); + from->SerializeToString(&data); + + protobuf_unittest::TestArenaMapLite* to = + Arena::CreateMessage(arena_.get()); + to->ParseFromString(data); + MapLiteTestUtil::ExpectArenaMapFieldsSet(*to); + } +} + +TEST_F(LiteArenaTest, UnknownFieldMemLeak) { + protobuf_unittest::ForeignMessageArenaLite* message = + Arena::CreateMessage( + arena_.get()); + std::string data = "\012\000"; + int original_capacity = data.capacity(); + while (data.capacity() <= original_capacity) { + data.append("a"); + } + data[1] = data.size() - 2; + message->ParseFromString(data); +} + +} // namespace +} // namespace protobuf +} // namespace google diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/map_field.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/map_field.h new file mode 100644 index 0000000..19b73ca --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/map_field.h @@ -0,0 +1,923 @@ +// 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_MAP_FIELD_H__ +#define GOOGLE_PROTOBUF_MAP_FIELD_H__ + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif + +namespace google { +namespace protobuf { +class DynamicMessage; +class MapIterator; + +#define TYPE_CHECK(EXPECTEDTYPE, METHOD) \ + if (type() != EXPECTEDTYPE) { \ + GOOGLE_LOG(FATAL) << "Protocol Buffer map usage error:\n" \ + << METHOD << " type does not match\n" \ + << " Expected : " \ + << FieldDescriptor::CppTypeName(EXPECTEDTYPE) << "\n" \ + << " Actual : " << FieldDescriptor::CppTypeName(type()); \ + } + +// MapKey is an union type for representing any possible +// map key. +class PROTOBUF_EXPORT MapKey { + public: + MapKey() : type_() {} + MapKey(const MapKey& other) : type_() { CopyFrom(other); } + + MapKey& operator=(const MapKey& other) { + CopyFrom(other); + return *this; + } + + ~MapKey() { + if (type_ == FieldDescriptor::CPPTYPE_STRING) { + val_.string_value_.Destruct(); + } + } + + FieldDescriptor::CppType type() const { + if (type_ == FieldDescriptor::CppType()) { + GOOGLE_LOG(FATAL) << "Protocol Buffer map usage error:\n" + << "MapKey::type MapKey is not initialized. " + << "Call set methods to initialize MapKey."; + } + return type_; + } + + void SetInt64Value(int64_t value) { + SetType(FieldDescriptor::CPPTYPE_INT64); + val_.int64_value_ = value; + } + void SetUInt64Value(uint64_t value) { + SetType(FieldDescriptor::CPPTYPE_UINT64); + val_.uint64_value_ = value; + } + void SetInt32Value(int32_t value) { + SetType(FieldDescriptor::CPPTYPE_INT32); + val_.int32_value_ = value; + } + void SetUInt32Value(uint32_t value) { + SetType(FieldDescriptor::CPPTYPE_UINT32); + val_.uint32_value_ = value; + } + void SetBoolValue(bool value) { + SetType(FieldDescriptor::CPPTYPE_BOOL); + val_.bool_value_ = value; + } + void SetStringValue(std::string val) { + SetType(FieldDescriptor::CPPTYPE_STRING); + *val_.string_value_.get_mutable() = std::move(val); + } + + int64_t GetInt64Value() const { + TYPE_CHECK(FieldDescriptor::CPPTYPE_INT64, "MapKey::GetInt64Value"); + return val_.int64_value_; + } + uint64_t GetUInt64Value() const { + TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT64, "MapKey::GetUInt64Value"); + return val_.uint64_value_; + } + int32_t GetInt32Value() const { + TYPE_CHECK(FieldDescriptor::CPPTYPE_INT32, "MapKey::GetInt32Value"); + return val_.int32_value_; + } + uint32_t GetUInt32Value() const { + TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT32, "MapKey::GetUInt32Value"); + return val_.uint32_value_; + } + bool GetBoolValue() const { + TYPE_CHECK(FieldDescriptor::CPPTYPE_BOOL, "MapKey::GetBoolValue"); + return val_.bool_value_; + } + const std::string& GetStringValue() const { + TYPE_CHECK(FieldDescriptor::CPPTYPE_STRING, "MapKey::GetStringValue"); + return val_.string_value_.get(); + } + + bool operator<(const MapKey& other) const { + if (type_ != other.type_) { + // We could define a total order that handles this case, but + // there currently no need. So, for now, fail. + GOOGLE_LOG(FATAL) << "Unsupported: type mismatch"; + } + switch (type()) { + case FieldDescriptor::CPPTYPE_DOUBLE: + case FieldDescriptor::CPPTYPE_FLOAT: + case FieldDescriptor::CPPTYPE_ENUM: + case FieldDescriptor::CPPTYPE_MESSAGE: + GOOGLE_LOG(FATAL) << "Unsupported"; + return false; + case FieldDescriptor::CPPTYPE_STRING: + return val_.string_value_.get() < other.val_.string_value_.get(); + case FieldDescriptor::CPPTYPE_INT64: + return val_.int64_value_ < other.val_.int64_value_; + case FieldDescriptor::CPPTYPE_INT32: + return val_.int32_value_ < other.val_.int32_value_; + case FieldDescriptor::CPPTYPE_UINT64: + return val_.uint64_value_ < other.val_.uint64_value_; + case FieldDescriptor::CPPTYPE_UINT32: + return val_.uint32_value_ < other.val_.uint32_value_; + case FieldDescriptor::CPPTYPE_BOOL: + return val_.bool_value_ < other.val_.bool_value_; + } + return false; + } + + bool operator==(const MapKey& other) const { + if (type_ != other.type_) { + // To be consistent with operator<, we don't allow this either. + GOOGLE_LOG(FATAL) << "Unsupported: type mismatch"; + } + switch (type()) { + case FieldDescriptor::CPPTYPE_DOUBLE: + case FieldDescriptor::CPPTYPE_FLOAT: + case FieldDescriptor::CPPTYPE_ENUM: + case FieldDescriptor::CPPTYPE_MESSAGE: + GOOGLE_LOG(FATAL) << "Unsupported"; + break; + case FieldDescriptor::CPPTYPE_STRING: + return val_.string_value_.get() == other.val_.string_value_.get(); + case FieldDescriptor::CPPTYPE_INT64: + return val_.int64_value_ == other.val_.int64_value_; + case FieldDescriptor::CPPTYPE_INT32: + return val_.int32_value_ == other.val_.int32_value_; + case FieldDescriptor::CPPTYPE_UINT64: + return val_.uint64_value_ == other.val_.uint64_value_; + case FieldDescriptor::CPPTYPE_UINT32: + return val_.uint32_value_ == other.val_.uint32_value_; + case FieldDescriptor::CPPTYPE_BOOL: + return val_.bool_value_ == other.val_.bool_value_; + } + GOOGLE_LOG(FATAL) << "Can't get here."; + return false; + } + + void CopyFrom(const MapKey& other) { + SetType(other.type()); + switch (type_) { + case FieldDescriptor::CPPTYPE_DOUBLE: + case FieldDescriptor::CPPTYPE_FLOAT: + case FieldDescriptor::CPPTYPE_ENUM: + case FieldDescriptor::CPPTYPE_MESSAGE: + GOOGLE_LOG(FATAL) << "Unsupported"; + break; + case FieldDescriptor::CPPTYPE_STRING: + *val_.string_value_.get_mutable() = other.val_.string_value_.get(); + break; + case FieldDescriptor::CPPTYPE_INT64: + val_.int64_value_ = other.val_.int64_value_; + break; + case FieldDescriptor::CPPTYPE_INT32: + val_.int32_value_ = other.val_.int32_value_; + break; + case FieldDescriptor::CPPTYPE_UINT64: + val_.uint64_value_ = other.val_.uint64_value_; + break; + case FieldDescriptor::CPPTYPE_UINT32: + val_.uint32_value_ = other.val_.uint32_value_; + break; + case FieldDescriptor::CPPTYPE_BOOL: + val_.bool_value_ = other.val_.bool_value_; + break; + } + } + + private: + template + friend class internal::TypeDefinedMapFieldBase; + friend class ::PROTOBUF_NAMESPACE_ID::MapIterator; + friend class internal::DynamicMapField; + + union KeyValue { + KeyValue() {} + internal::ExplicitlyConstructed string_value_; + int64_t int64_value_; + int32_t int32_value_; + uint64_t uint64_value_; + uint32_t uint32_value_; + bool bool_value_; + } val_; + + void SetType(FieldDescriptor::CppType type) { + if (type_ == type) return; + if (type_ == FieldDescriptor::CPPTYPE_STRING) { + val_.string_value_.Destruct(); + } + type_ = type; + if (type_ == FieldDescriptor::CPPTYPE_STRING) { + val_.string_value_.DefaultConstruct(); + } + } + + // type_ is 0 or a valid FieldDescriptor::CppType. + // Use "CppType()" to indicate zero. + FieldDescriptor::CppType type_; +}; + +} // namespace protobuf +} // namespace google +namespace std { +template <> +struct hash<::PROTOBUF_NAMESPACE_ID::MapKey> { + size_t operator()(const ::PROTOBUF_NAMESPACE_ID::MapKey& map_key) const { + switch (map_key.type()) { + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_DOUBLE: + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_FLOAT: + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_ENUM: + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_MESSAGE: + GOOGLE_LOG(FATAL) << "Unsupported"; + break; + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_STRING: + return hash()(map_key.GetStringValue()); + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_INT64: { + auto value = map_key.GetInt64Value(); + return hash()(value); + } + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_INT32: { + auto value = map_key.GetInt32Value(); + return hash()(map_key.GetInt32Value()); + } + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_UINT64: { + auto value = map_key.GetUInt64Value(); + return hash()(map_key.GetUInt64Value()); + } + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_UINT32: { + auto value = map_key.GetUInt32Value(); + return hash()(map_key.GetUInt32Value()); + } + case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_BOOL: { + return hash()(map_key.GetBoolValue()); + } + } + GOOGLE_LOG(FATAL) << "Can't get here."; + return 0; + } + bool operator()(const ::PROTOBUF_NAMESPACE_ID::MapKey& map_key1, + const ::PROTOBUF_NAMESPACE_ID::MapKey& map_key2) const { + return map_key1 < map_key2; + } +}; +} // namespace std + +namespace google { +namespace protobuf { +namespace internal { + +class ContendedMapCleanTest; +class GeneratedMessageReflection; +class MapFieldAccessor; + +// This class provides access to map field using reflection, which is the same +// as those provided for RepeatedPtrField. It is used for internal +// reflection implementation only. Users should never use this directly. +class PROTOBUF_EXPORT MapFieldBase { + public: + MapFieldBase() + : arena_(nullptr), repeated_field_(nullptr), state_(STATE_MODIFIED_MAP) {} + + // This constructor is for constant initialized global instances. + // It uses a linker initialized mutex, so it is not compatible with regular + // runtime instances. + // Except in MSVC, where we can't have a constinit mutex. + explicit constexpr MapFieldBase(ConstantInitialized) + : arena_(nullptr), + repeated_field_(nullptr), + mutex_(GOOGLE_PROTOBUF_LINKER_INITIALIZED), + state_(STATE_MODIFIED_MAP) {} + explicit MapFieldBase(Arena* arena) + : arena_(arena), repeated_field_(nullptr), state_(STATE_MODIFIED_MAP) {} + virtual ~MapFieldBase(); + + // Returns reference to internal repeated field. Data written using + // Map's api prior to calling this function is guarantted to be + // included in repeated field. + const RepeatedPtrFieldBase& GetRepeatedField() const; + + // Like above. Returns mutable pointer to the internal repeated field. + RepeatedPtrFieldBase* MutableRepeatedField(); + + // Pure virtual map APIs for Map Reflection. + virtual bool ContainsMapKey(const MapKey& map_key) const = 0; + virtual bool InsertOrLookupMapValue(const MapKey& map_key, + MapValueRef* val) = 0; + virtual bool LookupMapValue(const MapKey& map_key, + MapValueConstRef* val) const = 0; + bool LookupMapValue(const MapKey&, MapValueRef*) const = delete; + + // 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; + virtual bool EqualIterator(const MapIterator& a, + const MapIterator& b) const = 0; + virtual void MapBegin(MapIterator* map_iter) const = 0; + virtual void MapEnd(MapIterator* map_iter) const = 0; + virtual void MergeFrom(const MapFieldBase& other) = 0; + virtual void Swap(MapFieldBase* other); + virtual void UnsafeShallowSwap(MapFieldBase* other); + // Sync Map with repeated field and returns the size of map. + virtual int size() const = 0; + virtual void Clear() = 0; + + // Returns the number of bytes used by the repeated field, excluding + // sizeof(*this) + size_t SpaceUsedExcludingSelfLong() const; + + int SpaceUsedExcludingSelf() const { + return internal::ToIntSize(SpaceUsedExcludingSelfLong()); + } + + protected: + // Gets the size of space used by map field. + virtual size_t SpaceUsedExcludingSelfNoLock() const; + + // Synchronizes the content in Map to RepeatedPtrField if there is any change + // to Map after last synchronization. + void SyncRepeatedFieldWithMap() const; + virtual void SyncRepeatedFieldWithMapNoLock() const; + + // Synchronizes the content in RepeatedPtrField to Map if there is any change + // to RepeatedPtrField after last synchronization. + void SyncMapWithRepeatedField() const; + virtual void SyncMapWithRepeatedFieldNoLock() const {} + + // Tells MapFieldBase that there is new change to Map. + void SetMapDirty(); + + // Tells MapFieldBase that there is new change to RepeatedPtrField. + void SetRepeatedDirty(); + + // Provides derived class the access to repeated field. + void* MutableRepeatedPtrField() const; + + void InternalSwap(MapFieldBase* other); + + // Support thread sanitizer (tsan) by making const / mutable races + // more apparent. If one thread calls MutableAccess() while another + // thread calls either ConstAccess() or MutableAccess(), on the same + // MapFieldBase-derived object, and there is no synchronization going + // on between them, tsan will alert. +#if defined(__SANITIZE_THREAD__) || defined(THREAD_SANITIZER) + void ConstAccess() const { GOOGLE_CHECK_EQ(seq1_, seq2_); } + void MutableAccess() { + if (seq1_ & 1) { + seq2_ = ++seq1_; + } else { + seq1_ = ++seq2_; + } + } + unsigned int seq1_ = 0, seq2_ = 0; +#else + void ConstAccess() const {} + void MutableAccess() {} +#endif + enum State { + STATE_MODIFIED_MAP = 0, // map has newly added data that has not been + // synchronized to repeated field + STATE_MODIFIED_REPEATED = 1, // repeated field has newly added data that + // has not been synchronized to map + CLEAN = 2, // data in map and repeated field are same + }; + + Arena* arena_; + mutable RepeatedPtrField* repeated_field_; + + mutable internal::WrappedMutex + mutex_; // The thread to synchronize map and repeated field + // needs to get lock first; + mutable std::atomic state_; + + private: + friend class ContendedMapCleanTest; + friend class GeneratedMessageReflection; + friend class MapFieldAccessor; + friend class ::PROTOBUF_NAMESPACE_ID::Reflection; + friend class ::PROTOBUF_NAMESPACE_ID::DynamicMessage; + + // Virtual helper methods for MapIterator. MapIterator doesn't have the + // type helper for key and value. Call these help methods to deal with + // different types. Real helper methods are implemented in + // TypeDefinedMapFieldBase. + friend class ::PROTOBUF_NAMESPACE_ID::MapIterator; + // Allocate map<...>::iterator for MapIterator. + virtual void InitializeIterator(MapIterator* map_iter) const = 0; + + // DeleteIterator() is called by the destructor of MapIterator only. + // It deletes map<...>::iterator for MapIterator. + virtual void DeleteIterator(MapIterator* map_iter) const = 0; + + // Copy the map<...>::iterator from other_iterator to + // this_iterator. + virtual void CopyIterator(MapIterator* this_iterator, + const MapIterator& other_iterator) const = 0; + + // IncreaseIterator() is called by operator++() of MapIterator only. + // It implements the ++ operator of MapIterator. + virtual void IncreaseIterator(MapIterator* map_iter) const = 0; + + // Swaps state_ with another MapFieldBase + void SwapState(MapFieldBase* other); + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapFieldBase); +}; + +// This class provides common Map Reflection implementations for generated +// message and dynamic message. +template +class TypeDefinedMapFieldBase : public MapFieldBase { + public: + TypeDefinedMapFieldBase() {} + + // This constructor is for constant initialized global instances. + // It uses a linker initialized mutex, so it is not compatible with regular + // runtime instances. + explicit constexpr TypeDefinedMapFieldBase(ConstantInitialized tag) + : MapFieldBase(tag) {} + explicit TypeDefinedMapFieldBase(Arena* arena) : MapFieldBase(arena) {} + ~TypeDefinedMapFieldBase() override {} + void MapBegin(MapIterator* map_iter) const override; + void MapEnd(MapIterator* map_iter) const override; + bool EqualIterator(const MapIterator& a, const MapIterator& b) const override; + + virtual const Map& GetMap() const = 0; + virtual Map* MutableMap() = 0; + + protected: + typename Map::const_iterator& InternalGetIterator( + const MapIterator* map_iter) const; + + private: + void InitializeIterator(MapIterator* map_iter) const override; + void DeleteIterator(MapIterator* map_iter) const override; + void CopyIterator(MapIterator* this_iteratorm, + const MapIterator& that_iterator) const override; + void IncreaseIterator(MapIterator* map_iter) const override; + + virtual void SetMapIteratorValue(MapIterator* map_iter) const = 0; + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TypeDefinedMapFieldBase); +}; + +// This class provides access to map field using generated api. It is used for +// internal generated message implementation only. Users should never use this +// directly. +template +class MapField : public TypeDefinedMapFieldBase { + // Provide utilities to parse/serialize key/value. Provide utilities to + // manipulate internal stored type. + typedef MapTypeHandler KeyTypeHandler; + typedef MapTypeHandler ValueTypeHandler; + + // Define message type for internal repeated field. + typedef Derived EntryType; + + // Define abbreviation for parent MapFieldLite + typedef MapFieldLite + MapFieldLiteType; + + // Enum needs to be handled differently from other types because it has + // different exposed type in Map's api and repeated field's api. For + // details see the comment in the implementation of + // SyncMapWithRepeatedFieldNoLock. + static constexpr bool kIsValueEnum = ValueTypeHandler::kIsEnum; + typedef typename MapIf::type CastValueType; + + public: + typedef typename Derived::SuperType EntryTypeTrait; + typedef Map MapType; + + MapField() {} + + // This constructor is for constant initialized global instances. + // It uses a linker initialized mutex, so it is not compatible with regular + // runtime instances. + explicit constexpr MapField(ConstantInitialized tag) + : TypeDefinedMapFieldBase(tag), impl_() {} + explicit MapField(Arena* arena) + : TypeDefinedMapFieldBase(arena), impl_(arena) {} + + // Implement MapFieldBase + bool ContainsMapKey(const MapKey& map_key) const override; + bool InsertOrLookupMapValue(const MapKey& map_key, MapValueRef* val) override; + bool LookupMapValue(const MapKey& map_key, + MapValueConstRef* val) const override; + bool LookupMapValue(const MapKey&, MapValueRef*) const = delete; + bool DeleteMapValue(const MapKey& map_key) override; + + const Map& GetMap() const override { + MapFieldBase::SyncMapWithRepeatedField(); + return impl_.GetMap(); + } + + Map* MutableMap() override { + MapFieldBase::SyncMapWithRepeatedField(); + Map* result = impl_.MutableMap(); + MapFieldBase::SetMapDirty(); + return result; + } + + int size() const override; + void Clear() override; + void MergeFrom(const MapFieldBase& other) override; + void Swap(MapFieldBase* other) override; + void UnsafeShallowSwap(MapFieldBase* other) override; + void InternalSwap(MapField* other); + + // Used in the implementation of parsing. Caller should take the ownership iff + // arena_ is nullptr. + EntryType* NewEntry() const { return impl_.NewEntry(); } + // Used in the implementation of serializing enum value type. Caller should + // take the ownership iff arena_ is nullptr. + EntryType* NewEnumEntryWrapper(const Key& key, const T t) const { + return impl_.NewEnumEntryWrapper(key, t); + } + // Used in the implementation of serializing other value types. Caller should + // take the ownership iff arena_ is nullptr. + EntryType* NewEntryWrapper(const Key& key, const T& t) const { + return impl_.NewEntryWrapper(key, t); + } + + const char* _InternalParse(const char* ptr, ParseContext* ctx) { + return impl_._InternalParse(ptr, ctx); + } + template + const char* ParseWithEnumValidation(const char* ptr, ParseContext* ctx, + bool (*is_valid)(int), uint32_t field_num, + InternalMetadata* metadata) { + return impl_.template ParseWithEnumValidation( + ptr, ctx, is_valid, field_num, metadata); + } + + private: + MapFieldLiteType impl_; + + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + + // Implements MapFieldBase + void SyncRepeatedFieldWithMapNoLock() const override; + void SyncMapWithRepeatedFieldNoLock() const override; + size_t SpaceUsedExcludingSelfNoLock() const override; + + void SetMapIteratorValue(MapIterator* map_iter) const override; + + friend class ::PROTOBUF_NAMESPACE_ID::Arena; + friend class MapFieldStateTest; // For testing, it needs raw access to impl_ + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapField); +}; + +template +bool AllAreInitialized( + const MapField& field) { + const auto& t = field.GetMap(); + for (typename Map::const_iterator it = t.begin(); it != t.end(); + ++it) { + if (!it->second.IsInitialized()) return false; + } + return true; +} + +template +struct MapEntryToMapField< + MapEntry> { + typedef MapField MapFieldType; +}; + +class PROTOBUF_EXPORT DynamicMapField + : public TypeDefinedMapFieldBase { + public: + explicit DynamicMapField(const Message* default_entry); + DynamicMapField(const Message* default_entry, Arena* arena); + ~DynamicMapField() override; + + // Implement MapFieldBase + bool ContainsMapKey(const MapKey& map_key) const override; + bool InsertOrLookupMapValue(const MapKey& map_key, MapValueRef* val) override; + bool LookupMapValue(const MapKey& map_key, + MapValueConstRef* val) const override; + bool LookupMapValue(const MapKey&, MapValueRef*) const = delete; + bool DeleteMapValue(const MapKey& map_key) override; + void MergeFrom(const MapFieldBase& other) override; + void Swap(MapFieldBase* other) override; + void UnsafeShallowSwap(MapFieldBase* other) override { Swap(other); } + + const Map& GetMap() const override; + Map* MutableMap() override; + + int size() const override; + void Clear() override; + + private: + Map map_; + const Message* default_entry_; + + void AllocateMapValue(MapValueRef* map_val); + + // Implements MapFieldBase + void SyncRepeatedFieldWithMapNoLock() const override; + void SyncMapWithRepeatedFieldNoLock() const override; + size_t SpaceUsedExcludingSelfNoLock() const override; + void SetMapIteratorValue(MapIterator* map_iter) const override; + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DynamicMapField); +}; + +} // namespace internal + +// MapValueConstRef points to a map value. Users can NOT modify +// the map value. +class PROTOBUF_EXPORT MapValueConstRef { + public: + MapValueConstRef() : data_(nullptr), type_() {} + + int64_t GetInt64Value() const { + TYPE_CHECK(FieldDescriptor::CPPTYPE_INT64, + "MapValueConstRef::GetInt64Value"); + return *reinterpret_cast(data_); + } + uint64_t GetUInt64Value() const { + TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT64, + "MapValueConstRef::GetUInt64Value"); + return *reinterpret_cast(data_); + } + int32_t GetInt32Value() const { + TYPE_CHECK(FieldDescriptor::CPPTYPE_INT32, + "MapValueConstRef::GetInt32Value"); + return *reinterpret_cast(data_); + } + uint32_t GetUInt32Value() const { + TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT32, + "MapValueConstRef::GetUInt32Value"); + return *reinterpret_cast(data_); + } + bool GetBoolValue() const { + TYPE_CHECK(FieldDescriptor::CPPTYPE_BOOL, "MapValueConstRef::GetBoolValue"); + return *reinterpret_cast(data_); + } + int GetEnumValue() const { + TYPE_CHECK(FieldDescriptor::CPPTYPE_ENUM, "MapValueConstRef::GetEnumValue"); + return *reinterpret_cast(data_); + } + const std::string& GetStringValue() const { + TYPE_CHECK(FieldDescriptor::CPPTYPE_STRING, + "MapValueConstRef::GetStringValue"); + return *reinterpret_cast(data_); + } + float GetFloatValue() const { + TYPE_CHECK(FieldDescriptor::CPPTYPE_FLOAT, + "MapValueConstRef::GetFloatValue"); + return *reinterpret_cast(data_); + } + double GetDoubleValue() const { + TYPE_CHECK(FieldDescriptor::CPPTYPE_DOUBLE, + "MapValueConstRef::GetDoubleValue"); + return *reinterpret_cast(data_); + } + + const Message& GetMessageValue() const { + TYPE_CHECK(FieldDescriptor::CPPTYPE_MESSAGE, + "MapValueConstRef::GetMessageValue"); + return *reinterpret_cast(data_); + } + + protected: + // data_ point to a map value. MapValueConstRef does not + // own this value. + void* data_; + // type_ is 0 or a valid FieldDescriptor::CppType. + // Use "CppType()" to indicate zero. + FieldDescriptor::CppType type_; + + FieldDescriptor::CppType type() const { + if (type_ == FieldDescriptor::CppType() || data_ == nullptr) { + GOOGLE_LOG(FATAL) + << "Protocol Buffer map usage error:\n" + << "MapValueConstRef::type MapValueConstRef is not initialized."; + } + return type_; + } + + private: + template + friend class internal::MapField; + template + friend class internal::TypeDefinedMapFieldBase; + friend class ::PROTOBUF_NAMESPACE_ID::MapIterator; + friend class Reflection; + friend class internal::DynamicMapField; + + void SetType(FieldDescriptor::CppType type) { type_ = type; } + void SetValue(const void* val) { data_ = const_cast(val); } + void CopyFrom(const MapValueConstRef& other) { + type_ = other.type_; + data_ = other.data_; + } +}; + +// MapValueRef points to a map value. Users are able to modify +// the map value. +class PROTOBUF_EXPORT MapValueRef final : public MapValueConstRef { + public: + MapValueRef() {} + + void SetInt64Value(int64_t value) { + TYPE_CHECK(FieldDescriptor::CPPTYPE_INT64, "MapValueRef::SetInt64Value"); + *reinterpret_cast(data_) = value; + } + void SetUInt64Value(uint64_t value) { + TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT64, "MapValueRef::SetUInt64Value"); + *reinterpret_cast(data_) = value; + } + void SetInt32Value(int32_t value) { + TYPE_CHECK(FieldDescriptor::CPPTYPE_INT32, "MapValueRef::SetInt32Value"); + *reinterpret_cast(data_) = value; + } + void SetUInt32Value(uint32_t value) { + TYPE_CHECK(FieldDescriptor::CPPTYPE_UINT32, "MapValueRef::SetUInt32Value"); + *reinterpret_cast(data_) = value; + } + void SetBoolValue(bool value) { + TYPE_CHECK(FieldDescriptor::CPPTYPE_BOOL, "MapValueRef::SetBoolValue"); + *reinterpret_cast(data_) = value; + } + // TODO(jieluo) - Checks that enum is member. + void SetEnumValue(int value) { + TYPE_CHECK(FieldDescriptor::CPPTYPE_ENUM, "MapValueRef::SetEnumValue"); + *reinterpret_cast(data_) = value; + } + void SetStringValue(const std::string& value) { + TYPE_CHECK(FieldDescriptor::CPPTYPE_STRING, "MapValueRef::SetStringValue"); + *reinterpret_cast(data_) = value; + } + void SetFloatValue(float value) { + TYPE_CHECK(FieldDescriptor::CPPTYPE_FLOAT, "MapValueRef::SetFloatValue"); + *reinterpret_cast(data_) = value; + } + void SetDoubleValue(double value) { + TYPE_CHECK(FieldDescriptor::CPPTYPE_DOUBLE, "MapValueRef::SetDoubleValue"); + *reinterpret_cast(data_) = value; + } + + Message* MutableMessageValue() { + TYPE_CHECK(FieldDescriptor::CPPTYPE_MESSAGE, + "MapValueRef::MutableMessageValue"); + return reinterpret_cast(data_); + } + + private: + friend class internal::DynamicMapField; + + // Only used in DynamicMapField + void DeleteData() { + switch (type_) { +#define HANDLE_TYPE(CPPTYPE, TYPE) \ + case FieldDescriptor::CPPTYPE_##CPPTYPE: { \ + delete reinterpret_cast(data_); \ + break; \ + } + HANDLE_TYPE(INT32, int32_t); + HANDLE_TYPE(INT64, int64_t); + HANDLE_TYPE(UINT32, uint32_t); + HANDLE_TYPE(UINT64, uint64_t); + HANDLE_TYPE(DOUBLE, double); + HANDLE_TYPE(FLOAT, float); + HANDLE_TYPE(BOOL, bool); + HANDLE_TYPE(STRING, std::string); + HANDLE_TYPE(ENUM, int32_t); + HANDLE_TYPE(MESSAGE, Message); +#undef HANDLE_TYPE + } + } +}; + +#undef TYPE_CHECK + +class PROTOBUF_EXPORT MapIterator { + public: + MapIterator(Message* message, const FieldDescriptor* field) { + const Reflection* reflection = message->GetReflection(); + map_ = reflection->MutableMapData(message, field); + key_.SetType(field->message_type()->map_key()->cpp_type()); + value_.SetType(field->message_type()->map_value()->cpp_type()); + map_->InitializeIterator(this); + } + MapIterator(const MapIterator& other) { + map_ = other.map_; + map_->InitializeIterator(this); + map_->CopyIterator(this, other); + } + ~MapIterator() { map_->DeleteIterator(this); } + MapIterator& operator=(const MapIterator& other) { + map_ = other.map_; + map_->CopyIterator(this, other); + return *this; + } + friend bool operator==(const MapIterator& a, const MapIterator& b) { + return a.map_->EqualIterator(a, b); + } + friend bool operator!=(const MapIterator& a, const MapIterator& b) { + return !a.map_->EqualIterator(a, b); + } + MapIterator& operator++() { + map_->IncreaseIterator(this); + return *this; + } + MapIterator operator++(int) { + // iter_ is copied from Map<...>::iterator, no need to + // copy from its self again. Use the same implementation + // with operator++() + map_->IncreaseIterator(this); + return *this; + } + const MapKey& GetKey() { return key_; } + const MapValueRef& GetValueRef() { return value_; } + MapValueRef* MutableValueRef() { + map_->SetMapDirty(); + return &value_; + } + + private: + template + friend class internal::TypeDefinedMapFieldBase; + friend class internal::DynamicMapField; + template + friend class internal::MapField; + + // reinterpret_cast from heap-allocated Map<...>::iterator*. MapIterator owns + // the iterator. It is allocated by MapField<...>::InitializeIterator() called + // in constructor and deleted by MapField<...>::DeleteIterator() called in + // destructor. + void* iter_; + // Point to a MapField to call helper methods implemented in MapField. + // MapIterator does not own this object. + internal::MapFieldBase* map_; + MapKey key_; + MapValueRef value_; +}; + +} // namespace protobuf +} // namespace google + +#include + +#endif // GOOGLE_PROTOBUF_MAP_FIELD_H__ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/map_lite_test_util.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/map_lite_test_util.h new file mode 100644 index 0000000..573de7b --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/map_lite_test_util.h @@ -0,0 +1,80 @@ +// 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_MAP_LITE_TEST_UTIL_H__ +#define GOOGLE_PROTOBUF_MAP_LITE_TEST_UTIL_H__ + +#include + +namespace google { +namespace protobuf { + +class MapLiteTestUtil { + public: + // Set every field in the TestMapLite message to a unique value. + static void SetMapFields(protobuf_unittest::TestMapLite* message); + + // Set every field in the TestArenaMapLite message to a unique value. + static void SetArenaMapFields(protobuf_unittest::TestArenaMapLite* message); + + // Set every field in the message to a default value. + static void SetMapFieldsInitialized(protobuf_unittest::TestMapLite* message); + + // Modify all the map fields of the message (which should already have been + // initialized with SetMapFields()). + static void ModifyMapFields(protobuf_unittest::TestMapLite* message); + + // Check that all fields have the values that they should have after + // SetMapFields() is called. + static void ExpectMapFieldsSet(const protobuf_unittest::TestMapLite& message); + + // Check that all fields have the values that they should have after + // SetMapFields() is called for TestArenaMapLite. + static void ExpectArenaMapFieldsSet( + const protobuf_unittest::TestArenaMapLite& message); + + // Check that all fields have the values that they should have after + // SetMapFieldsInitialized() is called. + static void ExpectMapFieldsSetInitialized( + const protobuf_unittest::TestMapLite& message); + + // Expect that the message is modified as would be expected from + // ModifyMapFields(). + static void ExpectMapFieldsModified( + const protobuf_unittest::TestMapLite& message); + + // Check that all fields are empty. + static void ExpectClear(const protobuf_unittest::TestMapLite& message); +}; + +} // namespace protobuf +} // namespace google + +#endif // GOOGLE_PROTOBUF_MAP_LITE_TEST_UTIL_H__ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/map_test.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/map_test.cc new file mode 100644 index 0000000..c9be28b --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/map_test.cc @@ -0,0 +1,63 @@ +// 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. + +#include +#include +#include +#include + + +#define BRIDGE_UNITTEST ::google::protobuf::bridge_unittest +#define UNITTEST ::protobuf_unittest +#define UNITTEST_IMPORT ::protobuf_unittest_import +#define UNITTEST_PACKAGE_NAME "protobuf_unittest" + +// Must include after defining UNITTEST, etc. +// clang-format off +#include +#include +#include +// clang-format on + +// Must be included last. +#include + +namespace google { +namespace protobuf { +namespace internal { +namespace { + + + + +} // namespace +} // namespace internal +} // namespace protobuf +} // namespace google diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/proto3_arena_unittest.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/proto3_arena_unittest.cc new file mode 100644 index 0000000..5588f91 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/proto3_arena_unittest.cc @@ -0,0 +1,632 @@ +// 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. + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Must be included last. +#include + +using proto3_arena_unittest::ForeignMessage; +using proto3_arena_unittest::TestAllTypes; + +namespace google { +namespace protobuf { + +namespace internal { + +class Proto3ArenaTestHelper { + public: + template + static Arena* GetOwningArena(const T& msg) { + return msg.GetOwningArena(); + } +}; + +} // namespace internal + +namespace { +// We selectively set/check a few representative fields rather than all fields +// as this test is only expected to cover the basics of arena support. +void SetAllFields(TestAllTypes* m) { + m->set_optional_int32(100); + m->set_optional_string("asdf"); + m->set_optional_bytes("jkl;"); + m->mutable_optional_nested_message()->set_bb(42); + m->mutable_optional_foreign_message()->set_c(43); + m->set_optional_nested_enum(proto3_arena_unittest::TestAllTypes::BAZ); + m->set_optional_foreign_enum(proto3_arena_unittest::FOREIGN_BAZ); + m->mutable_optional_lazy_message()->set_bb(45); + m->add_repeated_int32(100); + m->add_repeated_string("asdf"); + m->add_repeated_bytes("jkl;"); + m->add_repeated_nested_message()->set_bb(46); + m->add_repeated_foreign_message()->set_c(47); + m->add_repeated_nested_enum(proto3_arena_unittest::TestAllTypes::BAZ); + m->add_repeated_foreign_enum(proto3_arena_unittest::FOREIGN_BAZ); + m->add_repeated_lazy_message()->set_bb(49); + + m->set_oneof_uint32(1); + m->mutable_oneof_nested_message()->set_bb(50); + m->set_oneof_string("test"); // only this one remains set +} + +void ExpectAllFieldsSet(const TestAllTypes& m) { + EXPECT_EQ(100, m.optional_int32()); + EXPECT_EQ("asdf", m.optional_string()); + EXPECT_EQ("jkl;", m.optional_bytes()); + EXPECT_EQ(true, m.has_optional_nested_message()); + 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_unittest::TestAllTypes::BAZ, m.optional_nested_enum()); + 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()); + + EXPECT_EQ(1, m.repeated_int32_size()); + EXPECT_EQ(100, m.repeated_int32(0)); + EXPECT_EQ(1, m.repeated_string_size()); + EXPECT_EQ("asdf", m.repeated_string(0)); + EXPECT_EQ(1, m.repeated_bytes_size()); + EXPECT_EQ("jkl;", m.repeated_bytes(0)); + EXPECT_EQ(1, m.repeated_nested_message_size()); + EXPECT_EQ(46, m.repeated_nested_message(0).bb()); + 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_unittest::TestAllTypes::BAZ, + m.repeated_nested_enum(0)); + EXPECT_EQ(1, m.repeated_foreign_enum_size()); + 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_unittest::TestAllTypes::kOneofString, + m.oneof_field_case()); + EXPECT_EQ("test", m.oneof_string()); +} + +// In this file we only test some basic functionalities of arena support in +// proto3 and expect the arena support to be fully tested in proto2 unittests +// because proto3 shares most code with proto2. + +TEST(Proto3ArenaTest, Parsing) { + TestAllTypes original; + SetAllFields(&original); + + Arena arena; + TestAllTypes* arena_message = Arena::CreateMessage(&arena); + arena_message->ParseFromString(original.SerializeAsString()); + ExpectAllFieldsSet(*arena_message); +} + +TEST(Proto3ArenaTest, UnknownFields) { + TestAllTypes original; + SetAllFields(&original); + + Arena arena; + TestAllTypes* arena_message = Arena::CreateMessage(&arena); + arena_message->ParseFromString(original.SerializeAsString()); + ExpectAllFieldsSet(*arena_message); + + // In proto3 we can still get a pointer to the UnknownFieldSet through + // reflection API. + UnknownFieldSet* unknown_fields = + arena_message->GetReflection()->MutableUnknownFields(arena_message); + // We can modify this UnknownFieldSet. + unknown_fields->AddVarint(1, 2); + // And the unknown fields should be changed. + ASSERT_NE(original.ByteSizeLong(), arena_message->ByteSizeLong()); + ASSERT_FALSE( + arena_message->GetReflection()->GetUnknownFields(*arena_message).empty()); +} + +TEST(Proto3ArenaTest, GetArena) { + Arena arena; + + // Tests arena-allocated message and submessages. + auto* arena_message1 = Arena::CreateMessage(&arena); + auto* arena_submessage1 = arena_message1->mutable_optional_foreign_message(); + auto* arena_repeated_submessage1 = + arena_message1->add_repeated_foreign_message(); + EXPECT_EQ(&arena, arena_message1->GetArena()); + EXPECT_EQ(&arena, arena_submessage1->GetArena()); + EXPECT_EQ(&arena, arena_repeated_submessage1->GetArena()); + + // Tests attached heap-allocated messages. + auto* arena_message2 = Arena::CreateMessage(&arena); + arena_message2->set_allocated_optional_foreign_message(new ForeignMessage()); + arena_message2->mutable_repeated_foreign_message()->AddAllocated( + new ForeignMessage()); + const auto& submessage2 = arena_message2->optional_foreign_message(); + const auto& repeated_submessage2 = + arena_message2->repeated_foreign_message(0); + EXPECT_EQ(nullptr, submessage2.GetArena()); + EXPECT_EQ(nullptr, repeated_submessage2.GetArena()); + + // Tests message created by Arena::Create. + auto* arena_message3 = Arena::Create(&arena); + EXPECT_EQ(nullptr, arena_message3->GetArena()); +} + +TEST(Proto3ArenaTest, GetArenaWithUnknown) { + Arena arena; + + // Tests arena-allocated message and submessages. + auto* arena_message1 = Arena::CreateMessage(&arena); + arena_message1->GetReflection()->MutableUnknownFields(arena_message1); + auto* arena_submessage1 = arena_message1->mutable_optional_foreign_message(); + arena_submessage1->GetReflection()->MutableUnknownFields(arena_submessage1); + auto* arena_repeated_submessage1 = + arena_message1->add_repeated_foreign_message(); + arena_repeated_submessage1->GetReflection()->MutableUnknownFields( + arena_repeated_submessage1); + EXPECT_EQ(&arena, arena_message1->GetArena()); + EXPECT_EQ(&arena, arena_submessage1->GetArena()); + EXPECT_EQ(&arena, arena_repeated_submessage1->GetArena()); + + // Tests attached heap-allocated messages. + auto* arena_message2 = Arena::CreateMessage(&arena); + arena_message2->set_allocated_optional_foreign_message(new ForeignMessage()); + arena_message2->mutable_repeated_foreign_message()->AddAllocated( + new ForeignMessage()); + auto* submessage2 = arena_message2->mutable_optional_foreign_message(); + submessage2->GetReflection()->MutableUnknownFields(submessage2); + auto* repeated_submessage2 = + arena_message2->mutable_repeated_foreign_message(0); + repeated_submessage2->GetReflection()->MutableUnknownFields( + repeated_submessage2); + EXPECT_EQ(nullptr, submessage2->GetArena()); + EXPECT_EQ(nullptr, repeated_submessage2->GetArena()); +} + +TEST(Proto3ArenaTest, Swap) { + Arena arena1; + Arena arena2; + + // Test Swap(). + TestAllTypes* arena1_message = Arena::CreateMessage(&arena1); + TestAllTypes* arena2_message = Arena::CreateMessage(&arena2); + arena1_message->Swap(arena2_message); + EXPECT_EQ(&arena1, arena1_message->GetArena()); + EXPECT_EQ(&arena2, arena2_message->GetArena()); +} + +TEST(Proto3ArenaTest, SetAllocatedMessage) { + Arena arena; + TestAllTypes* arena_message = Arena::CreateMessage(&arena); + TestAllTypes::NestedMessage* nested = new TestAllTypes::NestedMessage; + nested->set_bb(118); + arena_message->set_allocated_optional_nested_message(nested); + EXPECT_EQ(118, arena_message->optional_nested_message().bb()); +} + +TEST(Proto3ArenaTest, ReleaseMessage) { + Arena arena; + TestAllTypes* arena_message = Arena::CreateMessage(&arena); + arena_message->mutable_optional_nested_message()->set_bb(118); + std::unique_ptr nested( + arena_message->release_optional_nested_message()); + EXPECT_EQ(118, nested->bb()); +} + +TEST(Proto3ArenaTest, MessageFieldClear) { + // GitHub issue #310: https://github.com/protocolbuffers/protobuf/issues/310 + Arena arena; + TestAllTypes* arena_message = Arena::CreateMessage(&arena); + arena_message->mutable_optional_nested_message()->set_bb(118); + // This should not crash, but prior to the bugfix, it tried to use `operator + // delete` the nested message (which is on the arena): + arena_message->Clear(); +} + +TEST(Proto3ArenaTest, MessageFieldClearViaReflection) { + Arena arena; + TestAllTypes* message = Arena::CreateMessage(&arena); + const Reflection* r = message->GetReflection(); + const Descriptor* d = message->GetDescriptor(); + const FieldDescriptor* msg_field = + d->FindFieldByName("optional_nested_message"); + + message->mutable_optional_nested_message()->set_bb(1); + r->ClearField(message, msg_field); + EXPECT_FALSE(message->has_optional_nested_message()); + EXPECT_EQ(0, message->optional_nested_message().bb()); +} + +TEST(Proto3OptionalTest, OptionalFields) { + protobuf_unittest::TestProto3Optional msg; + EXPECT_FALSE(msg.has_optional_int32()); + msg.set_optional_int32(0); + EXPECT_TRUE(msg.has_optional_int32()); + + std::string serialized; + msg.SerializeToString(&serialized); + EXPECT_GT(serialized.size(), 0); + + msg.clear_optional_int32(); + EXPECT_FALSE(msg.has_optional_int32()); + msg.SerializeToString(&serialized); + EXPECT_EQ(serialized.size(), 0); +} + +TEST(Proto3OptionalTest, OptionalFieldDescriptor) { + const Descriptor* d = protobuf_unittest::TestProto3Optional::descriptor(); + + for (int i = 0; i < d->field_count(); i++) { + const FieldDescriptor* f = d->field(i); + if (HasPrefixString(f->name(), "singular")) { + EXPECT_FALSE(f->has_optional_keyword()) << f->full_name(); + EXPECT_FALSE(f->has_presence()) << f->full_name(); + EXPECT_FALSE(f->containing_oneof()) << f->full_name(); + } else { + EXPECT_TRUE(f->has_optional_keyword()) << f->full_name(); + EXPECT_TRUE(f->has_presence()) << f->full_name(); + EXPECT_TRUE(f->containing_oneof()) << f->full_name(); + } + } +} + +TEST(Proto3OptionalTest, Extensions) { + const DescriptorPool* p = DescriptorPool::generated_pool(); + const FieldDescriptor* no_optional = p->FindExtensionByName( + "protobuf_unittest.Proto3OptionalExtensions.ext_no_optional"); + const FieldDescriptor* with_optional = p->FindExtensionByName( + "protobuf_unittest.Proto3OptionalExtensions.ext_with_optional"); + GOOGLE_CHECK(no_optional); + GOOGLE_CHECK(with_optional); + EXPECT_FALSE(no_optional->has_optional_keyword()); + EXPECT_TRUE(with_optional->has_optional_keyword()); + + const Descriptor* d = protobuf_unittest::Proto3OptionalExtensions::descriptor(); + EXPECT_TRUE(d->options().HasExtension( + protobuf_unittest::Proto3OptionalExtensions::ext_no_optional)); + EXPECT_TRUE(d->options().HasExtension( + protobuf_unittest::Proto3OptionalExtensions::ext_with_optional)); + EXPECT_EQ(8, d->options().GetExtension( + protobuf_unittest::Proto3OptionalExtensions::ext_no_optional)); + EXPECT_EQ(16, + d->options().GetExtension( + protobuf_unittest::Proto3OptionalExtensions::ext_with_optional)); + + const Descriptor* d2 = protobuf_unittest::TestProto3Optional::descriptor(); + EXPECT_FALSE(d2->options().HasExtension( + protobuf_unittest::Proto3OptionalExtensions::ext_no_optional)); + EXPECT_FALSE(d2->options().HasExtension( + protobuf_unittest::Proto3OptionalExtensions::ext_with_optional)); +} + +TEST(Proto3OptionalTest, OptionalField) { + protobuf_unittest::TestProto3Optional msg; + EXPECT_FALSE(msg.has_optional_int32()); + msg.set_optional_int32(0); + EXPECT_TRUE(msg.has_optional_int32()); + + std::string serialized; + msg.SerializeToString(&serialized); + EXPECT_GT(serialized.size(), 0); + + msg.clear_optional_int32(); + EXPECT_FALSE(msg.has_optional_int32()); + msg.SerializeToString(&serialized); + EXPECT_EQ(serialized.size(), 0); +} + +TEST(Proto3OptionalTest, OptionalFieldReflection) { + // Tests that oneof reflection works on synthetic oneofs. + // + // We test this more deeply elsewhere by parsing/serializing TextFormat (which + // doesn't treat synthetic oneofs specially, so reflects over them normally). + protobuf_unittest::TestProto3Optional msg; + const google::protobuf::Descriptor* d = msg.GetDescriptor(); + const google::protobuf::Reflection* r = msg.GetReflection(); + const google::protobuf::FieldDescriptor* f = d->FindFieldByName("optional_int32"); + const google::protobuf::OneofDescriptor* o = d->FindOneofByName("_optional_int32"); + GOOGLE_CHECK(f); + GOOGLE_CHECK(o); + EXPECT_TRUE(o->is_synthetic()); + + EXPECT_FALSE(r->HasField(msg, f)); + EXPECT_FALSE(r->HasOneof(msg, o)); + EXPECT_TRUE(r->GetOneofFieldDescriptor(msg, o) == nullptr); + + r->SetInt32(&msg, f, 123); + EXPECT_EQ(123, msg.optional_int32()); + EXPECT_EQ(123, r->GetInt32(msg, f)); + EXPECT_TRUE(r->HasField(msg, f)); + EXPECT_TRUE(r->HasOneof(msg, o)); + EXPECT_EQ(f, r->GetOneofFieldDescriptor(msg, o)); + + std::vector fields; + r->ListFields(msg, &fields); + EXPECT_EQ(1, fields.size()); + EXPECT_EQ(f, fields[0]); + + r->ClearOneof(&msg, o); + EXPECT_FALSE(r->HasField(msg, f)); + EXPECT_FALSE(r->HasOneof(msg, o)); + EXPECT_TRUE(r->GetOneofFieldDescriptor(msg, o) == nullptr); + + msg.set_optional_int32(123); + EXPECT_EQ(123, r->GetInt32(msg, f)); + EXPECT_TRUE(r->HasField(msg, f)); + EXPECT_TRUE(r->HasOneof(msg, o)); + EXPECT_EQ(f, r->GetOneofFieldDescriptor(msg, o)); + + r->ClearOneof(&msg, o); + EXPECT_FALSE(r->HasField(msg, f)); + EXPECT_FALSE(r->HasOneof(msg, o)); + EXPECT_TRUE(r->GetOneofFieldDescriptor(msg, o) == nullptr); +} + +// It's a regression test for b/160665543. +TEST(Proto3OptionalTest, ClearNonOptionalMessageField) { + protobuf_unittest::TestProto3OptionalMessage msg; + msg.mutable_nested_message(); + const google::protobuf::Descriptor* d = msg.GetDescriptor(); + const google::protobuf::Reflection* r = msg.GetReflection(); + const google::protobuf::FieldDescriptor* f = d->FindFieldByName("nested_message"); + r->ClearField(&msg, f); +} + +TEST(Proto3OptionalTest, ClearOptionalMessageField) { + protobuf_unittest::TestProto3OptionalMessage msg; + msg.mutable_optional_nested_message(); + const google::protobuf::Descriptor* d = msg.GetDescriptor(); + const google::protobuf::Reflection* r = msg.GetReflection(); + const google::protobuf::FieldDescriptor* f = + d->FindFieldByName("optional_nested_message"); + r->ClearField(&msg, f); +} + +TEST(Proto3OptionalTest, SwapNonOptionalMessageField) { + protobuf_unittest::TestProto3OptionalMessage msg1; + protobuf_unittest::TestProto3OptionalMessage msg2; + msg1.mutable_nested_message(); + const google::protobuf::Descriptor* d = msg1.GetDescriptor(); + const google::protobuf::Reflection* r = msg1.GetReflection(); + const google::protobuf::FieldDescriptor* f = d->FindFieldByName("nested_message"); + r->SwapFields(&msg1, &msg2, {f}); +} + +TEST(Proto3OptionalTest, SwapOptionalMessageField) { + protobuf_unittest::TestProto3OptionalMessage msg1; + protobuf_unittest::TestProto3OptionalMessage msg2; + msg1.mutable_optional_nested_message(); + const google::protobuf::Descriptor* d = msg1.GetDescriptor(); + const google::protobuf::Reflection* r = msg1.GetReflection(); + const google::protobuf::FieldDescriptor* f = + d->FindFieldByName("optional_nested_message"); + r->SwapFields(&msg1, &msg2, {f}); +} + +void SetAllFieldsZero(protobuf_unittest::TestProto3Optional* msg) { + msg->set_optional_int32(0); + msg->set_optional_int64(0); + msg->set_optional_uint32(0); + msg->set_optional_uint64(0); + msg->set_optional_sint32(0); + msg->set_optional_sint64(0); + msg->set_optional_fixed32(0); + msg->set_optional_fixed64(0); + msg->set_optional_sfixed32(0); + msg->set_optional_sfixed64(0); + msg->set_optional_float(0); + msg->set_optional_double(0); + msg->set_optional_bool(false); + msg->set_optional_string(""); + msg->set_optional_bytes(""); + msg->mutable_optional_nested_message(); + msg->mutable_lazy_nested_message(); + msg->set_optional_nested_enum( + protobuf_unittest::TestProto3Optional::UNSPECIFIED); +} + +void SetAllFieldsNonZero(protobuf_unittest::TestProto3Optional* msg) { + msg->set_optional_int32(101); + msg->set_optional_int64(102); + msg->set_optional_uint32(103); + msg->set_optional_uint64(104); + msg->set_optional_sint32(105); + msg->set_optional_sint64(106); + msg->set_optional_fixed32(107); + msg->set_optional_fixed64(108); + msg->set_optional_sfixed32(109); + msg->set_optional_sfixed64(110); + msg->set_optional_float(111); + msg->set_optional_double(112); + msg->set_optional_bool(true); + msg->set_optional_string("abc"); + msg->set_optional_bytes("def"); + msg->mutable_optional_nested_message(); + msg->mutable_lazy_nested_message(); + msg->set_optional_nested_enum(protobuf_unittest::TestProto3Optional::BAZ); +} + +void TestAllFieldsZero(const protobuf_unittest::TestProto3Optional& msg) { + EXPECT_EQ(0, msg.optional_int32()); + EXPECT_EQ(0, msg.optional_int64()); + EXPECT_EQ(0, msg.optional_uint32()); + EXPECT_EQ(0, msg.optional_uint64()); + EXPECT_EQ(0, msg.optional_sint32()); + EXPECT_EQ(0, msg.optional_sint64()); + EXPECT_EQ(0, msg.optional_fixed32()); + EXPECT_EQ(0, msg.optional_fixed64()); + EXPECT_EQ(0, msg.optional_sfixed32()); + EXPECT_EQ(0, msg.optional_sfixed64()); + EXPECT_EQ(0, msg.optional_float()); + EXPECT_EQ(0, msg.optional_double()); + EXPECT_EQ(0, msg.optional_bool()); + EXPECT_EQ("", msg.optional_string()); + EXPECT_EQ("", msg.optional_bytes()); + EXPECT_EQ(protobuf_unittest::TestProto3Optional::UNSPECIFIED, + msg.optional_nested_enum()); + + const Reflection* r = msg.GetReflection(); + const Descriptor* d = msg.GetDescriptor(); + EXPECT_EQ("", r->GetString(msg, d->FindFieldByName("optional_string"))); +} + +void TestAllFieldsNonZero(const protobuf_unittest::TestProto3Optional& msg) { + EXPECT_EQ(101, msg.optional_int32()); + EXPECT_EQ(102, msg.optional_int64()); + EXPECT_EQ(103, msg.optional_uint32()); + EXPECT_EQ(104, msg.optional_uint64()); + EXPECT_EQ(105, msg.optional_sint32()); + EXPECT_EQ(106, msg.optional_sint64()); + EXPECT_EQ(107, msg.optional_fixed32()); + EXPECT_EQ(108, msg.optional_fixed64()); + EXPECT_EQ(109, msg.optional_sfixed32()); + EXPECT_EQ(110, msg.optional_sfixed64()); + EXPECT_EQ(111, msg.optional_float()); + EXPECT_EQ(112, msg.optional_double()); + EXPECT_EQ(true, msg.optional_bool()); + EXPECT_EQ("abc", msg.optional_string()); + EXPECT_EQ("def", msg.optional_bytes()); + EXPECT_EQ(protobuf_unittest::TestProto3Optional::BAZ, + msg.optional_nested_enum()); +} + +void TestAllFieldsSet(const protobuf_unittest::TestProto3Optional& msg, + bool set) { + EXPECT_EQ(set, msg.has_optional_int32()); + EXPECT_EQ(set, msg.has_optional_int64()); + EXPECT_EQ(set, msg.has_optional_uint32()); + EXPECT_EQ(set, msg.has_optional_uint64()); + EXPECT_EQ(set, msg.has_optional_sint32()); + EXPECT_EQ(set, msg.has_optional_sint64()); + EXPECT_EQ(set, msg.has_optional_fixed32()); + EXPECT_EQ(set, msg.has_optional_fixed64()); + EXPECT_EQ(set, msg.has_optional_sfixed32()); + EXPECT_EQ(set, msg.has_optional_sfixed64()); + EXPECT_EQ(set, msg.has_optional_float()); + EXPECT_EQ(set, msg.has_optional_double()); + EXPECT_EQ(set, msg.has_optional_bool()); + EXPECT_EQ(set, msg.has_optional_string()); + EXPECT_EQ(set, msg.has_optional_bytes()); + EXPECT_EQ(set, msg.has_optional_nested_message()); + EXPECT_EQ(set, msg.has_lazy_nested_message()); + EXPECT_EQ(set, msg.has_optional_nested_enum()); +} + +TEST(Proto3OptionalTest, BinaryRoundTrip) { + protobuf_unittest::TestProto3Optional msg; + TestAllFieldsSet(msg, false); + SetAllFieldsZero(&msg); + TestAllFieldsZero(msg); + TestAllFieldsSet(msg, true); + + protobuf_unittest::TestProto3Optional msg2; + std::string serialized; + msg.SerializeToString(&serialized); + EXPECT_TRUE(msg2.ParseFromString(serialized)); + TestAllFieldsZero(msg2); + TestAllFieldsSet(msg2, true); +} + +TEST(Proto3OptionalTest, TextFormatRoundTripZeros) { + protobuf_unittest::TestProto3Optional msg; + SetAllFieldsZero(&msg); + + protobuf_unittest::TestProto3Optional msg2; + std::string text; + EXPECT_TRUE(TextFormat::PrintToString(msg, &text)); + EXPECT_TRUE(TextFormat::ParseFromString(text, &msg2)); + TestAllFieldsSet(msg2, true); + TestAllFieldsZero(msg2); +} + +TEST(Proto3OptionalTest, TextFormatRoundTripNonZeros) { + protobuf_unittest::TestProto3Optional msg; + SetAllFieldsNonZero(&msg); + + protobuf_unittest::TestProto3Optional msg2; + std::string text; + EXPECT_TRUE(TextFormat::PrintToString(msg, &text)); + EXPECT_TRUE(TextFormat::ParseFromString(text, &msg2)); + TestAllFieldsSet(msg2, true); + TestAllFieldsNonZero(msg2); +} + +TEST(Proto3OptionalTest, SwapRoundTripZero) { + protobuf_unittest::TestProto3Optional msg; + SetAllFieldsZero(&msg); + TestAllFieldsSet(msg, true); + + protobuf_unittest::TestProto3Optional msg2; + msg.Swap(&msg2); + TestAllFieldsSet(msg2, true); + TestAllFieldsZero(msg2); +} + +TEST(Proto3OptionalTest, SwapRoundTripNonZero) { + protobuf_unittest::TestProto3Optional msg; + SetAllFieldsNonZero(&msg); + TestAllFieldsSet(msg, true); + + protobuf_unittest::TestProto3Optional msg2; + msg.Swap(&msg2); + TestAllFieldsSet(msg2, true); + TestAllFieldsNonZero(msg2); +} + +TEST(Proto3OptionalTest, ReflectiveSwapRoundTrip) { + protobuf_unittest::TestProto3Optional msg; + SetAllFieldsZero(&msg); + TestAllFieldsSet(msg, true); + + protobuf_unittest::TestProto3Optional msg2; + msg2.GetReflection()->Swap(&msg, &msg2); + TestAllFieldsSet(msg2, true); + TestAllFieldsZero(msg2); +} + +TEST(Proto3OptionalTest, PlainFields) { + const Descriptor* d = TestAllTypes::descriptor(); + + EXPECT_FALSE(d->FindFieldByName("optional_int32")->has_presence()); + EXPECT_TRUE(d->FindFieldByName("oneof_nested_message")->has_presence()); +} + +} // namespace +} // namespace protobuf +} // namespace google diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/reflection_ops.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/reflection_ops.cc new file mode 100644 index 0000000..8f0cfb9 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/reflection_ops.cc @@ -0,0 +1,454 @@ +// 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. +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace google { +namespace protobuf { +namespace internal { + +static const Reflection* GetReflectionOrDie(const Message& m) { + const Reflection* r = m.GetReflection(); + if (r == nullptr) { + const Descriptor* d = m.GetDescriptor(); + const std::string& mtype = d ? d->name() : "unknown"; + // RawMessage is one known type for which GetReflection() returns nullptr. + GOOGLE_LOG(FATAL) << "Message does not support reflection (type " << mtype << ")."; + } + return r; +} + +void ReflectionOps::Copy(const Message& from, Message* to) { + if (&from == to) return; + Clear(to); + Merge(from, to); +} + +void ReflectionOps::Merge(const Message& from, Message* to) { + GOOGLE_CHECK_NE(&from, to); + + const Descriptor* descriptor = from.GetDescriptor(); + GOOGLE_CHECK_EQ(to->GetDescriptor(), descriptor) + << "Tried to merge messages of different types " + << "(merge " << descriptor->full_name() << " to " + << to->GetDescriptor()->full_name() << ")"; + + const Reflection* from_reflection = GetReflectionOrDie(from); + const Reflection* to_reflection = GetReflectionOrDie(*to); + bool is_from_generated = (from_reflection->GetMessageFactory() == + google::protobuf::MessageFactory::generated_factory()); + bool is_to_generated = (to_reflection->GetMessageFactory() == + google::protobuf::MessageFactory::generated_factory()); + + std::vector fields; + from_reflection->ListFieldsOmitStripped(from, &fields); + for (const FieldDescriptor* field : fields) { + if (field->is_repeated()) { + // Use map reflection if both are in map status and have the + // same map type to avoid sync with repeated field. + // Note: As from and to messages have the same descriptor, the + // map field types are the same if they are both generated + // messages or both dynamic messages. + if (is_from_generated == is_to_generated && field->is_map()) { + const MapFieldBase* from_field = + from_reflection->GetMapData(from, field); + MapFieldBase* to_field = to_reflection->MutableMapData(to, field); + if (to_field->IsMapValid() && from_field->IsMapValid()) { + to_field->MergeFrom(*from_field); + continue; + } + } + int count = from_reflection->FieldSize(from, field); + for (int j = 0; j < count; j++) { + switch (field->cpp_type()) { +#define HANDLE_TYPE(CPPTYPE, METHOD) \ + case FieldDescriptor::CPPTYPE_##CPPTYPE: \ + to_reflection->Add##METHOD( \ + to, field, from_reflection->GetRepeated##METHOD(from, field, j)); \ + break; + + HANDLE_TYPE(INT32, Int32); + HANDLE_TYPE(INT64, Int64); + HANDLE_TYPE(UINT32, UInt32); + HANDLE_TYPE(UINT64, UInt64); + HANDLE_TYPE(FLOAT, Float); + HANDLE_TYPE(DOUBLE, Double); + HANDLE_TYPE(BOOL, Bool); + HANDLE_TYPE(STRING, String); + HANDLE_TYPE(ENUM, Enum); +#undef HANDLE_TYPE + + case FieldDescriptor::CPPTYPE_MESSAGE: + const Message& from_child = + from_reflection->GetRepeatedMessage(from, field, j); + if (from_reflection == to_reflection) { + to_reflection + ->AddMessage(to, field, + from_child.GetReflection()->GetMessageFactory()) + ->MergeFrom(from_child); + } else { + to_reflection->AddMessage(to, field)->MergeFrom(from_child); + } + break; + } + } + } else { + switch (field->cpp_type()) { +#define HANDLE_TYPE(CPPTYPE, METHOD) \ + case FieldDescriptor::CPPTYPE_##CPPTYPE: \ + to_reflection->Set##METHOD(to, field, \ + from_reflection->Get##METHOD(from, field)); \ + break; + + HANDLE_TYPE(INT32, Int32); + HANDLE_TYPE(INT64, Int64); + HANDLE_TYPE(UINT32, UInt32); + HANDLE_TYPE(UINT64, UInt64); + HANDLE_TYPE(FLOAT, Float); + HANDLE_TYPE(DOUBLE, Double); + HANDLE_TYPE(BOOL, Bool); + HANDLE_TYPE(STRING, String); + HANDLE_TYPE(ENUM, Enum); +#undef HANDLE_TYPE + + case FieldDescriptor::CPPTYPE_MESSAGE: + const Message& from_child = from_reflection->GetMessage(from, field); + if (from_reflection == to_reflection) { + to_reflection + ->MutableMessage( + to, field, from_child.GetReflection()->GetMessageFactory()) + ->MergeFrom(from_child); + } else { + to_reflection->MutableMessage(to, field)->MergeFrom(from_child); + } + break; + } + } + } + + to_reflection->MutableUnknownFields(to)->MergeFrom( + from_reflection->GetUnknownFields(from)); +} + +void ReflectionOps::Clear(Message* message) { + const Reflection* reflection = GetReflectionOrDie(*message); + + std::vector fields; + reflection->ListFieldsOmitStripped(*message, &fields); + for (const FieldDescriptor* field : fields) { + reflection->ClearField(message, field); + } + + reflection->MutableUnknownFields(message)->Clear(); +} + +bool ReflectionOps::IsInitialized(const Message& message, bool check_fields, + bool check_descendants) { + const Descriptor* descriptor = message.GetDescriptor(); + const Reflection* reflection = GetReflectionOrDie(message); + if (const int field_count = descriptor->field_count()) { + const FieldDescriptor* begin = descriptor->field(0); + const FieldDescriptor* end = begin + field_count; + GOOGLE_DCHECK_EQ(descriptor->field(field_count - 1), end - 1); + + if (check_fields) { + // Check required fields of this message. + for (const FieldDescriptor* field = begin; field != end; ++field) { + if (field->is_required() && !reflection->HasField(message, field)) { + return false; + } + } + } + + if (check_descendants) { + for (const FieldDescriptor* field = begin; field != end; ++field) { + if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { + const Descriptor* message_type = field->message_type(); + if (PROTOBUF_PREDICT_FALSE(message_type->options().map_entry())) { + if (message_type->field(1)->cpp_type() == + FieldDescriptor::CPPTYPE_MESSAGE) { + const MapFieldBase* map_field = + reflection->GetMapData(message, field); + if (map_field->IsMapValid()) { + MapIterator it(const_cast(&message), field); + MapIterator end_map(const_cast(&message), field); + for (map_field->MapBegin(&it), map_field->MapEnd(&end_map); + it != end_map; ++it) { + if (!it.GetValueRef().GetMessageValue().IsInitialized()) { + return false; + } + } + } + } + } else if (field->is_repeated()) { + const int size = reflection->FieldSize(message, field); + for (int j = 0; j < size; j++) { + if (!reflection->GetRepeatedMessage(message, field, j) + .IsInitialized()) { + return false; + } + } + } else if (reflection->HasField(message, field)) { + if (!reflection->GetMessage(message, field).IsInitialized()) { + return false; + } + } + } + } + } + } + if (check_descendants && reflection->HasExtensionSet(message) && + !reflection->GetExtensionSet(message).IsInitialized()) { + return false; + } + return true; +} + +bool ReflectionOps::IsInitialized(const Message& message) { + const Descriptor* descriptor = message.GetDescriptor(); + const Reflection* reflection = GetReflectionOrDie(message); + + // Check required fields of this message. + { + const int field_count = descriptor->field_count(); + for (int i = 0; i < field_count; i++) { + if (descriptor->field(i)->is_required()) { + if (!reflection->HasField(message, descriptor->field(i))) { + return false; + } + } + } + } + + // Check that sub-messages are initialized. + std::vector fields; + // Should be safe to skip stripped fields because required fields are not + // stripped. + reflection->ListFieldsOmitStripped(message, &fields); + for (const FieldDescriptor* field : fields) { + if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { + + if (field->is_map()) { + const FieldDescriptor* value_field = field->message_type()->field(1); + if (value_field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { + const MapFieldBase* map_field = + reflection->GetMapData(message, field); + if (map_field->IsMapValid()) { + MapIterator iter(const_cast(&message), field); + MapIterator end(const_cast(&message), field); + for (map_field->MapBegin(&iter), map_field->MapEnd(&end); + iter != end; ++iter) { + if (!iter.GetValueRef().GetMessageValue().IsInitialized()) { + return false; + } + } + continue; + } + } else { + continue; + } + } + + if (field->is_repeated()) { + int size = reflection->FieldSize(message, field); + + for (int j = 0; j < size; j++) { + if (!reflection->GetRepeatedMessage(message, field, j) + .IsInitialized()) { + return false; + } + } + } else { + if (!reflection->GetMessage(message, field).IsInitialized()) { + return false; + } + } + } + } + + return true; +} + +static bool IsMapValueMessageTyped(const FieldDescriptor* map_field) { + return map_field->message_type()->field(1)->cpp_type() == + FieldDescriptor::CPPTYPE_MESSAGE; +} + +void ReflectionOps::DiscardUnknownFields(Message* message) { + const Reflection* reflection = GetReflectionOrDie(*message); + + reflection->MutableUnknownFields(message)->Clear(); + + // Walk through the fields of this message and DiscardUnknownFields on any + // messages present. + std::vector fields; + reflection->ListFields(*message, &fields); + for (const FieldDescriptor* field : fields) { + // Skip over non-message fields. + if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) { + continue; + } + // Discard the unknown fields in maps that contain message values. + if (field->is_map() && IsMapValueMessageTyped(field)) { + const MapFieldBase* map_field = + reflection->MutableMapData(message, field); + if (map_field->IsMapValid()) { + MapIterator iter(message, field); + MapIterator end(message, field); + for (map_field->MapBegin(&iter), map_field->MapEnd(&end); iter != end; + ++iter) { + iter.MutableValueRef()->MutableMessageValue()->DiscardUnknownFields(); + } + } + // Discard every unknown field inside messages in a repeated field. + } else if (field->is_repeated()) { + int size = reflection->FieldSize(*message, field); + for (int j = 0; j < size; j++) { + reflection->MutableRepeatedMessage(message, field, j) + ->DiscardUnknownFields(); + } + // Discard the unknown fields inside an optional message. + } else { + reflection->MutableMessage(message, field)->DiscardUnknownFields(); + } + } +} + +static std::string SubMessagePrefix(const std::string& prefix, + const FieldDescriptor* field, int index) { + std::string result(prefix); + if (field->is_extension()) { + result.append("("); + result.append(field->full_name()); + result.append(")"); + } else { + result.append(field->name()); + } + if (index != -1) { + result.append("["); + result.append(StrCat(index)); + result.append("]"); + } + result.append("."); + return result; +} + +void ReflectionOps::FindInitializationErrors(const Message& message, + const std::string& prefix, + std::vector* errors) { + const Descriptor* descriptor = message.GetDescriptor(); + const Reflection* reflection = GetReflectionOrDie(message); + + // Check required fields of this message. + { + const int field_count = descriptor->field_count(); + for (int i = 0; i < field_count; i++) { + if (descriptor->field(i)->is_required()) { + if (!reflection->HasField(message, descriptor->field(i))) { + errors->push_back(prefix + descriptor->field(i)->name()); + } + } + } + } + + // Check sub-messages. + std::vector fields; + reflection->ListFieldsOmitStripped(message, &fields); + for (const FieldDescriptor* field : fields) { + if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { + + if (field->is_repeated()) { + int size = reflection->FieldSize(message, field); + + for (int j = 0; j < size; j++) { + const Message& sub_message = + reflection->GetRepeatedMessage(message, field, j); + FindInitializationErrors(sub_message, + SubMessagePrefix(prefix, field, j), errors); + } + } else { + const Message& sub_message = reflection->GetMessage(message, field); + FindInitializationErrors(sub_message, + SubMessagePrefix(prefix, field, -1), errors); + } + } + } +} + +void GenericSwap(Message* lhs, Message* rhs) { +#ifndef PROTOBUF_FORCE_COPY_IN_SWAP + GOOGLE_DCHECK(Arena::InternalHelper::GetOwningArena(lhs) != + Arena::InternalHelper::GetOwningArena(rhs)); + GOOGLE_DCHECK(Arena::InternalHelper::GetOwningArena(lhs) != nullptr || + Arena::InternalHelper::GetOwningArena(rhs) != nullptr); +#endif // !PROTOBUF_FORCE_COPY_IN_SWAP + // At least one of these must have an arena, so make `rhs` point to it. + Arena* arena = Arena::InternalHelper::GetOwningArena(rhs); + if (arena == nullptr) { + std::swap(lhs, rhs); + arena = Arena::InternalHelper::GetOwningArena(rhs); + } + + // Improve efficiency by placing the temporary on an arena so that messages + // are copied twice rather than three times. + Message* tmp = rhs->New(arena); + tmp->CheckTypeAndMergeFrom(*lhs); + lhs->Clear(); + lhs->CheckTypeAndMergeFrom(*rhs); +#ifdef PROTOBUF_FORCE_COPY_IN_SWAP + rhs->Clear(); + rhs->CheckTypeAndMergeFrom(*tmp); + if (arena == nullptr) delete tmp; +#else // PROTOBUF_FORCE_COPY_IN_SWAP + rhs->GetReflection()->Swap(tmp, rhs); +#endif // !PROTOBUF_FORCE_COPY_IN_SWAP +} + +} // namespace internal +} // namespace protobuf +} // namespace google + +#include diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/repeated_ptr_field.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/repeated_ptr_field.cc new file mode 100644 index 0000000..0f0b3e2 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/repeated_ptr_field.cc @@ -0,0 +1,157 @@ +// 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. + +#include + +#include + +#include +#include +#include + +#include + +namespace google { +namespace protobuf { + +namespace internal { + +void** RepeatedPtrFieldBase::InternalExtend(int extend_amount) { + int new_size = current_size_ + extend_amount; + if (total_size_ >= new_size) { + // N.B.: rep_ is non-nullptr because extend_amount is always > 0, hence + // total_size must be non-zero since it is lower-bounded by new_size. + return &rep_->elements[current_size_]; + } + Rep* old_rep = rep_; + Arena* arena = GetArena(); + new_size = std::max(internal::kRepeatedFieldLowerClampLimit, + std::max(total_size_ * 2, new_size)); + GOOGLE_CHECK_LE(static_cast(new_size), + static_cast( + (std::numeric_limits::max() - kRepHeaderSize) / + sizeof(old_rep->elements[0]))) + << "Requested size is too large to fit into size_t."; + size_t bytes = kRepHeaderSize + sizeof(old_rep->elements[0]) * new_size; + if (arena == nullptr) { + rep_ = reinterpret_cast(::operator new(bytes)); + } else { + rep_ = reinterpret_cast(Arena::CreateArray(arena, bytes)); + } +#if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation) + const int old_total_size = total_size_; +#endif + total_size_ = new_size; + if (old_rep && old_rep->allocated_size > 0) { + memcpy(rep_->elements, old_rep->elements, + old_rep->allocated_size * sizeof(rep_->elements[0])); + rep_->allocated_size = old_rep->allocated_size; + } else { + rep_->allocated_size = 0; + } + if (arena == nullptr) { +#if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation) + const size_t old_size = + old_total_size * sizeof(rep_->elements[0]) + kRepHeaderSize; + ::operator delete(static_cast(old_rep), old_size); +#else + ::operator delete(static_cast(old_rep)); +#endif + } + return &rep_->elements[current_size_]; +} + +void RepeatedPtrFieldBase::Reserve(int new_size) { + if (new_size > current_size_) { + InternalExtend(new_size - current_size_); + } +} + +void RepeatedPtrFieldBase::DestroyProtos() { + GOOGLE_DCHECK(rep_); + GOOGLE_DCHECK(arena_ == nullptr); + int n = rep_->allocated_size; + void* const* elements = rep_->elements; + for (int i = 0; i < n; i++) { + delete static_cast(elements[i]); + } +#if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation) + const size_t size = total_size_ * sizeof(elements[0]) + kRepHeaderSize; + ::operator delete(static_cast(rep_), size); + rep_ = nullptr; +#else + ::operator delete(static_cast(rep_)); + rep_ = nullptr; +#endif +} + +void* RepeatedPtrFieldBase::AddOutOfLineHelper(void* obj) { + if (!rep_ || rep_->allocated_size == total_size_) { + InternalExtend(1); // Equivalent to "Reserve(total_size_ + 1)" + } + ++rep_->allocated_size; + rep_->elements[current_size_++] = obj; + return obj; +} + +void RepeatedPtrFieldBase::CloseGap(int start, int num) { + if (rep_ == nullptr) return; + // Close up a gap of "num" elements starting at offset "start". + for (int i = start + num; i < rep_->allocated_size; ++i) + rep_->elements[i - num] = rep_->elements[i]; + current_size_ -= num; + rep_->allocated_size -= num; +} + +MessageLite* RepeatedPtrFieldBase::AddWeak(const MessageLite* prototype) { + if (rep_ != nullptr && current_size_ < rep_->allocated_size) { + return reinterpret_cast(rep_->elements[current_size_++]); + } + if (!rep_ || rep_->allocated_size == total_size_) { + Reserve(total_size_ + 1); + } + ++rep_->allocated_size; + MessageLite* result = prototype + ? prototype->New(arena_) + : Arena::CreateMessage(arena_); + rep_->elements[current_size_++] = result; + return result; +} + +} // namespace internal + +} // namespace protobuf +} // namespace google + +#include diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/repeated_ptr_field.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/repeated_ptr_field.h new file mode 100644 index 0000000..3c813a9 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/repeated_ptr_field.h @@ -0,0 +1,2022 @@ +// 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. +// +// RepeatedField and RepeatedPtrField are used by generated protocol message +// classes to manipulate repeated fields. These classes are very similar to +// STL's vector, but include a number of optimizations found to be useful +// specifically in the case of Protocol Buffers. RepeatedPtrField is +// particularly different from STL vector as it manages ownership of the +// pointers that it contains. +// +// Typically, clients should not need to access RepeatedField objects directly, +// but should instead use the accessor functions generated automatically by the +// protocol compiler. +// +// This header covers RepeatedPtrField. + +#ifndef GOOGLE_PROTOBUF_REPEATED_PTR_FIELD_H__ +#define GOOGLE_PROTOBUF_REPEATED_PTR_FIELD_H__ + +#include +#ifdef _MSC_VER +// This is required for min/max on VS2013 only. +#include +#endif + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + + +// Must be included last. +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif + +namespace google { +namespace protobuf { + +class Message; +class Reflection; + +template +struct WeakRepeatedPtrField; + +namespace internal { + +class MergePartialFromCodedStreamHelper; +class SwapFieldHelper; + + +} // namespace internal + +namespace internal { +template +class RepeatedPtrIterator; +template +class RepeatedPtrOverPtrsIterator; +} // namespace internal + +namespace internal { + +// type-traits helper for RepeatedPtrFieldBase: we only want to invoke +// arena-related "copy if on different arena" behavior if the necessary methods +// exist on the contained type. In particular, we rely on MergeFrom() existing +// as a general proxy for the fact that a copy will work, and we also provide a +// specific override for std::string*. +template +struct TypeImplementsMergeBehaviorProbeForMergeFrom { + typedef char HasMerge; + typedef long HasNoMerge; + + // We accept either of: + // - void MergeFrom(const T& other) + // - bool MergeFrom(const T& other) + // + // We mangle these names a bit to avoid compatibility issues in 'unclean' + // include environments that may have, e.g., "#define test ..." (yes, this + // exists). + template + struct CheckType; + template + static HasMerge Check(CheckType*); + template + static HasMerge Check(CheckType*); + template + static HasNoMerge Check(...); + + // Resolves to either std::true_type or std::false_type. + typedef std::integral_constant(0)) == sizeof(HasMerge))> + type; +}; + +template +struct TypeImplementsMergeBehavior + : TypeImplementsMergeBehaviorProbeForMergeFrom {}; + + +template <> +struct TypeImplementsMergeBehavior { + typedef std::true_type type; +}; + +template +struct IsMovable + : std::integral_constant::value && + std::is_move_assignable::value> {}; + +// This is the common base class for RepeatedPtrFields. It deals only in void* +// pointers. Users should not use this interface directly. +// +// The methods of this interface correspond to the methods of RepeatedPtrField, +// but may have a template argument called TypeHandler. Its signature is: +// class TypeHandler { +// public: +// typedef MyType Type; +// static Type* New(); +// static Type* NewFromPrototype(const Type* prototype, +// Arena* arena); +// static void Delete(Type*); +// static void Clear(Type*); +// static void Merge(const Type& from, Type* to); +// +// // Only needs to be implemented if SpaceUsedExcludingSelf() is called. +// static int SpaceUsedLong(const Type&); +// }; +class PROTOBUF_EXPORT RepeatedPtrFieldBase { + protected: + constexpr RepeatedPtrFieldBase(); + explicit RepeatedPtrFieldBase(Arena* arena); + ~RepeatedPtrFieldBase() { +#ifndef NDEBUG + // Try to trigger segfault / asan failure in non-opt builds. If arena_ + // lifetime has ended before the destructor. + if (arena_) (void)arena_->SpaceAllocated(); +#endif + } + + // Must be called from destructor. + template + void Destroy(); + bool NeedsDestroy() const { return rep_ != nullptr && arena_ == nullptr; } + void DestroyProtos(); + + bool empty() const; + int size() const; + + template + const typename TypeHandler::Type& at(int index) const; + template + typename TypeHandler::Type& at(int index); + + template + typename TypeHandler::Type* Mutable(int index); + template + void Delete(int index); + template + typename TypeHandler::Type* Add( + typename TypeHandler::Type* prototype = nullptr); + + public: + // The next few methods are public so that they can be called from generated + // code when implicit weak fields are used, but they should never be called by + // application code. + + template + const typename TypeHandler::Type& Get(int index) const; + + // Creates and adds an element using the given prototype, without introducing + // a link-time dependency on the concrete message type. This method is used to + // implement implicit weak fields. The prototype may be nullptr, in which case + // an ImplicitWeakMessage will be used as a placeholder. + MessageLite* AddWeak(const MessageLite* prototype); + + template + void Clear(); + + template + void MergeFrom(const RepeatedPtrFieldBase& other); + + inline void InternalSwap(RepeatedPtrFieldBase*); + + protected: + template < + typename TypeHandler, + typename std::enable_if::type* = nullptr> + void Add(typename TypeHandler::Type&& value); + + template + void RemoveLast(); + template + void CopyFrom(const RepeatedPtrFieldBase& other); + + void CloseGap(int start, int num); + + void Reserve(int new_size); + + int Capacity() const; + + template + static inline typename TypeHandler::Type* copy( + typename TypeHandler::Type* value) { + auto* new_value = TypeHandler::NewFromPrototype(value, nullptr); + TypeHandler::Merge(*value, new_value); + return new_value; + } + + // Used for constructing iterators. + void* const* raw_data() const; + void** raw_mutable_data() const; + + template + typename TypeHandler::Type** mutable_data(); + template + const typename TypeHandler::Type* const* data() const; + + template + PROTOBUF_NDEBUG_INLINE void Swap(RepeatedPtrFieldBase* other); + + void SwapElements(int index1, int index2); + + template + size_t SpaceUsedExcludingSelfLong() const; + + // Advanced memory management -------------------------------------- + + // Like Add(), but if there are no cleared objects to use, returns nullptr. + template + typename TypeHandler::Type* AddFromCleared(); + + template + void AddAllocated(typename TypeHandler::Type* value) { + typename TypeImplementsMergeBehavior::type t; + AddAllocatedInternal(value, t); + } + + template + void UnsafeArenaAddAllocated(typename TypeHandler::Type* value); + + template + PROTOBUF_NODISCARD typename TypeHandler::Type* ReleaseLast() { + typename TypeImplementsMergeBehavior::type t; + return ReleaseLastInternal(t); + } + + // Releases last element and returns it, but does not do out-of-arena copy. + // And just returns the raw pointer to the contained element in the arena. + template + typename TypeHandler::Type* UnsafeArenaReleaseLast(); + + int ClearedCount() const; + template + void AddCleared(typename TypeHandler::Type* value); + template + PROTOBUF_NODISCARD typename TypeHandler::Type* ReleaseCleared(); + + template + void AddAllocatedInternal(typename TypeHandler::Type* value, std::true_type); + template + void AddAllocatedInternal(typename TypeHandler::Type* value, std::false_type); + + template + PROTOBUF_NOINLINE void AddAllocatedSlowWithCopy( + typename TypeHandler::Type* value, Arena* value_arena, Arena* my_arena); + template + PROTOBUF_NOINLINE void AddAllocatedSlowWithoutCopy( + typename TypeHandler::Type* value); + + template + typename TypeHandler::Type* ReleaseLastInternal(std::true_type); + template + typename TypeHandler::Type* ReleaseLastInternal(std::false_type); + + template + PROTOBUF_NOINLINE void SwapFallback(RepeatedPtrFieldBase* other); + + inline Arena* GetArena() const { return arena_; } + + private: + static constexpr int kInitialSize = 0; + // A few notes on internal representation: + // + // We use an indirected approach, with struct Rep, to keep + // sizeof(RepeatedPtrFieldBase) equivalent to what it was before arena support + // was added, namely, 3 8-byte machine words on x86-64. An instance of Rep is + // allocated only when the repeated field is non-empty, and it is a + // dynamically-sized struct (the header is directly followed by elements[]). + // We place arena_ and current_size_ directly in the object to avoid cache + // misses due to the indirection, because these fields are checked frequently. + // Placing all fields directly in the RepeatedPtrFieldBase instance costs + // significant performance for memory-sensitive workloads. + Arena* arena_; + int current_size_; + int total_size_; + struct Rep { + int allocated_size; + // Here we declare a huge array as a way of approximating C's "flexible + // array member" feature without relying on undefined behavior. + void* elements[(std::numeric_limits::max() - 2 * sizeof(int)) / + sizeof(void*)]; + }; + static constexpr size_t kRepHeaderSize = offsetof(Rep, elements); + Rep* rep_; + + template + static inline typename TypeHandler::Type* cast(void* element) { + return reinterpret_cast(element); + } + template + static inline const typename TypeHandler::Type* cast(const void* element) { + return reinterpret_cast(element); + } + + // Non-templated inner function to avoid code duplication. Takes a function + // pointer to the type-specific (templated) inner allocate/merge loop. + void MergeFromInternal(const RepeatedPtrFieldBase& other, + void (RepeatedPtrFieldBase::*inner_loop)(void**, + void**, int, + int)); + + template + PROTOBUF_NOINLINE void MergeFromInnerLoop(void** our_elems, + void** other_elems, int length, + int already_allocated); + + // Internal helper: extend array space if necessary to contain |extend_amount| + // more elements, and return a pointer to the element immediately following + // the old list of elements. This interface factors out common behavior from + // Reserve() and MergeFrom() to reduce code size. |extend_amount| must be > 0. + void** InternalExtend(int extend_amount); + + // Internal helper for Add: add "obj" as the next element in the + // array, including potentially resizing the array with Reserve if + // needed + void* AddOutOfLineHelper(void* obj); + + // The reflection implementation needs to call protected methods directly, + // reinterpreting pointers as being to Message instead of a specific Message + // subclass. + friend class ::PROTOBUF_NAMESPACE_ID::Reflection; + friend class ::PROTOBUF_NAMESPACE_ID::internal::SwapFieldHelper; + + // ExtensionSet stores repeated message extensions as + // RepeatedPtrField, but non-lite ExtensionSets need to implement + // SpaceUsedLong(), and thus need to call SpaceUsedExcludingSelfLong() + // reinterpreting MessageLite as Message. ExtensionSet also needs to make use + // of AddFromCleared(), which is not part of the public interface. + friend class ExtensionSet; + + // The MapFieldBase implementation needs to call protected methods directly, + // reinterpreting pointers as being to Message instead of a specific Message + // subclass. + friend class MapFieldBase; + friend class MapFieldBaseStub; + + // The table-driven MergePartialFromCodedStream implementation needs to + // operate on RepeatedPtrField. + friend class MergePartialFromCodedStreamHelper; + friend class AccessorHelper; + template + friend struct google::protobuf::WeakRepeatedPtrField; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPtrFieldBase); +}; + +template +class GenericTypeHandler { + public: + typedef GenericType Type; + using Movable = IsMovable; + + static inline GenericType* New(Arena* arena) { + return Arena::CreateMaybeMessage(arena); + } + static inline GenericType* New(Arena* arena, GenericType&& value) { + return Arena::Create(arena, std::move(value)); + } + static inline GenericType* NewFromPrototype(const GenericType* prototype, + Arena* arena = nullptr); + static inline void Delete(GenericType* value, Arena* arena) { + if (arena == nullptr) { + delete value; + } + } + static inline Arena* GetOwningArena(GenericType* value) { + return Arena::GetOwningArena(value); + } + + static inline void Clear(GenericType* value) { value->Clear(); } + PROTOBUF_NOINLINE + static void Merge(const GenericType& from, GenericType* to); + static inline size_t SpaceUsedLong(const GenericType& value) { + return value.SpaceUsedLong(); + } +}; + +template +GenericType* GenericTypeHandler::NewFromPrototype( + const GenericType* /* prototype */, Arena* arena) { + return New(arena); +} +template +void GenericTypeHandler::Merge(const GenericType& from, + GenericType* to) { + to->MergeFrom(from); +} + +// NewFromPrototype() and Merge() are not defined inline here, as we will need +// to do a virtual function dispatch anyways to go from Message* to call +// New/Merge. +template <> +MessageLite* GenericTypeHandler::NewFromPrototype( + const MessageLite* prototype, Arena* arena); +template <> +inline Arena* GenericTypeHandler::GetOwningArena( + MessageLite* value) { + return value->GetOwningArena(); +} +template <> +void GenericTypeHandler::Merge(const MessageLite& from, + MessageLite* to); +template <> +inline void GenericTypeHandler::Clear(std::string* value) { + value->clear(); +} +template <> +void GenericTypeHandler::Merge(const std::string& from, + std::string* to); + +// Message specialization bodies defined in message.cc. This split is necessary +// to allow proto2-lite (which includes this header) to be independent of +// Message. +template <> +PROTOBUF_EXPORT Message* GenericTypeHandler::NewFromPrototype( + const Message* prototype, Arena* arena); +template <> +PROTOBUF_EXPORT Arena* GenericTypeHandler::GetOwningArena( + Message* value); + +class StringTypeHandler { + public: + typedef std::string Type; + using Movable = IsMovable; + + static inline std::string* New(Arena* arena) { + return Arena::Create(arena); + } + static inline std::string* New(Arena* arena, std::string&& value) { + return Arena::Create(arena, std::move(value)); + } + static inline std::string* NewFromPrototype(const std::string*, + Arena* arena) { + return New(arena); + } + static inline Arena* GetOwningArena(std::string*) { return nullptr; } + static inline void Delete(std::string* value, Arena* arena) { + if (arena == nullptr) { + delete value; + } + } + static inline void Clear(std::string* value) { value->clear(); } + static inline void Merge(const std::string& from, std::string* to) { + *to = from; + } + static size_t SpaceUsedLong(const std::string& value) { + return sizeof(value) + StringSpaceUsedExcludingSelfLong(value); + } +}; + +} // namespace internal + +// RepeatedPtrField is like RepeatedField, but used for repeated strings or +// Messages. +template +class RepeatedPtrField final : private internal::RepeatedPtrFieldBase { + public: + constexpr RepeatedPtrField(); + explicit RepeatedPtrField(Arena* arena); + + RepeatedPtrField(const RepeatedPtrField& other); + + template ())>::value>::type> + RepeatedPtrField(Iter begin, Iter end); + + ~RepeatedPtrField(); + + RepeatedPtrField& operator=(const RepeatedPtrField& other); + + RepeatedPtrField(RepeatedPtrField&& other) noexcept; + RepeatedPtrField& operator=(RepeatedPtrField&& other) noexcept; + + bool empty() const; + int size() const; + + const Element& Get(int index) const; + Element* Mutable(int index); + Element* Add(); + void Add(Element&& value); + // Append elements in the range [begin, end) after reserving + // the appropriate number of elements. + template + void Add(Iter begin, Iter end); + + const Element& operator[](int index) const { return Get(index); } + Element& operator[](int index) { return *Mutable(index); } + + const Element& at(int index) const; + Element& at(int index); + + // Remove the last element in the array. + // Ownership of the element is retained by the array. + void RemoveLast(); + + // Delete elements with indices in the range [start .. start+num-1]. + // Caution: implementation moves all elements with indices [start+num .. ]. + // Calling this routine inside a loop can cause quadratic behavior. + void DeleteSubrange(int start, int num); + + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear(); + void MergeFrom(const RepeatedPtrField& other); + PROTOBUF_ATTRIBUTE_REINITIALIZES void CopyFrom(const RepeatedPtrField& other); + + // Replaces the contents with RepeatedPtrField(begin, end). + template + PROTOBUF_ATTRIBUTE_REINITIALIZES void Assign(Iter begin, Iter end); + + // Reserve space to expand the field to at least the given size. This only + // resizes the pointer array; it doesn't allocate any objects. If the + // array is grown, it will always be at least doubled in size. + void Reserve(int new_size); + + int Capacity() const; + + // Gets the underlying array. This pointer is possibly invalidated by + // any add or remove operation. + Element** mutable_data(); + const Element* const* data() const; + + // Swap entire contents with "other". If they are on separate arenas, then + // copies data. + void Swap(RepeatedPtrField* other); + + // Swap entire contents with "other". Caller should guarantee that either both + // fields are on the same arena or both are on the heap. Swapping between + // different arenas with this function is disallowed and is caught via + // GOOGLE_DCHECK. + void UnsafeArenaSwap(RepeatedPtrField* other); + + // Swap two elements. + void SwapElements(int index1, int index2); + + // STL-like iterator support + typedef internal::RepeatedPtrIterator iterator; + typedef internal::RepeatedPtrIterator const_iterator; + typedef Element value_type; + typedef value_type& reference; + typedef const value_type& const_reference; + typedef value_type* pointer; + typedef const value_type* const_pointer; + typedef int size_type; + typedef ptrdiff_t difference_type; + + iterator begin(); + const_iterator begin() const; + const_iterator cbegin() const; + iterator end(); + const_iterator end() const; + const_iterator cend() const; + + // Reverse iterator support + typedef std::reverse_iterator const_reverse_iterator; + typedef std::reverse_iterator reverse_iterator; + reverse_iterator rbegin() { return reverse_iterator(end()); } + const_reverse_iterator rbegin() const { + return const_reverse_iterator(end()); + } + reverse_iterator rend() { return reverse_iterator(begin()); } + const_reverse_iterator rend() const { + return const_reverse_iterator(begin()); + } + + // Custom STL-like iterator that iterates over and returns the underlying + // pointers to Element rather than Element itself. + typedef internal::RepeatedPtrOverPtrsIterator + pointer_iterator; + typedef internal::RepeatedPtrOverPtrsIterator + const_pointer_iterator; + pointer_iterator pointer_begin(); + const_pointer_iterator pointer_begin() const; + pointer_iterator pointer_end(); + const_pointer_iterator pointer_end() const; + + // Returns (an estimate of) the number of bytes used by the repeated field, + // excluding sizeof(*this). + size_t SpaceUsedExcludingSelfLong() const; + + int SpaceUsedExcludingSelf() const { + return internal::ToIntSize(SpaceUsedExcludingSelfLong()); + } + + // Advanced memory management -------------------------------------- + // When hardcore memory management becomes necessary -- as it sometimes + // does here at Google -- the following methods may be useful. + + // Add an already-allocated object, passing ownership to the + // RepeatedPtrField. + // + // Note that some special behavior occurs with respect to arenas: + // + // (i) if this field holds submessages, the new submessage will be copied if + // the original is in an arena and this RepeatedPtrField is either in a + // different arena, or on the heap. + // (ii) if this field holds strings, the passed-in string *must* be + // heap-allocated, not arena-allocated. There is no way to dynamically check + // this at runtime, so User Beware. + void AddAllocated(Element* value); + + // Remove the last element and return it, passing ownership to the caller. + // Requires: size() > 0 + // + // If this RepeatedPtrField is on an arena, an object copy is required to pass + // ownership back to the user (for compatible semantics). Use + // UnsafeArenaReleaseLast() if this behavior is undesired. + PROTOBUF_NODISCARD Element* ReleaseLast(); + + // Add an already-allocated object, skipping arena-ownership checks. The user + // must guarantee that the given object is in the same arena as this + // RepeatedPtrField. + // It is also useful in legacy code that uses temporary ownership to avoid + // copies. Example: + // RepeatedPtrField temp_field; + // temp_field.UnsafeArenaAddAllocated(new T); + // ... // Do something with temp_field + // temp_field.UnsafeArenaExtractSubrange(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. + void UnsafeArenaAddAllocated(Element* value); + + // Remove the last element and return it. Unlike ReleaseLast, the returned + // pointer is always to the original object. This may be in an arena, and + // therefore have the arena's lifetime. + // Requires: current_size_ > 0 + Element* UnsafeArenaReleaseLast(); + + // Extract elements with indices in the range "[start .. start+num-1]". + // The caller assumes ownership of the extracted elements and is responsible + // for deleting them when they are no longer needed. + // If "elements" is non-nullptr, then pointers to the extracted elements + // are stored in "elements[0 .. num-1]" for the convenience of the caller. + // If "elements" is nullptr, then the caller must use some other mechanism + // to perform any further operations (like deletion) on these elements. + // Caution: implementation also moves elements with indices [start+num ..]. + // Calling this routine inside a loop can cause quadratic behavior. + // + // Memory copying behavior is identical to ReleaseLast(), described above: if + // this RepeatedPtrField is on an arena, an object copy is performed for each + // returned element, so that all returned element pointers are to + // heap-allocated copies. If this copy is not desired, the user should call + // UnsafeArenaExtractSubrange(). + void ExtractSubrange(int start, int num, Element** elements); + + // Identical to ExtractSubrange() described above, except that no object + // copies are ever performed. Instead, the raw object pointers are returned. + // Thus, if on an arena, the returned objects must not be freed, because they + // will not be heap-allocated objects. + void UnsafeArenaExtractSubrange(int start, int num, Element** elements); + + // When elements are removed by calls to RemoveLast() or Clear(), they + // are not actually freed. Instead, they are cleared and kept so that + // they can be reused later. This can save lots of CPU time when + // repeatedly reusing a protocol message for similar purposes. + // + // Hardcore programs may choose to manipulate these cleared objects + // to better optimize memory management using the following routines. + + // Get the number of cleared objects that are currently being kept + // around for reuse. + int ClearedCount() const; +#ifndef PROTOBUF_FUTURE_BREAKING_CHANGES + // Add an element to the pool of cleared objects, passing ownership to + // the RepeatedPtrField. The element must be cleared prior to calling + // this method. + // + // This method cannot be called when the repeated field is on an arena or when + // |value| is; both cases will trigger a GOOGLE_DCHECK-failure. + void AddCleared(Element* value); + // Remove a single element from the cleared pool and return it, passing + // ownership to the caller. The element is guaranteed to be cleared. + // Requires: ClearedCount() > 0 + // + // + // This method cannot be called when the repeated field is on an arena; doing + // so will trigger a GOOGLE_DCHECK-failure. + PROTOBUF_NODISCARD Element* ReleaseCleared(); +#endif // !PROTOBUF_FUTURE_BREAKING_CHANGES + + // Removes the element referenced by position. + // + // Returns an iterator to the element immediately following the removed + // element. + // + // Invalidates all iterators at or after the removed element, including end(). + iterator erase(const_iterator position); + + // Removes the elements in the range [first, last). + // + // Returns an iterator to the element immediately following the removed range. + // + // Invalidates all iterators at or after the removed range, including end(). + iterator erase(const_iterator first, const_iterator last); + + // Gets the arena on which this RepeatedPtrField stores its elements. + inline Arena* GetArena() const; + + // For internal use only. + // + // This is public due to it being called by generated code. + void InternalSwap(RepeatedPtrField* other) { + internal::RepeatedPtrFieldBase::InternalSwap(other); + } + + private: + // Note: RepeatedPtrField SHOULD NOT be subclassed by users. + class TypeHandler; + + // Implementations for ExtractSubrange(). The copying behavior must be + // included only if the type supports the necessary operations (e.g., + // 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, + std::true_type); + void ExtractSubrangeInternal(int start, int num, Element** elements, + std::false_type); + + friend class Arena; + + template + friend struct WeakRepeatedPtrField; + + typedef void InternalArenaConstructable_; + +}; + +// implementation ==================================================== + +namespace internal { + +constexpr RepeatedPtrFieldBase::RepeatedPtrFieldBase() + : arena_(nullptr), current_size_(0), total_size_(0), rep_(nullptr) {} + +inline RepeatedPtrFieldBase::RepeatedPtrFieldBase(Arena* arena) + : arena_(arena), current_size_(0), total_size_(0), rep_(nullptr) {} + +template +void RepeatedPtrFieldBase::Destroy() { + if (rep_ != nullptr && arena_ == nullptr) { + int n = rep_->allocated_size; + void* const* elements = rep_->elements; + for (int i = 0; i < n; i++) { + TypeHandler::Delete(cast(elements[i]), nullptr); + } +#if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation) + const size_t size = total_size_ * sizeof(elements[0]) + kRepHeaderSize; + ::operator delete(static_cast(rep_), size); +#else + ::operator delete(static_cast(rep_)); +#endif + } + rep_ = nullptr; +} + +template +inline void RepeatedPtrFieldBase::Swap(RepeatedPtrFieldBase* other) { +#ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetArena() != nullptr && GetArena() == other->GetArena()) { +#else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetArena() == other->GetArena()) { +#endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + SwapFallback(other); + } +} + +template +void RepeatedPtrFieldBase::SwapFallback(RepeatedPtrFieldBase* other) { +#ifdef PROTOBUF_FORCE_COPY_IN_SWAP + GOOGLE_DCHECK(GetArena() == nullptr || other->GetArena() != GetArena()); +#else // PROTOBUF_FORCE_COPY_IN_SWAP + GOOGLE_DCHECK(other->GetArena() != GetArena()); +#endif // !PROTOBUF_FORCE_COPY_IN_SWAP + + // Copy semantics in this case. We try to improve efficiency by placing the + // temporary on |other|'s arena so that messages are copied twice rather than + // three times. + RepeatedPtrFieldBase temp(other->GetArena()); + temp.MergeFrom(*this); + this->Clear(); + this->MergeFrom(*other); + other->InternalSwap(&temp); + temp.Destroy(); // Frees rep_ if `other` had no arena. +} + +inline bool RepeatedPtrFieldBase::empty() const { return current_size_ == 0; } + +inline int RepeatedPtrFieldBase::size() const { return current_size_; } + +template +inline const typename TypeHandler::Type& RepeatedPtrFieldBase::Get( + int index) const { + GOOGLE_DCHECK_GE(index, 0); + GOOGLE_DCHECK_LT(index, current_size_); + return *cast(rep_->elements[index]); +} + +template +inline const typename TypeHandler::Type& RepeatedPtrFieldBase::at( + int index) const { + GOOGLE_CHECK_GE(index, 0); + GOOGLE_CHECK_LT(index, current_size_); + return *cast(rep_->elements[index]); +} + +template +inline typename TypeHandler::Type& RepeatedPtrFieldBase::at(int index) { + GOOGLE_CHECK_GE(index, 0); + GOOGLE_CHECK_LT(index, current_size_); + return *cast(rep_->elements[index]); +} + +template +inline typename TypeHandler::Type* RepeatedPtrFieldBase::Mutable(int index) { + GOOGLE_DCHECK_GE(index, 0); + GOOGLE_DCHECK_LT(index, current_size_); + return cast(rep_->elements[index]); +} + +template +inline void RepeatedPtrFieldBase::Delete(int index) { + GOOGLE_DCHECK_GE(index, 0); + GOOGLE_DCHECK_LT(index, current_size_); + TypeHandler::Delete(cast(rep_->elements[index]), arena_); +} + +template +inline typename TypeHandler::Type* RepeatedPtrFieldBase::Add( + typename TypeHandler::Type* prototype) { + if (rep_ != nullptr && current_size_ < rep_->allocated_size) { + return cast(rep_->elements[current_size_++]); + } + typename TypeHandler::Type* result = + TypeHandler::NewFromPrototype(prototype, arena_); + return reinterpret_cast( + AddOutOfLineHelper(result)); +} + +template ::type*> +inline void RepeatedPtrFieldBase::Add(typename TypeHandler::Type&& value) { + if (rep_ != nullptr && current_size_ < rep_->allocated_size) { + *cast(rep_->elements[current_size_++]) = std::move(value); + return; + } + if (!rep_ || rep_->allocated_size == total_size_) { + Reserve(total_size_ + 1); + } + ++rep_->allocated_size; + typename TypeHandler::Type* result = + TypeHandler::New(arena_, std::move(value)); + rep_->elements[current_size_++] = result; +} + +template +inline void RepeatedPtrFieldBase::RemoveLast() { + GOOGLE_DCHECK_GT(current_size_, 0); + TypeHandler::Clear(cast(rep_->elements[--current_size_])); +} + +template +void RepeatedPtrFieldBase::Clear() { + const int n = current_size_; + GOOGLE_DCHECK_GE(n, 0); + if (n > 0) { + void* const* elements = rep_->elements; + int i = 0; + do { + TypeHandler::Clear(cast(elements[i++])); + } while (i < n); + current_size_ = 0; + } +} + +// To avoid unnecessary code duplication and reduce binary size, we use a +// layered approach to implementing MergeFrom(). The toplevel method is +// templated, so we get a small thunk per concrete message type in the binary. +// This calls a shared implementation with most of the logic, passing a function +// pointer to another type-specific piece of code that calls the object-allocate +// and merge handlers. +template +inline void RepeatedPtrFieldBase::MergeFrom(const RepeatedPtrFieldBase& other) { + GOOGLE_DCHECK_NE(&other, this); + if (other.current_size_ == 0) return; + MergeFromInternal(other, + &RepeatedPtrFieldBase::MergeFromInnerLoop); +} + +inline void RepeatedPtrFieldBase::MergeFromInternal( + const RepeatedPtrFieldBase& other, + void (RepeatedPtrFieldBase::*inner_loop)(void**, void**, int, int)) { + // Note: wrapper has already guaranteed that other.rep_ != nullptr here. + int other_size = other.current_size_; + void** other_elements = other.rep_->elements; + void** new_elements = InternalExtend(other_size); + int allocated_elems = rep_->allocated_size - current_size_; + (this->*inner_loop)(new_elements, other_elements, other_size, + allocated_elems); + current_size_ += other_size; + if (rep_->allocated_size < current_size_) { + rep_->allocated_size = current_size_; + } +} + +// Merges other_elems to our_elems. +template +void RepeatedPtrFieldBase::MergeFromInnerLoop(void** our_elems, + void** other_elems, int length, + int already_allocated) { + if (already_allocated < length) { + Arena* arena = GetArena(); + typename TypeHandler::Type* elem_prototype = + reinterpret_cast(other_elems[0]); + for (int i = already_allocated; i < length; i++) { + // Allocate a new empty element that we'll merge into below + typename TypeHandler::Type* new_elem = + TypeHandler::NewFromPrototype(elem_prototype, arena); + our_elems[i] = new_elem; + } + } + // Main loop that does the actual merging + for (int i = 0; i < length; i++) { + // Already allocated: use existing element. + typename TypeHandler::Type* other_elem = + reinterpret_cast(other_elems[i]); + typename TypeHandler::Type* new_elem = + reinterpret_cast(our_elems[i]); + TypeHandler::Merge(*other_elem, new_elem); + } +} + +template +inline void RepeatedPtrFieldBase::CopyFrom(const RepeatedPtrFieldBase& other) { + if (&other == this) return; + RepeatedPtrFieldBase::Clear(); + RepeatedPtrFieldBase::MergeFrom(other); +} + +inline int RepeatedPtrFieldBase::Capacity() const { return total_size_; } + +inline void* const* RepeatedPtrFieldBase::raw_data() const { + return rep_ ? rep_->elements : nullptr; +} + +inline void** RepeatedPtrFieldBase::raw_mutable_data() const { + return rep_ ? const_cast(rep_->elements) : nullptr; +} + +template +inline typename TypeHandler::Type** RepeatedPtrFieldBase::mutable_data() { + // TODO(kenton): Breaks C++ aliasing rules. We should probably remove this + // method entirely. + return reinterpret_cast(raw_mutable_data()); +} + +template +inline const typename TypeHandler::Type* const* RepeatedPtrFieldBase::data() + const { + // TODO(kenton): Breaks C++ aliasing rules. We should probably remove this + // method entirely. + return reinterpret_cast(raw_data()); +} + +inline void RepeatedPtrFieldBase::SwapElements(int index1, int index2) { + using std::swap; // enable ADL with fallback + swap(rep_->elements[index1], rep_->elements[index2]); +} + +template +inline size_t RepeatedPtrFieldBase::SpaceUsedExcludingSelfLong() const { + size_t allocated_bytes = static_cast(total_size_) * sizeof(void*); + if (rep_ != nullptr) { + for (int i = 0; i < rep_->allocated_size; ++i) { + allocated_bytes += + TypeHandler::SpaceUsedLong(*cast(rep_->elements[i])); + } + allocated_bytes += kRepHeaderSize; + } + return allocated_bytes; +} + +template +inline typename TypeHandler::Type* RepeatedPtrFieldBase::AddFromCleared() { + if (rep_ != nullptr && current_size_ < rep_->allocated_size) { + return cast(rep_->elements[current_size_++]); + } else { + return nullptr; + } +} + +// AddAllocated version that implements arena-safe copying behavior. +template +void RepeatedPtrFieldBase::AddAllocatedInternal( + typename TypeHandler::Type* value, std::true_type) { + Arena* element_arena = + reinterpret_cast(TypeHandler::GetOwningArena(value)); + Arena* arena = GetArena(); + if (arena == element_arena && 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 + // one slot that is not allocated). + void** elems = rep_->elements; + if (current_size_ < rep_->allocated_size) { + // Make space at [current] by moving first allocated element to end of + // allocated list. + elems[rep_->allocated_size] = elems[current_size_]; + } + elems[current_size_] = value; + current_size_ = current_size_ + 1; + rep_->allocated_size = rep_->allocated_size + 1; + } else { + AddAllocatedSlowWithCopy(value, element_arena, arena); + } +} + +// Slowpath handles all cases, copying if necessary. +template +void RepeatedPtrFieldBase::AddAllocatedSlowWithCopy( + // Pass value_arena and my_arena to avoid duplicate virtual call (value) or + // load (mine). + typename TypeHandler::Type* value, Arena* value_arena, Arena* my_arena) { + // Ensure that either the value is in the same arena, or if not, we do the + // appropriate thing: Own() it (if it's on heap and we're in an arena) or copy + // it to our arena/heap (otherwise). + if (my_arena != nullptr && value_arena == nullptr) { + my_arena->Own(value); + } else if (my_arena != value_arena) { + typename TypeHandler::Type* new_value = + TypeHandler::NewFromPrototype(value, my_arena); + TypeHandler::Merge(*value, new_value); + TypeHandler::Delete(value, value_arena); + value = new_value; + } + + UnsafeArenaAddAllocated(value); +} + +// AddAllocated version that does not implement arena-safe copying behavior. +template +void RepeatedPtrFieldBase::AddAllocatedInternal( + typename TypeHandler::Type* value, 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 + // one slot that is not allocated). + void** elems = rep_->elements; + if (current_size_ < rep_->allocated_size) { + // Make space at [current] by moving first allocated element to end of + // allocated list. + elems[rep_->allocated_size] = elems[current_size_]; + } + elems[current_size_] = value; + current_size_ = current_size_ + 1; + ++rep_->allocated_size; + } else { + UnsafeArenaAddAllocated(value); + } +} + +template +void RepeatedPtrFieldBase::UnsafeArenaAddAllocated( + typename TypeHandler::Type* value) { + // Make room for the new pointer. + if (!rep_ || current_size_ == total_size_) { + // The array is completely full with no cleared objects, so grow it. + Reserve(total_size_ + 1); + ++rep_->allocated_size; + } else if (rep_->allocated_size == total_size_) { + // There is no more space in the pointer array because it contains some + // cleared objects awaiting reuse. We don't want to grow the array in this + // case because otherwise a loop calling AddAllocated() followed by Clear() + // would leak memory. + TypeHandler::Delete(cast(rep_->elements[current_size_]), + arena_); + } else if (current_size_ < rep_->allocated_size) { + // We have some cleared objects. We don't care about their order, so we + // can just move the first one to the end to make space. + rep_->elements[rep_->allocated_size] = rep_->elements[current_size_]; + ++rep_->allocated_size; + } else { + // There are no cleared objects. + ++rep_->allocated_size; + } + + rep_->elements[current_size_++] = value; +} + +// ReleaseLast() for types that implement merge/copy behavior. +template +inline typename TypeHandler::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. + Arena* arena = GetArena(); + + typename TypeHandler::Type* new_result; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + new_result = copy(result); + if (arena == nullptr) delete result; +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + new_result = (arena == nullptr) ? result : copy(result); +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return new_result; +} + +// ReleaseLast() for types that *do not* implement merge/copy behavior -- this +// is the same as UnsafeArenaReleaseLast(). Note that we GOOGLE_DCHECK-fail if we're on +// an arena, since the user really should implement the copy operation in this +// case. +template +inline typename TypeHandler::Type* RepeatedPtrFieldBase::ReleaseLastInternal( + std::false_type) { + GOOGLE_DCHECK(GetArena() == nullptr) + << "ReleaseLast() called on a RepeatedPtrField that is on an arena, " + << "with a type that does not implement MergeFrom. This is unsafe; " + << "please implement MergeFrom for your type."; + return UnsafeArenaReleaseLast(); +} + +template +inline typename TypeHandler::Type* +RepeatedPtrFieldBase::UnsafeArenaReleaseLast() { + GOOGLE_DCHECK_GT(current_size_, 0); + typename TypeHandler::Type* result = + cast(rep_->elements[--current_size_]); + --rep_->allocated_size; + if (current_size_ < rep_->allocated_size) { + // There are cleared elements on the end; replace the removed element + // with the last allocated element. + rep_->elements[current_size_] = rep_->elements[rep_->allocated_size]; + } + return result; +} + +inline int RepeatedPtrFieldBase::ClearedCount() const { + return rep_ ? (rep_->allocated_size - current_size_) : 0; +} + +template +inline void RepeatedPtrFieldBase::AddCleared( + typename TypeHandler::Type* value) { + GOOGLE_DCHECK(GetArena() == nullptr) + << "AddCleared() can only be used on a RepeatedPtrField not on an arena."; + GOOGLE_DCHECK(TypeHandler::GetOwningArena(value) == nullptr) + << "AddCleared() can only accept values not on an arena."; + if (!rep_ || rep_->allocated_size == total_size_) { + Reserve(total_size_ + 1); + } + rep_->elements[rep_->allocated_size++] = value; +} + +template +inline typename TypeHandler::Type* RepeatedPtrFieldBase::ReleaseCleared() { + GOOGLE_DCHECK(GetArena() == nullptr) + << "ReleaseCleared() can only be used on a RepeatedPtrField not on " + << "an arena."; + GOOGLE_DCHECK(GetArena() == nullptr); + GOOGLE_DCHECK(rep_ != nullptr); + GOOGLE_DCHECK_GT(rep_->allocated_size, current_size_); + return cast(rep_->elements[--rep_->allocated_size]); +} + +} // namespace internal + +// ------------------------------------------------------------------- + +template +class RepeatedPtrField::TypeHandler + : public internal::GenericTypeHandler {}; + +template <> +class RepeatedPtrField::TypeHandler + : public internal::StringTypeHandler {}; + +template +constexpr RepeatedPtrField::RepeatedPtrField() + : RepeatedPtrFieldBase() {} + +template +inline RepeatedPtrField::RepeatedPtrField(Arena* arena) + : RepeatedPtrFieldBase(arena) {} + +template +inline RepeatedPtrField::RepeatedPtrField( + const RepeatedPtrField& other) + : RepeatedPtrFieldBase() { + MergeFrom(other); +} + +template +template +inline RepeatedPtrField::RepeatedPtrField(Iter begin, Iter end) { + Add(begin, end); +} + +template +RepeatedPtrField::~RepeatedPtrField() { +#ifdef __cpp_if_constexpr + if constexpr (std::is_base_of::value) { +#else + if (std::is_base_of::value) { +#endif + if (NeedsDestroy()) DestroyProtos(); + } else { + Destroy(); + } +} + +template +inline RepeatedPtrField& RepeatedPtrField::operator=( + const RepeatedPtrField& other) { + if (this != &other) CopyFrom(other); + return *this; +} + +template +inline RepeatedPtrField::RepeatedPtrField( + RepeatedPtrField&& other) noexcept + : RepeatedPtrField() { +#ifdef PROTOBUF_FORCE_COPY_IN_MOVE + CopyFrom(other); +#else // PROTOBUF_FORCE_COPY_IN_MOVE + // We don't just call Swap(&other) here because it would perform 3 copies if + // other is on an arena. This field can't be on an arena because arena + // construction always uses the Arena* accepting constructor. + if (other.GetArena()) { + CopyFrom(other); + } else { + InternalSwap(&other); + } +#endif // !PROTOBUF_FORCE_COPY_IN_MOVE +} + +template +inline RepeatedPtrField& RepeatedPtrField::operator=( + RepeatedPtrField&& other) noexcept { + // We don't just call Swap(&other) here because it would perform 3 copies if + // the two fields are on different arenas. + if (this != &other) { + if (GetArena() != other.GetArena() +#ifdef PROTOBUF_FORCE_COPY_IN_MOVE + || GetArena() == nullptr +#endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + CopyFrom(other); + } else { + InternalSwap(&other); + } + } + return *this; +} + +template +inline bool RepeatedPtrField::empty() const { + return RepeatedPtrFieldBase::empty(); +} + +template +inline int RepeatedPtrField::size() const { + return RepeatedPtrFieldBase::size(); +} + +template +inline const Element& RepeatedPtrField::Get(int index) const { + return RepeatedPtrFieldBase::Get(index); +} + +template +inline const Element& RepeatedPtrField::at(int index) const { + return RepeatedPtrFieldBase::at(index); +} + +template +inline Element& RepeatedPtrField::at(int index) { + return RepeatedPtrFieldBase::at(index); +} + + +template +inline Element* RepeatedPtrField::Mutable(int index) { + return RepeatedPtrFieldBase::Mutable(index); +} + +template +inline Element* RepeatedPtrField::Add() { + return RepeatedPtrFieldBase::Add(); +} + +template +inline void RepeatedPtrField::Add(Element&& value) { + RepeatedPtrFieldBase::Add(std::move(value)); +} + +template +template +inline void RepeatedPtrField::Add(Iter begin, Iter end) { + if (std::is_base_of< + std::forward_iterator_tag, + typename std::iterator_traits::iterator_category>::value) { + int reserve = std::distance(begin, end); + Reserve(size() + reserve); + } + for (; begin != end; ++begin) { + *Add() = *begin; + } +} + +template +inline void RepeatedPtrField::RemoveLast() { + RepeatedPtrFieldBase::RemoveLast(); +} + +template +inline void RepeatedPtrField::DeleteSubrange(int start, int num) { + GOOGLE_DCHECK_GE(start, 0); + GOOGLE_DCHECK_GE(num, 0); + GOOGLE_DCHECK_LE(start + num, size()); + for (int i = 0; i < num; ++i) { + RepeatedPtrFieldBase::Delete(start + i); + } + UnsafeArenaExtractSubrange(start, num, nullptr); +} + +template +inline void RepeatedPtrField::ExtractSubrange(int start, int num, + Element** elements) { + typename internal::TypeImplementsMergeBehavior< + typename TypeHandler::Type>::type t; + ExtractSubrangeInternal(start, num, elements, t); +} + +// ExtractSubrange() implementation for types that implement merge/copy +// behavior. +template +inline void RepeatedPtrField::ExtractSubrangeInternal( + 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()); + + if (num == 0) return; + + GOOGLE_DCHECK_NE(elements, nullptr) + << "Releasing elements without transferring ownership is an unsafe " + "operation. Use UnsafeArenaExtractSubrange."; + if (elements == nullptr) { + CloseGap(start, num); + return; + } + + Arena* arena = GetArena(); +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + // Always copy. + for (int i = 0; i < num; ++i) { + elements[i] = copy( + RepeatedPtrFieldBase::Mutable(i + start)); + } + if (arena == nullptr) { + for (int i = 0; i < num; ++i) { + delete RepeatedPtrFieldBase::Mutable(i + start); + } + } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + // If we're on an arena, we perform a copy for each element so that the + // returned elements are heap-allocated. Otherwise, just forward it. + if (arena != nullptr) { + for (int i = 0; i < num; ++i) { + elements[i] = copy( + RepeatedPtrFieldBase::Mutable(i + start)); + } + } else { + for (int i = 0; i < num; ++i) { + elements[i] = RepeatedPtrFieldBase::Mutable(i + start); + } + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + CloseGap(start, num); +} + +// ExtractSubrange() implementation for types that do not implement merge/copy +// behavior. +template +inline void RepeatedPtrField::ExtractSubrangeInternal( + 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 + // we are not on an arena. + GOOGLE_DCHECK(GetArena() == nullptr) + << "ExtractSubrange() when arena is non-nullptr is only supported when " + << "the Element type supplies a MergeFrom() operation to make copies."; + UnsafeArenaExtractSubrange(start, num, elements); +} + +template +inline void RepeatedPtrField::UnsafeArenaExtractSubrange( + int start, int num, Element** elements) { + GOOGLE_DCHECK_GE(start, 0); + GOOGLE_DCHECK_GE(num, 0); + GOOGLE_DCHECK_LE(start + num, size()); + + if (num > 0) { + // Save the values of the removed elements if requested. + if (elements != nullptr) { + for (int i = 0; i < num; ++i) { + elements[i] = RepeatedPtrFieldBase::Mutable(i + start); + } + } + CloseGap(start, num); + } +} + +template +inline void RepeatedPtrField::Clear() { + RepeatedPtrFieldBase::Clear(); +} + +template +inline void RepeatedPtrField::MergeFrom( + const RepeatedPtrField& other) { + RepeatedPtrFieldBase::MergeFrom(other); +} + +template +inline void RepeatedPtrField::CopyFrom(const RepeatedPtrField& other) { + RepeatedPtrFieldBase::CopyFrom(other); +} + +template +template +inline void RepeatedPtrField::Assign(Iter begin, Iter end) { + Clear(); + Add(begin, end); +} + +template +inline typename RepeatedPtrField::iterator +RepeatedPtrField::erase(const_iterator position) { + return erase(position, position + 1); +} + +template +inline typename RepeatedPtrField::iterator +RepeatedPtrField::erase(const_iterator first, const_iterator last) { + size_type pos_offset = std::distance(cbegin(), first); + size_type last_offset = std::distance(cbegin(), last); + DeleteSubrange(pos_offset, last_offset - pos_offset); + return begin() + pos_offset; +} + +template +inline Element** RepeatedPtrField::mutable_data() { + return RepeatedPtrFieldBase::mutable_data(); +} + +template +inline const Element* const* RepeatedPtrField::data() const { + return RepeatedPtrFieldBase::data(); +} + +template +inline void RepeatedPtrField::Swap(RepeatedPtrField* other) { + if (this == other) return; + RepeatedPtrFieldBase::Swap(other); +} + +template +inline void RepeatedPtrField::UnsafeArenaSwap( + RepeatedPtrField* other) { + if (this == other) return; + RepeatedPtrFieldBase::InternalSwap(other); +} + +template +inline void RepeatedPtrField::SwapElements(int index1, int index2) { + RepeatedPtrFieldBase::SwapElements(index1, index2); +} + +template +inline Arena* RepeatedPtrField::GetArena() const { + return RepeatedPtrFieldBase::GetArena(); +} + +template +inline size_t RepeatedPtrField::SpaceUsedExcludingSelfLong() const { + return RepeatedPtrFieldBase::SpaceUsedExcludingSelfLong(); +} + +template +inline void RepeatedPtrField::AddAllocated(Element* value) { + RepeatedPtrFieldBase::AddAllocated(value); +} + +template +inline void RepeatedPtrField::UnsafeArenaAddAllocated(Element* value) { + RepeatedPtrFieldBase::UnsafeArenaAddAllocated(value); +} + +template +inline Element* RepeatedPtrField::ReleaseLast() { + return RepeatedPtrFieldBase::ReleaseLast(); +} + +template +inline Element* RepeatedPtrField::UnsafeArenaReleaseLast() { + return RepeatedPtrFieldBase::UnsafeArenaReleaseLast(); +} + +template +inline int RepeatedPtrField::ClearedCount() const { + return RepeatedPtrFieldBase::ClearedCount(); +} + +#ifndef PROTOBUF_FUTURE_BREAKING_CHANGES +template +inline void RepeatedPtrField::AddCleared(Element* value) { + return RepeatedPtrFieldBase::AddCleared(value); +} + +template +inline Element* RepeatedPtrField::ReleaseCleared() { + return RepeatedPtrFieldBase::ReleaseCleared(); +} +#endif // !PROTOBUF_FUTURE_BREAKING_CHANGES + +template +inline void RepeatedPtrField::Reserve(int new_size) { + return RepeatedPtrFieldBase::Reserve(new_size); +} + +template +inline int RepeatedPtrField::Capacity() const { + return RepeatedPtrFieldBase::Capacity(); +} + +// ------------------------------------------------------------------- + +namespace internal { + +// STL-like iterator implementation for RepeatedPtrField. You should not +// refer to this class directly; use RepeatedPtrField::iterator instead. +// +// The iterator for RepeatedPtrField, RepeatedPtrIterator, is +// very similar to iterator_ptr in util/gtl/iterator_adaptors.h, +// but adds random-access operators and is modified to wrap a void** base +// iterator (since RepeatedPtrField stores its array as a void* array and +// casting void** to T** would violate C++ aliasing rules). +// +// This code based on net/proto/proto-array-internal.h by Jeffrey Yasskin +// (jyasskin@google.com). +template +class RepeatedPtrIterator { + public: + using iterator = RepeatedPtrIterator; + using iterator_category = std::random_access_iterator_tag; + using value_type = typename std::remove_const::type; + using const_iterator = RepeatedPtrIterator; + using nonconst_iterator = RepeatedPtrIterator; + using difference_type = std::ptrdiff_t; + using pointer = Element*; + using reference = Element&; + + RepeatedPtrIterator() : it_(nullptr) {} + explicit RepeatedPtrIterator(void* const* it) : it_(it) {} + + // Allow "upcasting" from RepeatedPtrIterator to + // RepeatedPtrIterator. + template + RepeatedPtrIterator(const RepeatedPtrIterator& other) + : it_(other.it_) { + // Force a compiler error if the other type is not convertible to ours. + if (false) { + static_cast([](OtherElement* from) -> Element* { return from; }); + } + } + + // dereferenceable + reference operator*() const { return *reinterpret_cast(*it_); } + pointer operator->() const { return &(operator*()); } + + // {inc,dec}rementable + iterator& operator++() { + ++it_; + return *this; + } + iterator operator++(int) { return iterator(it_++); } + iterator& operator--() { + --it_; + return *this; + } + iterator operator--(int) { return iterator(it_--); } + + // equality_comparable + bool operator==(const nonconst_iterator& x) const { return it_ == x.it_; } + bool operator==(const const_iterator& x) const { return it_ == x.it_; } + bool operator!=(const nonconst_iterator& x) const { return it_ != x.it_; } + bool operator!=(const const_iterator& x) const { return it_ != x.it_; } + + // less_than_comparable + bool operator<(const nonconst_iterator& x) const { return it_ < x.it_; } + bool operator<(const const_iterator& x) const { return it_ < x.it_; } + bool operator<=(const nonconst_iterator& x) const { return it_ <= x.it_; } + bool operator<=(const const_iterator& x) const { return it_ <= x.it_; } + bool operator>(const nonconst_iterator& x) const { return it_ > x.it_; } + bool operator>(const const_iterator& x) const { return it_ > x.it_; } + bool operator>=(const nonconst_iterator& x) const { return it_ >= x.it_; } + bool operator>=(const const_iterator& x) const { return it_ >= x.it_; } + + // addable, subtractable + iterator& operator+=(difference_type d) { + it_ += d; + return *this; + } + friend iterator operator+(iterator it, const difference_type d) { + it += d; + return it; + } + friend iterator operator+(const difference_type d, iterator it) { + it += d; + return it; + } + iterator& operator-=(difference_type d) { + it_ -= d; + return *this; + } + friend iterator operator-(iterator it, difference_type d) { + it -= d; + return it; + } + + // indexable + reference operator[](difference_type d) const { return *(*this + d); } + + // random access iterator + difference_type operator-(const iterator& x) const { return it_ - x.it_; } + + private: + template + friend class RepeatedPtrIterator; + + // The internal iterator. + void* const* it_; +}; + +// Provide an iterator that operates on pointers to the underlying objects +// rather than the objects themselves as RepeatedPtrIterator does. +// Consider using this when working with stl algorithms that change +// the array. +// The VoidPtr template parameter holds the type-agnostic pointer value +// referenced by the iterator. It should either be "void *" for a mutable +// iterator, or "const void* const" for a constant iterator. +template +class RepeatedPtrOverPtrsIterator { + public: + using iterator = RepeatedPtrOverPtrsIterator; + using iterator_category = std::random_access_iterator_tag; + using value_type = typename std::remove_const::type; + using difference_type = std::ptrdiff_t; + using pointer = Element*; + using reference = Element&; + + RepeatedPtrOverPtrsIterator() : it_(nullptr) {} + explicit RepeatedPtrOverPtrsIterator(VoidPtr* it) : it_(it) {} + + // dereferenceable + reference operator*() const { return *reinterpret_cast(it_); } + pointer operator->() const { return &(operator*()); } + + // {inc,dec}rementable + iterator& operator++() { + ++it_; + return *this; + } + iterator operator++(int) { return iterator(it_++); } + iterator& operator--() { + --it_; + return *this; + } + iterator operator--(int) { return iterator(it_--); } + + // equality_comparable + bool operator==(const iterator& x) const { return it_ == x.it_; } + bool operator!=(const iterator& x) const { return it_ != x.it_; } + + // less_than_comparable + bool operator<(const iterator& x) const { return it_ < x.it_; } + bool operator<=(const iterator& x) const { return it_ <= x.it_; } + bool operator>(const iterator& x) const { return it_ > x.it_; } + bool operator>=(const iterator& x) const { return it_ >= x.it_; } + + // addable, subtractable + iterator& operator+=(difference_type d) { + it_ += d; + return *this; + } + friend iterator operator+(iterator it, difference_type d) { + it += d; + return it; + } + friend iterator operator+(difference_type d, iterator it) { + it += d; + return it; + } + iterator& operator-=(difference_type d) { + it_ -= d; + return *this; + } + friend iterator operator-(iterator it, difference_type d) { + it -= d; + return it; + } + + // indexable + reference operator[](difference_type d) const { return *(*this + d); } + + // random access iterator + difference_type operator-(const iterator& x) const { return it_ - x.it_; } + + private: + template + friend class RepeatedPtrIterator; + + // The internal iterator. + VoidPtr* it_; +}; + +void RepeatedPtrFieldBase::InternalSwap(RepeatedPtrFieldBase* rhs) { + GOOGLE_DCHECK(this != rhs); + + // Swap all fields at once. + auto temp = std::make_tuple(rhs->arena_, rhs->current_size_, rhs->total_size_, + rhs->rep_); + std::tie(rhs->arena_, rhs->current_size_, rhs->total_size_, rhs->rep_) = + std::make_tuple(arena_, current_size_, total_size_, rep_); + std::tie(arena_, current_size_, total_size_, rep_) = temp; +} + +} // namespace internal + +template +inline typename RepeatedPtrField::iterator +RepeatedPtrField::begin() { + return iterator(raw_data()); +} +template +inline typename RepeatedPtrField::const_iterator +RepeatedPtrField::begin() const { + return iterator(raw_data()); +} +template +inline typename RepeatedPtrField::const_iterator +RepeatedPtrField::cbegin() const { + return begin(); +} +template +inline typename RepeatedPtrField::iterator +RepeatedPtrField::end() { + return iterator(raw_data() + size()); +} +template +inline typename RepeatedPtrField::const_iterator +RepeatedPtrField::end() const { + return iterator(raw_data() + size()); +} +template +inline typename RepeatedPtrField::const_iterator +RepeatedPtrField::cend() const { + return end(); +} + +template +inline typename RepeatedPtrField::pointer_iterator +RepeatedPtrField::pointer_begin() { + return pointer_iterator(raw_mutable_data()); +} +template +inline typename RepeatedPtrField::const_pointer_iterator +RepeatedPtrField::pointer_begin() const { + return const_pointer_iterator(const_cast(raw_data())); +} +template +inline typename RepeatedPtrField::pointer_iterator +RepeatedPtrField::pointer_end() { + return pointer_iterator(raw_mutable_data() + size()); +} +template +inline typename RepeatedPtrField::const_pointer_iterator +RepeatedPtrField::pointer_end() const { + return const_pointer_iterator( + const_cast(raw_data() + size())); +} + +// Iterators and helper functions that follow the spirit of the STL +// std::back_insert_iterator and std::back_inserter but are tailor-made +// for RepeatedField and RepeatedPtrField. Typical usage would be: +// +// std::copy(some_sequence.begin(), some_sequence.end(), +// RepeatedFieldBackInserter(proto.mutable_sequence())); +// +// Ported by johannes from util/gtl/proto-array-iterators.h + +namespace internal { + +// A back inserter for RepeatedPtrField objects. +template +class RepeatedPtrFieldBackInsertIterator { + public: + using iterator_category = std::output_iterator_tag; + using value_type = T; + using pointer = void; + using reference = void; + using difference_type = std::ptrdiff_t; + + RepeatedPtrFieldBackInsertIterator(RepeatedPtrField* const mutable_field) + : field_(mutable_field) {} + RepeatedPtrFieldBackInsertIterator& operator=(const T& value) { + *field_->Add() = value; + return *this; + } + RepeatedPtrFieldBackInsertIterator& operator=( + const T* const ptr_to_value) { + *field_->Add() = *ptr_to_value; + return *this; + } + RepeatedPtrFieldBackInsertIterator& operator=(T&& value) { + *field_->Add() = std::move(value); + return *this; + } + RepeatedPtrFieldBackInsertIterator& operator*() { return *this; } + RepeatedPtrFieldBackInsertIterator& operator++() { return *this; } + RepeatedPtrFieldBackInsertIterator& operator++(int /* unused */) { + return *this; + } + + private: + RepeatedPtrField* field_; +}; + +// A back inserter for RepeatedPtrFields that inserts by transferring ownership +// of a pointer. +template +class AllocatedRepeatedPtrFieldBackInsertIterator { + public: + using iterator_category = std::output_iterator_tag; + using value_type = T; + using pointer = void; + using reference = void; + using difference_type = std::ptrdiff_t; + + explicit AllocatedRepeatedPtrFieldBackInsertIterator( + RepeatedPtrField* const mutable_field) + : field_(mutable_field) {} + AllocatedRepeatedPtrFieldBackInsertIterator& operator=( + T* const ptr_to_value) { + field_->AddAllocated(ptr_to_value); + return *this; + } + AllocatedRepeatedPtrFieldBackInsertIterator& operator*() { return *this; } + AllocatedRepeatedPtrFieldBackInsertIterator& operator++() { return *this; } + AllocatedRepeatedPtrFieldBackInsertIterator& operator++(int /* unused */) { + return *this; + } + + private: + RepeatedPtrField* field_; +}; + +// Almost identical to AllocatedRepeatedPtrFieldBackInsertIterator. This one +// uses the UnsafeArenaAddAllocated instead. +template +class UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator { + public: + using iterator_category = std::output_iterator_tag; + using value_type = T; + using pointer = void; + using reference = void; + using difference_type = std::ptrdiff_t; + + explicit UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator( + RepeatedPtrField* const mutable_field) + : field_(mutable_field) {} + UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator& operator=( + T const* const ptr_to_value) { + field_->UnsafeArenaAddAllocated(const_cast(ptr_to_value)); + return *this; + } + UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator& operator*() { + return *this; + } + UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator& operator++() { + return *this; + } + UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator& operator++( + int /* unused */) { + return *this; + } + + private: + RepeatedPtrField* field_; +}; + +} // namespace internal + +// Provides a back insert iterator for RepeatedPtrField instances, +// similar to std::back_inserter(). +template +internal::RepeatedPtrFieldBackInsertIterator RepeatedPtrFieldBackInserter( + RepeatedPtrField* const mutable_field) { + return internal::RepeatedPtrFieldBackInsertIterator(mutable_field); +} + +// Special back insert iterator for RepeatedPtrField instances, just in +// case someone wants to write generic template code that can access both +// RepeatedFields and RepeatedPtrFields using a common name. +template +internal::RepeatedPtrFieldBackInsertIterator RepeatedFieldBackInserter( + RepeatedPtrField* const mutable_field) { + return internal::RepeatedPtrFieldBackInsertIterator(mutable_field); +} + +// Provides a back insert iterator for RepeatedPtrField instances +// similar to std::back_inserter() which transfers the ownership while +// copying elements. +template +internal::AllocatedRepeatedPtrFieldBackInsertIterator +AllocatedRepeatedPtrFieldBackInserter( + RepeatedPtrField* const mutable_field) { + return internal::AllocatedRepeatedPtrFieldBackInsertIterator( + mutable_field); +} + +// Similar to AllocatedRepeatedPtrFieldBackInserter, using +// UnsafeArenaAddAllocated instead of AddAllocated. +// This is slightly faster if that matters. It is also useful in legacy code +// that uses temporary ownership to avoid copies. Example: +// RepeatedPtrField temp_field; +// temp_field.UnsafeArenaAddAllocated(new T); +// ... // Do something with temp_field +// temp_field.UnsafeArenaExtractSubrange(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. +template +internal::UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator +UnsafeArenaAllocatedRepeatedPtrFieldBackInserter( + RepeatedPtrField* const mutable_field) { + return internal::UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator( + mutable_field); +} + +extern template class PROTOBUF_EXPORT_TEMPLATE_DECLARE + RepeatedPtrField; + +} // namespace protobuf +} // namespace google + +#include + +#endif // GOOGLE_PROTOBUF_REPEATED_PTR_FIELD_H__ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/source_context.pb.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/source_context.pb.h new file mode 100644 index 0000000..28af27d --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/source_context.pb.h @@ -0,0 +1,290 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/source_context.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fsource_5fcontext_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fsource_5fcontext_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3019000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3019004 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fsource_5fcontext_2eproto PROTOBUF_EXPORT +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fsource_5fcontext_2eproto { + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; + static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; + static const uint32_t offsets[]; +}; +PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto; +PROTOBUF_NAMESPACE_OPEN +class SourceContext; +struct SourceContextDefaultTypeInternal; +PROTOBUF_EXPORT extern SourceContextDefaultTypeInternal _SourceContext_default_instance_; +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::SourceContext* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::SourceContext>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN + +// =================================================================== + +class PROTOBUF_EXPORT SourceContext final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceContext) */ { + public: + inline SourceContext() : SourceContext(nullptr) {} + ~SourceContext() override; + explicit constexpr SourceContext(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + SourceContext(const SourceContext& from); + SourceContext(SourceContext&& from) noexcept + : SourceContext() { + *this = ::std::move(from); + } + + inline SourceContext& operator=(const SourceContext& from) { + CopyFrom(from); + return *this; + } + inline SourceContext& operator=(SourceContext&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const SourceContext& default_instance() { + return *internal_default_instance(); + } + static inline const SourceContext* internal_default_instance() { + return reinterpret_cast( + &_SourceContext_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(SourceContext& a, SourceContext& b) { + a.Swap(&b); + } + inline void Swap(SourceContext* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(SourceContext* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + SourceContext* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const SourceContext& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom(const SourceContext& from); + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + + private: + void SharedCtor(); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(SourceContext* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.SourceContext"; + } + protected: + explicit SourceContext(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kFileNameFieldNumber = 1, + }; + // string file_name = 1; + void clear_file_name(); + const std::string& file_name() const; + template + void set_file_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_file_name(); + PROTOBUF_NODISCARD std::string* release_file_name(); + void set_allocated_file_name(std::string* file_name); + private: + const std::string& _internal_file_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_file_name(const std::string& value); + std::string* _internal_mutable_file_name(); + public: + + // @@protoc_insertion_point(class_scope:google.protobuf.SourceContext) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr file_name_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + friend struct ::TableStruct_google_2fprotobuf_2fsource_5fcontext_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// SourceContext + +// string file_name = 1; +inline void SourceContext::clear_file_name() { + file_name_.ClearToEmpty(); +} +inline const std::string& SourceContext::file_name() const { + // @@protoc_insertion_point(field_get:google.protobuf.SourceContext.file_name) + return _internal_file_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void SourceContext::set_file_name(ArgT0&& arg0, ArgT... args) { + + file_name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:google.protobuf.SourceContext.file_name) +} +inline std::string* SourceContext::mutable_file_name() { + std::string* _s = _internal_mutable_file_name(); + // @@protoc_insertion_point(field_mutable:google.protobuf.SourceContext.file_name) + return _s; +} +inline const std::string& SourceContext::_internal_file_name() const { + return file_name_.Get(); +} +inline void SourceContext::_internal_set_file_name(const std::string& value) { + + file_name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation()); +} +inline std::string* SourceContext::_internal_mutable_file_name() { + + return file_name_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation()); +} +inline std::string* SourceContext::release_file_name() { + // @@protoc_insertion_point(field_release:google.protobuf.SourceContext.file_name) + return file_name_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation()); +} +inline void SourceContext::set_allocated_file_name(std::string* file_name) { + if (file_name != nullptr) { + + } else { + + } + file_name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), file_name, + GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (file_name_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) { + file_name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:google.protobuf.SourceContext.file_name) +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ + +// @@protoc_insertion_point(namespace_scope) + +PROTOBUF_NAMESPACE_CLOSE + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fsource_5fcontext_2eproto diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/struct.pb.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/struct.pb.h new file mode 100644 index 0000000..8ac5cdb --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/struct.pb.h @@ -0,0 +1,1182 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/struct.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fstruct_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fstruct_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3019000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3019004 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include +#include +#include +#include +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fstruct_2eproto PROTOBUF_EXPORT +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fstruct_2eproto { + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[4] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; + static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; + static const uint32_t offsets[]; +}; +PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fstruct_2eproto; +PROTOBUF_NAMESPACE_OPEN +class ListValue; +struct ListValueDefaultTypeInternal; +PROTOBUF_EXPORT extern ListValueDefaultTypeInternal _ListValue_default_instance_; +class Struct; +struct StructDefaultTypeInternal; +PROTOBUF_EXPORT extern StructDefaultTypeInternal _Struct_default_instance_; +class Struct_FieldsEntry_DoNotUse; +struct Struct_FieldsEntry_DoNotUseDefaultTypeInternal; +PROTOBUF_EXPORT extern Struct_FieldsEntry_DoNotUseDefaultTypeInternal _Struct_FieldsEntry_DoNotUse_default_instance_; +class Value; +struct ValueDefaultTypeInternal; +PROTOBUF_EXPORT extern ValueDefaultTypeInternal _Value_default_instance_; +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::ListValue* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::ListValue>(Arena*); +template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Struct* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Struct>(Arena*); +template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse>(Arena*); +template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Value* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Value>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN + +enum NullValue : int { + NULL_VALUE = 0, + NullValue_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits::min(), + NullValue_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits::max() +}; +PROTOBUF_EXPORT bool NullValue_IsValid(int value); +constexpr NullValue NullValue_MIN = NULL_VALUE; +constexpr NullValue NullValue_MAX = NULL_VALUE; +constexpr int NullValue_ARRAYSIZE = NullValue_MAX + 1; + +PROTOBUF_EXPORT const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* NullValue_descriptor(); +template +inline const std::string& NullValue_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function NullValue_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + NullValue_descriptor(), enum_t_value); +} +inline bool NullValue_Parse( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, NullValue* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( + NullValue_descriptor(), name, value); +} +// =================================================================== + +class Struct_FieldsEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry { +public: + typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry SuperType; + Struct_FieldsEntry_DoNotUse(); + explicit constexpr Struct_FieldsEntry_DoNotUse( + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + explicit Struct_FieldsEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::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_); } + static bool ValidateKey(std::string* s) { + return ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(s->data(), static_cast(s->size()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "google.protobuf.Struct.FieldsEntry.key"); + } + static bool ValidateValue(void*) { return true; } + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; +}; + +// ------------------------------------------------------------------- + +class PROTOBUF_EXPORT Struct final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Struct) */ { + public: + inline Struct() : Struct(nullptr) {} + ~Struct() override; + explicit constexpr Struct(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + Struct(const Struct& from); + Struct(Struct&& from) noexcept + : Struct() { + *this = ::std::move(from); + } + + inline Struct& operator=(const Struct& from) { + CopyFrom(from); + return *this; + } + inline Struct& operator=(Struct&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const Struct& default_instance() { + return *internal_default_instance(); + } + static inline const Struct* internal_default_instance() { + return reinterpret_cast( + &_Struct_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(Struct& a, Struct& b) { + a.Swap(&b); + } + inline void Swap(Struct* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(Struct* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + Struct* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const Struct& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom(const Struct& from); + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + + private: + void SharedCtor(); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(Struct* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.Struct"; + } + protected: + explicit Struct(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + + // accessors ------------------------------------------------------- + + enum : int { + kFieldsFieldNumber = 1, + }; + // map fields = 1; + int fields_size() const; + private: + int _internal_fields_size() const; + public: + void clear_fields(); + private: + const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::PROTOBUF_NAMESPACE_ID::Value >& + _internal_fields() const; + ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::PROTOBUF_NAMESPACE_ID::Value >* + _internal_mutable_fields(); + public: + const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::PROTOBUF_NAMESPACE_ID::Value >& + fields() const; + ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::PROTOBUF_NAMESPACE_ID::Value >* + mutable_fields(); + + // @@protoc_insertion_point(class_scope:google.protobuf.Struct) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + ::PROTOBUF_NAMESPACE_ID::internal::MapField< + Struct_FieldsEntry_DoNotUse, + std::string, ::PROTOBUF_NAMESPACE_ID::Value, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> fields_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + friend struct ::TableStruct_google_2fprotobuf_2fstruct_2eproto; +}; +// ------------------------------------------------------------------- + +class PROTOBUF_EXPORT Value final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Value) */ { + public: + inline Value() : Value(nullptr) {} + ~Value() override; + explicit constexpr Value(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + Value(const Value& from); + Value(Value&& from) noexcept + : Value() { + *this = ::std::move(from); + } + + inline Value& operator=(const Value& from) { + CopyFrom(from); + return *this; + } + inline Value& operator=(Value&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const Value& default_instance() { + return *internal_default_instance(); + } + enum KindCase { + kNullValue = 1, + kNumberValue = 2, + kStringValue = 3, + kBoolValue = 4, + kStructValue = 5, + kListValue = 6, + KIND_NOT_SET = 0, + }; + + static inline const Value* internal_default_instance() { + return reinterpret_cast( + &_Value_default_instance_); + } + static constexpr int kIndexInFileMessages = + 2; + + friend void swap(Value& a, Value& b) { + a.Swap(&b); + } + inline void Swap(Value* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(Value* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + Value* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const Value& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom(const Value& from); + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + + private: + void SharedCtor(); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(Value* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.Value"; + } + protected: + explicit Value(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kNullValueFieldNumber = 1, + kNumberValueFieldNumber = 2, + kStringValueFieldNumber = 3, + kBoolValueFieldNumber = 4, + kStructValueFieldNumber = 5, + kListValueFieldNumber = 6, + }; + // .google.protobuf.NullValue null_value = 1; + bool has_null_value() const; + private: + bool _internal_has_null_value() const; + public: + void clear_null_value(); + ::PROTOBUF_NAMESPACE_ID::NullValue null_value() const; + void set_null_value(::PROTOBUF_NAMESPACE_ID::NullValue value); + private: + ::PROTOBUF_NAMESPACE_ID::NullValue _internal_null_value() const; + void _internal_set_null_value(::PROTOBUF_NAMESPACE_ID::NullValue value); + public: + + // double number_value = 2; + bool has_number_value() const; + private: + bool _internal_has_number_value() const; + public: + void clear_number_value(); + double number_value() const; + void set_number_value(double value); + private: + double _internal_number_value() const; + void _internal_set_number_value(double value); + public: + + // string string_value = 3; + bool has_string_value() const; + private: + bool _internal_has_string_value() const; + public: + void clear_string_value(); + const std::string& string_value() const; + template + void set_string_value(ArgT0&& arg0, ArgT... args); + std::string* mutable_string_value(); + PROTOBUF_NODISCARD std::string* release_string_value(); + void set_allocated_string_value(std::string* string_value); + private: + const std::string& _internal_string_value() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_string_value(const std::string& value); + std::string* _internal_mutable_string_value(); + public: + + // bool bool_value = 4; + bool has_bool_value() const; + private: + bool _internal_has_bool_value() const; + public: + void clear_bool_value(); + bool bool_value() const; + void set_bool_value(bool value); + private: + bool _internal_bool_value() const; + void _internal_set_bool_value(bool value); + public: + + // .google.protobuf.Struct struct_value = 5; + bool has_struct_value() const; + private: + bool _internal_has_struct_value() const; + public: + void clear_struct_value(); + const ::PROTOBUF_NAMESPACE_ID::Struct& struct_value() const; + PROTOBUF_NODISCARD ::PROTOBUF_NAMESPACE_ID::Struct* release_struct_value(); + ::PROTOBUF_NAMESPACE_ID::Struct* mutable_struct_value(); + void set_allocated_struct_value(::PROTOBUF_NAMESPACE_ID::Struct* struct_value); + private: + const ::PROTOBUF_NAMESPACE_ID::Struct& _internal_struct_value() const; + ::PROTOBUF_NAMESPACE_ID::Struct* _internal_mutable_struct_value(); + public: + void unsafe_arena_set_allocated_struct_value( + ::PROTOBUF_NAMESPACE_ID::Struct* struct_value); + ::PROTOBUF_NAMESPACE_ID::Struct* unsafe_arena_release_struct_value(); + + // .google.protobuf.ListValue list_value = 6; + bool has_list_value() const; + private: + bool _internal_has_list_value() const; + public: + void clear_list_value(); + const ::PROTOBUF_NAMESPACE_ID::ListValue& list_value() const; + PROTOBUF_NODISCARD ::PROTOBUF_NAMESPACE_ID::ListValue* release_list_value(); + ::PROTOBUF_NAMESPACE_ID::ListValue* mutable_list_value(); + void set_allocated_list_value(::PROTOBUF_NAMESPACE_ID::ListValue* list_value); + private: + const ::PROTOBUF_NAMESPACE_ID::ListValue& _internal_list_value() const; + ::PROTOBUF_NAMESPACE_ID::ListValue* _internal_mutable_list_value(); + public: + void unsafe_arena_set_allocated_list_value( + ::PROTOBUF_NAMESPACE_ID::ListValue* list_value); + ::PROTOBUF_NAMESPACE_ID::ListValue* unsafe_arena_release_list_value(); + + void clear_kind(); + KindCase kind_case() const; + // @@protoc_insertion_point(class_scope:google.protobuf.Value) + private: + class _Internal; + void set_has_null_value(); + void set_has_number_value(); + void set_has_string_value(); + void set_has_bool_value(); + void set_has_struct_value(); + void set_has_list_value(); + + inline bool has_kind() const; + inline void clear_has_kind(); + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + union KindUnion { + constexpr KindUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + int null_value_; + double number_value_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr string_value_; + bool bool_value_; + ::PROTOBUF_NAMESPACE_ID::Struct* struct_value_; + ::PROTOBUF_NAMESPACE_ID::ListValue* list_value_; + } kind_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + uint32_t _oneof_case_[1]; + + friend struct ::TableStruct_google_2fprotobuf_2fstruct_2eproto; +}; +// ------------------------------------------------------------------- + +class PROTOBUF_EXPORT ListValue final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ListValue) */ { + public: + inline ListValue() : ListValue(nullptr) {} + ~ListValue() override; + explicit constexpr ListValue(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + ListValue(const ListValue& from); + ListValue(ListValue&& from) noexcept + : ListValue() { + *this = ::std::move(from); + } + + inline ListValue& operator=(const ListValue& from) { + CopyFrom(from); + return *this; + } + inline ListValue& operator=(ListValue&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const ListValue& default_instance() { + return *internal_default_instance(); + } + static inline const ListValue* internal_default_instance() { + return reinterpret_cast( + &_ListValue_default_instance_); + } + static constexpr int kIndexInFileMessages = + 3; + + friend void swap(ListValue& a, ListValue& b) { + a.Swap(&b); + } + inline void Swap(ListValue* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(ListValue* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + ListValue* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const ListValue& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom(const ListValue& from); + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + + private: + void SharedCtor(); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(ListValue* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.ListValue"; + } + protected: + explicit ListValue(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kValuesFieldNumber = 1, + }; + // repeated .google.protobuf.Value values = 1; + int values_size() const; + private: + int _internal_values_size() const; + public: + void clear_values(); + ::PROTOBUF_NAMESPACE_ID::Value* mutable_values(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Value >* + mutable_values(); + private: + const ::PROTOBUF_NAMESPACE_ID::Value& _internal_values(int index) const; + ::PROTOBUF_NAMESPACE_ID::Value* _internal_add_values(); + public: + const ::PROTOBUF_NAMESPACE_ID::Value& values(int index) const; + ::PROTOBUF_NAMESPACE_ID::Value* add_values(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Value >& + values() const; + + // @@protoc_insertion_point(class_scope:google.protobuf.ListValue) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Value > values_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + friend struct ::TableStruct_google_2fprotobuf_2fstruct_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// ------------------------------------------------------------------- + +// Struct + +// map fields = 1; +inline int Struct::_internal_fields_size() const { + return fields_.size(); +} +inline int Struct::fields_size() const { + return _internal_fields_size(); +} +inline void Struct::clear_fields() { + fields_.Clear(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::PROTOBUF_NAMESPACE_ID::Value >& +Struct::_internal_fields() const { + return fields_.GetMap(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::PROTOBUF_NAMESPACE_ID::Value >& +Struct::fields() const { + // @@protoc_insertion_point(field_map:google.protobuf.Struct.fields) + return _internal_fields(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::PROTOBUF_NAMESPACE_ID::Value >* +Struct::_internal_mutable_fields() { + return fields_.MutableMap(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::PROTOBUF_NAMESPACE_ID::Value >* +Struct::mutable_fields() { + // @@protoc_insertion_point(field_mutable_map:google.protobuf.Struct.fields) + return _internal_mutable_fields(); +} + +// ------------------------------------------------------------------- + +// Value + +// .google.protobuf.NullValue null_value = 1; +inline bool Value::_internal_has_null_value() const { + return kind_case() == kNullValue; +} +inline bool Value::has_null_value() const { + return _internal_has_null_value(); +} +inline void Value::set_has_null_value() { + _oneof_case_[0] = kNullValue; +} +inline void Value::clear_null_value() { + if (_internal_has_null_value()) { + kind_.null_value_ = 0; + clear_has_kind(); + } +} +inline ::PROTOBUF_NAMESPACE_ID::NullValue Value::_internal_null_value() const { + if (_internal_has_null_value()) { + return static_cast< ::PROTOBUF_NAMESPACE_ID::NullValue >(kind_.null_value_); + } + return static_cast< ::PROTOBUF_NAMESPACE_ID::NullValue >(0); +} +inline ::PROTOBUF_NAMESPACE_ID::NullValue Value::null_value() const { + // @@protoc_insertion_point(field_get:google.protobuf.Value.null_value) + return _internal_null_value(); +} +inline void Value::_internal_set_null_value(::PROTOBUF_NAMESPACE_ID::NullValue value) { + if (!_internal_has_null_value()) { + clear_kind(); + set_has_null_value(); + } + kind_.null_value_ = value; +} +inline void Value::set_null_value(::PROTOBUF_NAMESPACE_ID::NullValue value) { + _internal_set_null_value(value); + // @@protoc_insertion_point(field_set:google.protobuf.Value.null_value) +} + +// double number_value = 2; +inline bool Value::_internal_has_number_value() const { + return kind_case() == kNumberValue; +} +inline bool Value::has_number_value() const { + return _internal_has_number_value(); +} +inline void Value::set_has_number_value() { + _oneof_case_[0] = kNumberValue; +} +inline void Value::clear_number_value() { + if (_internal_has_number_value()) { + kind_.number_value_ = 0; + clear_has_kind(); + } +} +inline double Value::_internal_number_value() const { + if (_internal_has_number_value()) { + return kind_.number_value_; + } + return 0; +} +inline void Value::_internal_set_number_value(double value) { + if (!_internal_has_number_value()) { + clear_kind(); + set_has_number_value(); + } + kind_.number_value_ = value; +} +inline double Value::number_value() const { + // @@protoc_insertion_point(field_get:google.protobuf.Value.number_value) + return _internal_number_value(); +} +inline void Value::set_number_value(double value) { + _internal_set_number_value(value); + // @@protoc_insertion_point(field_set:google.protobuf.Value.number_value) +} + +// string string_value = 3; +inline bool Value::_internal_has_string_value() const { + return kind_case() == kStringValue; +} +inline bool Value::has_string_value() const { + return _internal_has_string_value(); +} +inline void Value::set_has_string_value() { + _oneof_case_[0] = kStringValue; +} +inline void Value::clear_string_value() { + if (_internal_has_string_value()) { + kind_.string_value_.Destroy(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation()); + clear_has_kind(); + } +} +inline const std::string& Value::string_value() const { + // @@protoc_insertion_point(field_get:google.protobuf.Value.string_value) + return _internal_string_value(); +} +template +inline void Value::set_string_value(ArgT0&& arg0, ArgT... args) { + if (!_internal_has_string_value()) { + clear_kind(); + set_has_string_value(); + kind_.string_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + } + kind_.string_value_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:google.protobuf.Value.string_value) +} +inline std::string* Value::mutable_string_value() { + std::string* _s = _internal_mutable_string_value(); + // @@protoc_insertion_point(field_mutable:google.protobuf.Value.string_value) + return _s; +} +inline const std::string& Value::_internal_string_value() const { + if (_internal_has_string_value()) { + return kind_.string_value_.Get(); + } + return ::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(); +} +inline void Value::_internal_set_string_value(const std::string& value) { + if (!_internal_has_string_value()) { + clear_kind(); + set_has_string_value(); + kind_.string_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + } + kind_.string_value_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation()); +} +inline std::string* Value::_internal_mutable_string_value() { + if (!_internal_has_string_value()) { + clear_kind(); + set_has_string_value(); + kind_.string_value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); + } + return kind_.string_value_.Mutable( + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation()); +} +inline std::string* Value::release_string_value() { + // @@protoc_insertion_point(field_release:google.protobuf.Value.string_value) + if (_internal_has_string_value()) { + clear_has_kind(); + return kind_.string_value_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation()); + } else { + return nullptr; + } +} +inline void Value::set_allocated_string_value(std::string* string_value) { + if (has_kind()) { + clear_kind(); + } + if (string_value != nullptr) { + set_has_string_value(); + kind_.string_value_.UnsafeSetDefault(string_value); + ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaForAllocation(); + if (arena != nullptr) { + arena->Own(string_value); + } + } + // @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.string_value) +} + +// bool bool_value = 4; +inline bool Value::_internal_has_bool_value() const { + return kind_case() == kBoolValue; +} +inline bool Value::has_bool_value() const { + return _internal_has_bool_value(); +} +inline void Value::set_has_bool_value() { + _oneof_case_[0] = kBoolValue; +} +inline void Value::clear_bool_value() { + if (_internal_has_bool_value()) { + kind_.bool_value_ = false; + clear_has_kind(); + } +} +inline bool Value::_internal_bool_value() const { + if (_internal_has_bool_value()) { + return kind_.bool_value_; + } + return false; +} +inline void Value::_internal_set_bool_value(bool value) { + if (!_internal_has_bool_value()) { + clear_kind(); + set_has_bool_value(); + } + kind_.bool_value_ = value; +} +inline bool Value::bool_value() const { + // @@protoc_insertion_point(field_get:google.protobuf.Value.bool_value) + return _internal_bool_value(); +} +inline void Value::set_bool_value(bool value) { + _internal_set_bool_value(value); + // @@protoc_insertion_point(field_set:google.protobuf.Value.bool_value) +} + +// .google.protobuf.Struct struct_value = 5; +inline bool Value::_internal_has_struct_value() const { + return kind_case() == kStructValue; +} +inline bool Value::has_struct_value() const { + return _internal_has_struct_value(); +} +inline void Value::set_has_struct_value() { + _oneof_case_[0] = kStructValue; +} +inline void Value::clear_struct_value() { + if (_internal_has_struct_value()) { + if (GetArenaForAllocation() == nullptr) { + delete kind_.struct_value_; + } + clear_has_kind(); + } +} +inline ::PROTOBUF_NAMESPACE_ID::Struct* Value::release_struct_value() { + // @@protoc_insertion_point(field_release:google.protobuf.Value.struct_value) + if (_internal_has_struct_value()) { + clear_has_kind(); + ::PROTOBUF_NAMESPACE_ID::Struct* temp = kind_.struct_value_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + kind_.struct_value_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::PROTOBUF_NAMESPACE_ID::Struct& Value::_internal_struct_value() const { + return _internal_has_struct_value() + ? *kind_.struct_value_ + : reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::Struct&>(::PROTOBUF_NAMESPACE_ID::_Struct_default_instance_); +} +inline const ::PROTOBUF_NAMESPACE_ID::Struct& Value::struct_value() const { + // @@protoc_insertion_point(field_get:google.protobuf.Value.struct_value) + return _internal_struct_value(); +} +inline ::PROTOBUF_NAMESPACE_ID::Struct* Value::unsafe_arena_release_struct_value() { + // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Value.struct_value) + if (_internal_has_struct_value()) { + clear_has_kind(); + ::PROTOBUF_NAMESPACE_ID::Struct* temp = kind_.struct_value_; + kind_.struct_value_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void Value::unsafe_arena_set_allocated_struct_value(::PROTOBUF_NAMESPACE_ID::Struct* struct_value) { + clear_kind(); + if (struct_value) { + set_has_struct_value(); + kind_.struct_value_ = struct_value; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Value.struct_value) +} +inline ::PROTOBUF_NAMESPACE_ID::Struct* Value::_internal_mutable_struct_value() { + if (!_internal_has_struct_value()) { + clear_kind(); + set_has_struct_value(); + kind_.struct_value_ = CreateMaybeMessage< ::PROTOBUF_NAMESPACE_ID::Struct >(GetArenaForAllocation()); + } + return kind_.struct_value_; +} +inline ::PROTOBUF_NAMESPACE_ID::Struct* Value::mutable_struct_value() { + ::PROTOBUF_NAMESPACE_ID::Struct* _msg = _internal_mutable_struct_value(); + // @@protoc_insertion_point(field_mutable:google.protobuf.Value.struct_value) + return _msg; +} + +// .google.protobuf.ListValue list_value = 6; +inline bool Value::_internal_has_list_value() const { + return kind_case() == kListValue; +} +inline bool Value::has_list_value() const { + return _internal_has_list_value(); +} +inline void Value::set_has_list_value() { + _oneof_case_[0] = kListValue; +} +inline void Value::clear_list_value() { + if (_internal_has_list_value()) { + if (GetArenaForAllocation() == nullptr) { + delete kind_.list_value_; + } + clear_has_kind(); + } +} +inline ::PROTOBUF_NAMESPACE_ID::ListValue* Value::release_list_value() { + // @@protoc_insertion_point(field_release:google.protobuf.Value.list_value) + if (_internal_has_list_value()) { + clear_has_kind(); + ::PROTOBUF_NAMESPACE_ID::ListValue* temp = kind_.list_value_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + kind_.list_value_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::PROTOBUF_NAMESPACE_ID::ListValue& Value::_internal_list_value() const { + return _internal_has_list_value() + ? *kind_.list_value_ + : reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::ListValue&>(::PROTOBUF_NAMESPACE_ID::_ListValue_default_instance_); +} +inline const ::PROTOBUF_NAMESPACE_ID::ListValue& Value::list_value() const { + // @@protoc_insertion_point(field_get:google.protobuf.Value.list_value) + return _internal_list_value(); +} +inline ::PROTOBUF_NAMESPACE_ID::ListValue* Value::unsafe_arena_release_list_value() { + // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Value.list_value) + if (_internal_has_list_value()) { + clear_has_kind(); + ::PROTOBUF_NAMESPACE_ID::ListValue* temp = kind_.list_value_; + kind_.list_value_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void Value::unsafe_arena_set_allocated_list_value(::PROTOBUF_NAMESPACE_ID::ListValue* list_value) { + clear_kind(); + if (list_value) { + set_has_list_value(); + kind_.list_value_ = list_value; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Value.list_value) +} +inline ::PROTOBUF_NAMESPACE_ID::ListValue* Value::_internal_mutable_list_value() { + if (!_internal_has_list_value()) { + clear_kind(); + set_has_list_value(); + kind_.list_value_ = CreateMaybeMessage< ::PROTOBUF_NAMESPACE_ID::ListValue >(GetArenaForAllocation()); + } + return kind_.list_value_; +} +inline ::PROTOBUF_NAMESPACE_ID::ListValue* Value::mutable_list_value() { + ::PROTOBUF_NAMESPACE_ID::ListValue* _msg = _internal_mutable_list_value(); + // @@protoc_insertion_point(field_mutable:google.protobuf.Value.list_value) + return _msg; +} + +inline bool Value::has_kind() const { + return kind_case() != KIND_NOT_SET; +} +inline void Value::clear_has_kind() { + _oneof_case_[0] = KIND_NOT_SET; +} +inline Value::KindCase Value::kind_case() const { + return Value::KindCase(_oneof_case_[0]); +} +// ------------------------------------------------------------------- + +// ListValue + +// repeated .google.protobuf.Value values = 1; +inline int ListValue::_internal_values_size() const { + return values_.size(); +} +inline int ListValue::values_size() const { + return _internal_values_size(); +} +inline void ListValue::clear_values() { + values_.Clear(); +} +inline ::PROTOBUF_NAMESPACE_ID::Value* ListValue::mutable_values(int index) { + // @@protoc_insertion_point(field_mutable:google.protobuf.ListValue.values) + return values_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Value >* +ListValue::mutable_values() { + // @@protoc_insertion_point(field_mutable_list:google.protobuf.ListValue.values) + return &values_; +} +inline const ::PROTOBUF_NAMESPACE_ID::Value& ListValue::_internal_values(int index) const { + return values_.Get(index); +} +inline const ::PROTOBUF_NAMESPACE_ID::Value& ListValue::values(int index) const { + // @@protoc_insertion_point(field_get:google.protobuf.ListValue.values) + return _internal_values(index); +} +inline ::PROTOBUF_NAMESPACE_ID::Value* ListValue::_internal_add_values() { + return values_.Add(); +} +inline ::PROTOBUF_NAMESPACE_ID::Value* ListValue::add_values() { + ::PROTOBUF_NAMESPACE_ID::Value* _add = _internal_add_values(); + // @@protoc_insertion_point(field_add:google.protobuf.ListValue.values) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Value >& +ListValue::values() const { + // @@protoc_insertion_point(field_list:google.protobuf.ListValue.values) + return values_; +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +PROTOBUF_NAMESPACE_CLOSE + +PROTOBUF_NAMESPACE_OPEN + +template <> struct is_proto_enum< ::PROTOBUF_NAMESPACE_ID::NullValue> : ::std::true_type {}; +template <> +inline const EnumDescriptor* GetEnumDescriptor< ::PROTOBUF_NAMESPACE_ID::NullValue>() { + return ::PROTOBUF_NAMESPACE_ID::NullValue_descriptor(); +} + +PROTOBUF_NAMESPACE_CLOSE + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fstruct_2eproto diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/bytestream.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/bytestream.cc new file mode 100644 index 0000000..980d6f6 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/bytestream.cc @@ -0,0 +1,194 @@ +// 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. + +#include + +#include +#include + +#include + +namespace google { +namespace protobuf { +namespace strings { + +void ByteSource::CopyTo(ByteSink* sink, size_t n) { + while (n > 0) { + StringPiece fragment = Peek(); + if (fragment.empty()) { + GOOGLE_LOG(DFATAL) << "ByteSource::CopyTo() overran input."; + break; + } + std::size_t fragment_size = std::min(n, fragment.size()); + sink->Append(fragment.data(), fragment_size); + Skip(fragment_size); + n -= fragment_size; + } +} + +void ByteSink::Flush() {} + +void UncheckedArrayByteSink::Append(const char* data, size_t n) { + if (data != dest_) { + // Catch cases where the pointer returned by GetAppendBuffer() was modified. + GOOGLE_DCHECK(!(dest_ <= data && data < (dest_ + n))) + << "Append() data[] overlaps with dest_[]"; + memcpy(dest_, data, n); + } + dest_ += n; +} + +CheckedArrayByteSink::CheckedArrayByteSink(char* outbuf, size_t capacity) + : outbuf_(outbuf), capacity_(capacity), size_(0), overflowed_(false) { +} + +void CheckedArrayByteSink::Append(const char* bytes, size_t n) { + size_t available = capacity_ - size_; + if (n > available) { + n = available; + overflowed_ = true; + } + if (n > 0 && bytes != (outbuf_ + size_)) { + // Catch cases where the pointer returned by GetAppendBuffer() was modified. + GOOGLE_DCHECK(!(outbuf_ <= bytes && bytes < (outbuf_ + capacity_))) + << "Append() bytes[] overlaps with outbuf_[]"; + memcpy(outbuf_ + size_, bytes, n); + } + size_ += n; +} + +GrowingArrayByteSink::GrowingArrayByteSink(size_t estimated_size) + : capacity_(estimated_size), + buf_(new char[estimated_size]), + size_(0) { +} + +GrowingArrayByteSink::~GrowingArrayByteSink() { + delete[] buf_; // Just in case the user didn't call GetBuffer. +} + +void GrowingArrayByteSink::Append(const char* bytes, size_t n) { + size_t available = capacity_ - size_; + if (bytes != (buf_ + size_)) { + // Catch cases where the pointer returned by GetAppendBuffer() was modified. + // We need to test for this before calling Expand() which may reallocate. + GOOGLE_DCHECK(!(buf_ <= bytes && bytes < (buf_ + capacity_))) + << "Append() bytes[] overlaps with buf_[]"; + } + if (n > available) { + Expand(n - available); + } + if (n > 0 && bytes != (buf_ + size_)) { + memcpy(buf_ + size_, bytes, n); + } + size_ += n; +} + +char* GrowingArrayByteSink::GetBuffer(size_t* nbytes) { + ShrinkToFit(); + char* b = buf_; + *nbytes = size_; + buf_ = nullptr; + size_ = capacity_ = 0; + return b; +} + +void GrowingArrayByteSink::Expand(size_t amount) { // Expand by at least 50%. + size_t new_capacity = std::max(capacity_ + amount, (3 * capacity_) / 2); + char* bigger = new char[new_capacity]; + memcpy(bigger, buf_, size_); + delete[] buf_; + buf_ = bigger; + capacity_ = new_capacity; +} + +void GrowingArrayByteSink::ShrinkToFit() { + // Shrink only if the buffer is large and size_ is less than 3/4 + // of capacity_. + if (capacity_ > 256 && size_ < (3 * capacity_) / 4) { + char* just_enough = new char[size_]; + memcpy(just_enough, buf_, size_); + delete[] buf_; + buf_ = just_enough; + capacity_ = size_; + } +} + +void StringByteSink::Append(const char* data, size_t n) { + dest_->append(data, n); +} + +size_t ArrayByteSource::Available() const { + return input_.size(); +} + +StringPiece ArrayByteSource::Peek() { + return input_; +} + +void ArrayByteSource::Skip(size_t n) { + GOOGLE_DCHECK_LE(n, input_.size()); + input_.remove_prefix(n); +} + +LimitByteSource::LimitByteSource(ByteSource *source, size_t limit) + : source_(source), + limit_(limit) { +} + +size_t LimitByteSource::Available() const { + size_t available = source_->Available(); + if (available > limit_) { + available = limit_; + } + + return available; +} + +StringPiece LimitByteSource::Peek() { + StringPiece piece = source_->Peek(); + return StringPiece(piece.data(), std::min(piece.size(), limit_)); +} + +void LimitByteSource::Skip(size_t n) { + GOOGLE_DCHECK_LE(n, limit_); + source_->Skip(n); + limit_ -= n; +} + +void LimitByteSource::CopyTo(ByteSink *sink, size_t n) { + GOOGLE_DCHECK_LE(n, limit_); + source_->CopyTo(sink, n); + limit_ -= n; +} + +} // namespace strings +} // namespace protobuf +} // namespace google diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/bytestream.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/bytestream.h new file mode 100644 index 0000000..c7a48de --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/bytestream.h @@ -0,0 +1,351 @@ +// 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. + +// This file declares the ByteSink and ByteSource abstract interfaces. These +// interfaces represent objects that consume (ByteSink) or produce (ByteSource) +// a sequence of bytes. Using these abstract interfaces in your APIs can help +// make your code work with a variety of input and output types. +// +// This file also declares the following commonly used implementations of these +// interfaces. +// +// ByteSink: +// UncheckedArrayByteSink Writes to an array, without bounds checking +// CheckedArrayByteSink Writes to an array, with bounds checking +// GrowingArrayByteSink Allocates and writes to a growable buffer +// StringByteSink Writes to an STL string +// NullByteSink Consumes a never-ending stream of bytes +// +// ByteSource: +// ArrayByteSource Reads from an array or string/StringPiece +// LimitedByteSource Limits the number of bytes read from an + +#ifndef GOOGLE_PROTOBUF_STUBS_BYTESTREAM_H_ +#define GOOGLE_PROTOBUF_STUBS_BYTESTREAM_H_ + +#include +#include + +#include +#include + +#include + +class CordByteSink; + +namespace google { +namespace protobuf { +namespace strings { + +// An abstract interface for an object that consumes a sequence of bytes. This +// interface offers a way to append data as well as a Flush() function. +// +// Example: +// +// string my_data; +// ... +// ByteSink* sink = ... +// sink->Append(my_data.data(), my_data.size()); +// sink->Flush(); +// +class PROTOBUF_EXPORT ByteSink { + public: + ByteSink() {} + virtual ~ByteSink() {} + + // Appends the "n" bytes starting at "bytes". + virtual void Append(const char* bytes, size_t n) = 0; + + // Flushes internal buffers. The default implementation does nothing. ByteSink + // subclasses may use internal buffers that require calling Flush() at the end + // of the stream. + virtual void Flush(); + + private: + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ByteSink); +}; + +// An abstract interface for an object that produces a fixed-size sequence of +// bytes. +// +// Example: +// +// ByteSource* source = ... +// while (source->Available() > 0) { +// StringPiece data = source->Peek(); +// ... do something with "data" ... +// source->Skip(data.length()); +// } +// +class PROTOBUF_EXPORT ByteSource { + public: + ByteSource() {} + virtual ~ByteSource() {} + + // Returns the number of bytes left to read from the source. Available() + // should decrease by N each time Skip(N) is called. Available() may not + // increase. Available() returning 0 indicates that the ByteSource is + // exhausted. + // + // Note: Size() may have been a more appropriate name as it's more + // indicative of the fixed-size nature of a ByteSource. + virtual size_t Available() const = 0; + + // Returns a StringPiece of the next contiguous region of the source. Does not + // reposition the source. The returned region is empty iff Available() == 0. + // + // The returned region is valid until the next call to Skip() or until this + // object is destroyed, whichever occurs first. + // + // The length of the returned StringPiece will be <= Available(). + virtual StringPiece Peek() = 0; + + // Skips the next n bytes. Invalidates any StringPiece returned by a previous + // call to Peek(). + // + // REQUIRES: Available() >= n + virtual void Skip(size_t n) = 0; + + // Writes the next n bytes in this ByteSource to the given ByteSink, and + // advances this ByteSource past the copied bytes. The default implementation + // of this method just copies the bytes normally, but subclasses might + // override CopyTo to optimize certain cases. + // + // REQUIRES: Available() >= n + virtual void CopyTo(ByteSink* sink, size_t n); + + private: + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ByteSource); +}; + +// +// Some commonly used implementations of ByteSink +// + +// Implementation of ByteSink that writes to an unsized byte array. No +// bounds-checking is performed--it is the caller's responsibility to ensure +// that the destination array is large enough. +// +// Example: +// +// char buf[10]; +// UncheckedArrayByteSink sink(buf); +// sink.Append("hi", 2); // OK +// sink.Append(data, 100); // WOOPS! Overflows buf[10]. +// +class PROTOBUF_EXPORT UncheckedArrayByteSink : public ByteSink { + public: + explicit UncheckedArrayByteSink(char* dest) : dest_(dest) {} + virtual void Append(const char* data, size_t n) override; + + // Returns the current output pointer so that a caller can see how many bytes + // were produced. + // + // Note: this method is not part of the ByteSink interface. + char* CurrentDestination() const { return dest_; } + + private: + char* dest_; + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(UncheckedArrayByteSink); +}; + +// Implementation of ByteSink that writes to a sized byte array. This sink will +// not write more than "capacity" bytes to outbuf. Once "capacity" bytes are +// appended, subsequent bytes will be ignored and Overflowed() will return true. +// Overflowed() does not cause a runtime error (i.e., it does not CHECK fail). +// +// Example: +// +// char buf[10]; +// CheckedArrayByteSink sink(buf, 10); +// sink.Append("hi", 2); // OK +// sink.Append(data, 100); // Will only write 8 more bytes +// +class PROTOBUF_EXPORT CheckedArrayByteSink : public ByteSink { + public: + CheckedArrayByteSink(char* outbuf, size_t capacity); + virtual void Append(const char* bytes, size_t n) override; + + // Returns the number of bytes actually written to the sink. + size_t NumberOfBytesWritten() const { return size_; } + + // Returns true if any bytes were discarded, i.e., if there was an + // attempt to write more than 'capacity' bytes. + bool Overflowed() const { return overflowed_; } + + private: + char* outbuf_; + const size_t capacity_; + size_t size_; + bool overflowed_; + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CheckedArrayByteSink); +}; + +// Implementation of ByteSink that allocates an internal buffer (a char array) +// and expands it as needed to accommodate appended data (similar to a string), +// and allows the caller to take ownership of the internal buffer via the +// GetBuffer() method. The buffer returned from GetBuffer() must be deleted by +// the caller with delete[]. GetBuffer() also sets the internal buffer to be +// empty, and subsequent appends to the sink will create a new buffer. The +// destructor will free the internal buffer if GetBuffer() was not called. +// +// Example: +// +// GrowingArrayByteSink sink(10); +// sink.Append("hi", 2); +// sink.Append(data, n); +// const char* buf = sink.GetBuffer(); // Ownership transferred +// delete[] buf; +// +class PROTOBUF_EXPORT GrowingArrayByteSink : public strings::ByteSink { + public: + explicit GrowingArrayByteSink(size_t estimated_size); + virtual ~GrowingArrayByteSink(); + virtual void Append(const char* bytes, size_t n) override; + + // Returns the allocated buffer, and sets nbytes to its size. The caller takes + // ownership of the buffer and must delete it with delete[]. + char* GetBuffer(size_t* nbytes); + + private: + void Expand(size_t amount); + void ShrinkToFit(); + + size_t capacity_; + char* buf_; + size_t size_; + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(GrowingArrayByteSink); +}; + +// Implementation of ByteSink that appends to the given string. +// Existing contents of "dest" are not modified; new data is appended. +// +// Example: +// +// string dest = "Hello "; +// StringByteSink sink(&dest); +// sink.Append("World", 5); +// assert(dest == "Hello World"); +// +class PROTOBUF_EXPORT StringByteSink : public ByteSink { + public: + explicit StringByteSink(std::string* dest) : dest_(dest) {} + virtual void Append(const char* data, size_t n) override; + + private: + std::string* dest_; + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringByteSink); +}; + +// Implementation of ByteSink that discards all data. +// +// Example: +// +// NullByteSink sink; +// sink.Append(data, data.size()); // All data ignored. +// +class PROTOBUF_EXPORT NullByteSink : public ByteSink { + public: + NullByteSink() {} + void Append(const char* /*data*/, size_t /*n*/) override {} + + private: + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(NullByteSink); +}; + +// +// Some commonly used implementations of ByteSource +// + +// Implementation of ByteSource that reads from a StringPiece. +// +// Example: +// +// string data = "Hello"; +// ArrayByteSource source(data); +// assert(source.Available() == 5); +// assert(source.Peek() == "Hello"); +// +class PROTOBUF_EXPORT ArrayByteSource : public ByteSource { + public: + explicit ArrayByteSource(StringPiece s) : input_(s) {} + + virtual size_t Available() const override; + virtual StringPiece Peek() override; + virtual void Skip(size_t n) override; + + private: + StringPiece input_; + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ArrayByteSource); +}; + +// Implementation of ByteSource that wraps another ByteSource, limiting the +// number of bytes returned. +// +// The caller maintains ownership of the underlying source, and may not use the +// underlying source while using the LimitByteSource object. The underlying +// source's pointer is advanced by n bytes every time this LimitByteSource +// object is advanced by n. +// +// Example: +// +// string data = "Hello World"; +// ArrayByteSource abs(data); +// assert(abs.Available() == data.size()); +// +// LimitByteSource limit(abs, 5); +// assert(limit.Available() == 5); +// assert(limit.Peek() == "Hello"); +// +class PROTOBUF_EXPORT LimitByteSource : public ByteSource { + public: + // Returns at most "limit" bytes from "source". + LimitByteSource(ByteSource* source, size_t limit); + + virtual size_t Available() const override; + virtual StringPiece Peek() override; + virtual void Skip(size_t n) override; + + // We override CopyTo so that we can forward to the underlying source, in + // case it has an efficient implementation of CopyTo. + virtual void CopyTo(ByteSink* sink, size_t n) override; + + private: + ByteSource* source_; + size_t limit_; +}; + +} // namespace strings +} // namespace protobuf +} // namespace google + +#include + +#endif // GOOGLE_PROTOBUF_STUBS_BYTESTREAM_H_ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/common_unittest.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/common_unittest.cc new file mode 100644 index 0000000..c55e452 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/common_unittest.cc @@ -0,0 +1,358 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: kenton@google.com (Kenton Varda) + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace google { +namespace protobuf { +namespace { + +// TODO(kenton): More tests. + +#ifdef PACKAGE_VERSION // only defined when using automake, not MSVC + +TEST(VersionTest, VersionMatchesConfig) { + // Verify that the version string specified in config.h matches the one + // in common.h. The config.h version is a string which may have a suffix + // like "beta" or "rc1", so we remove that. + std::string version = PACKAGE_VERSION; + int pos = 0; + while (pos < version.size() && + (ascii_isdigit(version[pos]) || version[pos] == '.')) { + ++pos; + } + version.erase(pos); + + EXPECT_EQ(version, internal::VersionString(GOOGLE_PROTOBUF_VERSION)); +} + +#endif // PACKAGE_VERSION + +TEST(CommonTest, IntMinMaxConstants) { + // kint32min was declared incorrectly in the first release of protobufs. + // Ugh. + EXPECT_LT(kint32min, kint32max); + EXPECT_EQ(static_cast(kint32min), static_cast(kint32max) + 1); + EXPECT_LT(kint64min, kint64max); + EXPECT_EQ(static_cast(kint64min), static_cast(kint64max) + 1); + EXPECT_EQ(0, kuint32max + 1); + EXPECT_EQ(0, kuint64max + 1); +} + +std::vector captured_messages_; + +void CaptureLog(LogLevel level, const char* filename, int line, + const std::string& message) { + captured_messages_.push_back( + strings::Substitute("$0 $1:$2: $3", + implicit_cast(level), filename, line, message)); +} + +TEST(LoggingTest, DefaultLogging) { + CaptureTestStderr(); + int line = __LINE__; + GOOGLE_LOG(INFO ) << "A message."; + GOOGLE_LOG(WARNING) << "A warning."; + GOOGLE_LOG(ERROR ) << "An error."; + + std::string text = GetCapturedTestStderr(); + EXPECT_EQ( + "[libprotobuf INFO " __FILE__ ":" + SimpleItoa(line + 1) + "] A message.\n" + "[libprotobuf WARNING " __FILE__ ":" + SimpleItoa(line + 2) + "] A warning.\n" + "[libprotobuf ERROR " __FILE__ ":" + SimpleItoa(line + 3) + "] An error.\n", + text); +} + +TEST(LoggingTest, NullLogging) { + LogHandler* old_handler = SetLogHandler(nullptr); + + CaptureTestStderr(); + GOOGLE_LOG(INFO ) << "A message."; + GOOGLE_LOG(WARNING) << "A warning."; + GOOGLE_LOG(ERROR ) << "An error."; + + EXPECT_TRUE(SetLogHandler(old_handler) == nullptr); + + std::string text = GetCapturedTestStderr(); + EXPECT_EQ("", text); +} + +TEST(LoggingTest, CaptureLogging) { + captured_messages_.clear(); + + LogHandler* old_handler = SetLogHandler(&CaptureLog); + + int start_line = __LINE__; + GOOGLE_LOG(ERROR) << "An error."; + GOOGLE_LOG(WARNING) << "A warning."; + + EXPECT_TRUE(SetLogHandler(old_handler) == &CaptureLog); + + ASSERT_EQ(2, captured_messages_.size()); + EXPECT_EQ( + "2 " __FILE__ ":" + SimpleItoa(start_line + 1) + ": An error.", + captured_messages_[0]); + EXPECT_EQ( + "1 " __FILE__ ":" + SimpleItoa(start_line + 2) + ": A warning.", + captured_messages_[1]); +} + +TEST(LoggingTest, SilenceLogging) { + captured_messages_.clear(); + + LogHandler* old_handler = SetLogHandler(&CaptureLog); + + int line1 = __LINE__; GOOGLE_LOG(INFO) << "Visible1"; + LogSilencer* silencer1 = new LogSilencer; + GOOGLE_LOG(INFO) << "Not visible."; + LogSilencer* silencer2 = new LogSilencer; + GOOGLE_LOG(INFO) << "Not visible."; + delete silencer1; + GOOGLE_LOG(INFO) << "Not visible."; + delete silencer2; + int line2 = __LINE__; GOOGLE_LOG(INFO) << "Visible2"; + + EXPECT_TRUE(SetLogHandler(old_handler) == &CaptureLog); + + ASSERT_EQ(2, captured_messages_.size()); + EXPECT_EQ( + "0 " __FILE__ ":" + SimpleItoa(line1) + ": Visible1", + captured_messages_[0]); + EXPECT_EQ( + "0 " __FILE__ ":" + SimpleItoa(line2) + ": Visible2", + captured_messages_[1]); +} + +class ClosureTest : public testing::Test { + public: + void SetA123Method() { a_ = 123; } + static void SetA123Function() { current_instance_->a_ = 123; } + + void SetAMethod(int a) { a_ = a; } + void SetCMethod(std::string c) { c_ = c; } + + static void SetAFunction(int a) { current_instance_->a_ = a; } + static void SetCFunction(std::string c) { current_instance_->c_ = c; } + + void SetABMethod(int a, const char* b) { a_ = a; b_ = b; } + static void SetABFunction(int a, const char* b) { + current_instance_->a_ = a; + current_instance_->b_ = b; + } + + virtual void SetUp() { + current_instance_ = this; + a_ = 0; + b_ = nullptr; + c_.clear(); + permanent_closure_ = nullptr; + } + + void DeleteClosureInCallback() { + delete permanent_closure_; + } + + int a_; + const char* b_; + std::string c_; + Closure* permanent_closure_; + + static ClosureTest* current_instance_; +}; + +ClosureTest* ClosureTest::current_instance_ = nullptr; + +TEST_F(ClosureTest, TestClosureFunction0) { + Closure* closure = NewCallback(&SetA123Function); + EXPECT_NE(123, a_); + closure->Run(); + EXPECT_EQ(123, a_); +} + +TEST_F(ClosureTest, TestClosureMethod0) { + Closure* closure = NewCallback(current_instance_, + &ClosureTest::SetA123Method); + EXPECT_NE(123, a_); + closure->Run(); + EXPECT_EQ(123, a_); +} + +TEST_F(ClosureTest, TestClosureFunction1) { + Closure* closure = NewCallback(&SetAFunction, 456); + EXPECT_NE(456, a_); + closure->Run(); + EXPECT_EQ(456, a_); +} + +TEST_F(ClosureTest, TestClosureMethod1) { + Closure* closure = NewCallback(current_instance_, + &ClosureTest::SetAMethod, 456); + EXPECT_NE(456, a_); + closure->Run(); + EXPECT_EQ(456, a_); +} + +TEST_F(ClosureTest, TestClosureFunction1String) { + Closure* closure = NewCallback(&SetCFunction, std::string("test")); + EXPECT_NE("test", c_); + closure->Run(); + EXPECT_EQ("test", c_); +} + +TEST_F(ClosureTest, TestClosureMethod1String) { + Closure* closure = NewCallback(current_instance_, &ClosureTest::SetCMethod, + std::string("test")); + EXPECT_NE("test", c_); + closure->Run(); + EXPECT_EQ("test", c_); +} + +TEST_F(ClosureTest, TestClosureFunction2) { + const char* cstr = "hello"; + Closure* closure = NewCallback(&SetABFunction, 789, cstr); + EXPECT_NE(789, a_); + EXPECT_NE(cstr, b_); + closure->Run(); + EXPECT_EQ(789, a_); + EXPECT_EQ(cstr, b_); +} + +TEST_F(ClosureTest, TestClosureMethod2) { + const char* cstr = "hello"; + Closure* closure = NewCallback(current_instance_, + &ClosureTest::SetABMethod, 789, cstr); + EXPECT_NE(789, a_); + EXPECT_NE(cstr, b_); + closure->Run(); + EXPECT_EQ(789, a_); + EXPECT_EQ(cstr, b_); +} + +// Repeat all of the above with NewPermanentCallback() + +TEST_F(ClosureTest, TestPermanentClosureFunction0) { + Closure* closure = NewPermanentCallback(&SetA123Function); + EXPECT_NE(123, a_); + closure->Run(); + EXPECT_EQ(123, a_); + a_ = 0; + closure->Run(); + EXPECT_EQ(123, a_); + delete closure; +} + +TEST_F(ClosureTest, TestPermanentClosureMethod0) { + Closure* closure = NewPermanentCallback(current_instance_, + &ClosureTest::SetA123Method); + EXPECT_NE(123, a_); + closure->Run(); + EXPECT_EQ(123, a_); + a_ = 0; + closure->Run(); + EXPECT_EQ(123, a_); + delete closure; +} + +TEST_F(ClosureTest, TestPermanentClosureFunction1) { + Closure* closure = NewPermanentCallback(&SetAFunction, 456); + EXPECT_NE(456, a_); + closure->Run(); + EXPECT_EQ(456, a_); + a_ = 0; + closure->Run(); + EXPECT_EQ(456, a_); + delete closure; +} + +TEST_F(ClosureTest, TestPermanentClosureMethod1) { + Closure* closure = NewPermanentCallback(current_instance_, + &ClosureTest::SetAMethod, 456); + EXPECT_NE(456, a_); + closure->Run(); + EXPECT_EQ(456, a_); + a_ = 0; + closure->Run(); + EXPECT_EQ(456, a_); + delete closure; +} + +TEST_F(ClosureTest, TestPermanentClosureFunction2) { + const char* cstr = "hello"; + Closure* closure = NewPermanentCallback(&SetABFunction, 789, cstr); + EXPECT_NE(789, a_); + EXPECT_NE(cstr, b_); + closure->Run(); + EXPECT_EQ(789, a_); + EXPECT_EQ(cstr, b_); + a_ = 0; + b_ = nullptr; + closure->Run(); + EXPECT_EQ(789, a_); + EXPECT_EQ(cstr, b_); + delete closure; +} + +TEST_F(ClosureTest, TestPermanentClosureMethod2) { + const char* cstr = "hello"; + Closure* closure = NewPermanentCallback(current_instance_, + &ClosureTest::SetABMethod, 789, cstr); + EXPECT_NE(789, a_); + EXPECT_NE(cstr, b_); + closure->Run(); + EXPECT_EQ(789, a_); + EXPECT_EQ(cstr, b_); + a_ = 0; + b_ = nullptr; + closure->Run(); + EXPECT_EQ(789, a_); + EXPECT_EQ(cstr, b_); + delete closure; +} + +TEST_F(ClosureTest, TestPermanentClosureDeleteInCallback) { + permanent_closure_ = NewPermanentCallback((ClosureTest*) this, + &ClosureTest::DeleteClosureInCallback); + permanent_closure_->Run(); +} + +} // anonymous namespace +} // namespace protobuf +} // namespace google diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/hash.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/hash.h new file mode 100644 index 0000000..a7ec068 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/hash.h @@ -0,0 +1,114 @@ +// 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) + +#ifndef GOOGLE_PROTOBUF_STUBS_HASH_H__ +#define GOOGLE_PROTOBUF_STUBS_HASH_H__ + +#include +#include +#include +#include + +# define GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_START \ + namespace google { \ + namespace protobuf { +# define GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_END }} + +namespace google { +namespace protobuf { + +template +struct hash : public std::hash {}; + +template +struct hash { + inline size_t operator()(const Key* key) const { + return reinterpret_cast(key); + } +}; + +// Unlike the old SGI version, the TR1 "hash" does not special-case char*. So, +// we go ahead and provide our own implementation. +template <> +struct hash { + inline size_t operator()(const char* str) const { + size_t result = 0; + for (; *str != '\0'; str++) { + result = 5 * result + static_cast(*str); + } + return result; + } +}; + +template<> +struct hash { + size_t operator()(bool x) const { + return static_cast(x); + } +}; + +template <> +struct hash { + inline size_t operator()(const std::string& key) const { + return hash()(key.c_str()); + } + + static const size_t bucket_size = 4; + static const size_t min_buckets = 8; + inline bool operator()(const std::string& a, const std::string& b) const { + return a < b; + } +}; + +template +struct hash > { + inline size_t operator()(const std::pair& key) const { + size_t first_hash = hash()(key.first); + size_t second_hash = hash()(key.second); + + // FIXME(kenton): What is the best way to compute this hash? I have + // no idea! This seems a bit better than an XOR. + return first_hash * ((1 << 16) - 1) + second_hash; + } + + static const size_t bucket_size = 4; + static const size_t min_buckets = 8; + inline bool operator()(const std::pair& a, + const std::pair& b) const { + return a < b; + } +}; + +} // namespace protobuf +} // namespace google + +#endif // GOOGLE_PROTOBUF_STUBS_HASH_H__ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/map_util.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/map_util.h new file mode 100644 index 0000000..24e098a --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/map_util.h @@ -0,0 +1,769 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2014 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// from google3/util/gtl/map_util.h +// Author: Anton Carver + +#ifndef GOOGLE_PROTOBUF_STUBS_MAP_UTIL_H__ +#define GOOGLE_PROTOBUF_STUBS_MAP_UTIL_H__ + +#include +#include +#include +#include +#include + +#include + +namespace google { +namespace protobuf { +namespace internal { +// Local implementation of RemoveConst to avoid including base/type_traits.h. +template struct RemoveConst { typedef T type; }; +template struct RemoveConst : RemoveConst {}; +} // namespace internal + +// +// Find*() +// + +// Returns a const reference to the value associated with the given key if it +// exists. Crashes otherwise. +// +// This is intended as a replacement for operator[] as an rvalue (for reading) +// when the key is guaranteed to exist. +// +// operator[] for lookup is discouraged for several reasons: +// * It has a side-effect of inserting missing keys +// * It is not thread-safe (even when it is not inserting, it can still +// choose to resize the underlying storage) +// * It invalidates iterators (when it chooses to resize) +// * It default constructs a value object even if it doesn't need to +// +// This version assumes the key is printable, and includes it in the fatal log +// message. +template +const typename Collection::value_type::second_type& +FindOrDie(const Collection& collection, + const typename Collection::value_type::first_type& key) { + typename Collection::const_iterator it = collection.find(key); + GOOGLE_CHECK(it != collection.end()) << "Map key not found: " << key; + return it->second; +} + +// Same as above, but returns a non-const reference. +template +typename Collection::value_type::second_type& +FindOrDie(Collection& collection, // NOLINT + const typename Collection::value_type::first_type& key) { + typename Collection::iterator it = collection.find(key); + GOOGLE_CHECK(it != collection.end()) << "Map key not found: " << key; + return it->second; +} + +// Same as FindOrDie above, but doesn't log the key on failure. +template +const typename Collection::value_type::second_type& +FindOrDieNoPrint(const Collection& collection, + const typename Collection::value_type::first_type& key) { + typename Collection::const_iterator it = collection.find(key); + GOOGLE_CHECK(it != collection.end()) << "Map key not found"; + return it->second; +} + +// Same as above, but returns a non-const reference. +template +typename Collection::value_type::second_type& +FindOrDieNoPrint(Collection& collection, // NOLINT + const typename Collection::value_type::first_type& key) { + typename Collection::iterator it = collection.find(key); + GOOGLE_CHECK(it != collection.end()) << "Map key not found"; + return it->second; +} + +// Returns a const reference to the value associated with the given key if it +// exists, otherwise returns a const reference to the provided default value. +// +// WARNING: If a temporary object is passed as the default "value," +// this function will return a reference to that temporary object, +// which will be destroyed at the end of the statement. A common +// example: if you have a map with string values, and you pass a char* +// as the default "value," either use the returned value immediately +// or store it in a string (not string&). +// Details: http://go/findwithdefault +template +const typename Collection::value_type::second_type& +FindWithDefault(const Collection& collection, + const typename Collection::value_type::first_type& key, + const typename Collection::value_type::second_type& value) { + typename Collection::const_iterator it = collection.find(key); + if (it == collection.end()) { + return value; + } + return it->second; +} + +// Returns a pointer to the const value associated with the given key if it +// exists, or nullptr otherwise. +template +const typename Collection::value_type::second_type* +FindOrNull(const Collection& collection, + const typename Collection::value_type::first_type& key) { + typename Collection::const_iterator it = collection.find(key); + if (it == collection.end()) { + return 0; + } + return &it->second; +} + +// Same as above but returns a pointer to the non-const value. +template +typename Collection::value_type::second_type* +FindOrNull(Collection& collection, // NOLINT + const typename Collection::value_type::first_type& key) { + typename Collection::iterator it = collection.find(key); + if (it == collection.end()) { + return 0; + } + return &it->second; +} + +// Returns the pointer value associated with the given key. If none is found, +// nullptr is returned. The function is designed to be used with a map of keys to +// pointers. +// +// This function does not distinguish between a missing key and a key mapped +// to nullptr. +template +typename Collection::value_type::second_type +FindPtrOrNull(const Collection& collection, + const typename Collection::value_type::first_type& key) { + typename Collection::const_iterator it = collection.find(key); + if (it == collection.end()) { + return typename Collection::value_type::second_type(); + } + return it->second; +} + +// Same as above, except takes non-const reference to collection. +// +// This function is needed for containers that propagate constness to the +// pointee, such as boost::ptr_map. +template +typename Collection::value_type::second_type +FindPtrOrNull(Collection& collection, // NOLINT + const typename Collection::value_type::first_type& key) { + typename Collection::iterator it = collection.find(key); + if (it == collection.end()) { + return typename Collection::value_type::second_type(); + } + return it->second; +} + +// Finds the pointer value associated with the given key in a map whose values +// are linked_ptrs. Returns nullptr if key is not found. +template +typename Collection::value_type::second_type::element_type* +FindLinkedPtrOrNull(const Collection& collection, + const typename Collection::value_type::first_type& key) { + typename Collection::const_iterator it = collection.find(key); + if (it == collection.end()) { + return 0; + } + // Since linked_ptr::get() is a const member returning a non const, + // we do not need a version of this function taking a non const collection. + return it->second.get(); +} + +// Same as above, but dies if the key is not found. +template +typename Collection::value_type::second_type::element_type& +FindLinkedPtrOrDie(const Collection& collection, + const typename Collection::value_type::first_type& key) { + typename Collection::const_iterator it = collection.find(key); + GOOGLE_CHECK(it != collection.end()) << "key not found: " << key; + // Since linked_ptr::operator*() is a const member returning a non const, + // we do not need a version of this function taking a non const collection. + return *it->second; +} + +// Finds the value associated with the given key and copies it to *value (if not +// nullptr). Returns false if the key was not found, true otherwise. +template +bool FindCopy(const Collection& collection, + const Key& key, + Value* const value) { + typename Collection::const_iterator it = collection.find(key); + if (it == collection.end()) { + return false; + } + if (value) { + *value = it->second; + } + return true; +} + +// +// Contains*() +// + +// Returns true if and only if the given collection contains the given key. +template +bool ContainsKey(const Collection& collection, const Key& key) { + return collection.find(key) != collection.end(); +} + +// Returns true if and only if the given collection contains the given key-value +// pair. +template +bool ContainsKeyValuePair(const Collection& collection, + const Key& key, + const Value& value) { + typedef typename Collection::const_iterator const_iterator; + std::pair range = collection.equal_range(key); + for (const_iterator it = range.first; it != range.second; ++it) { + if (it->second == value) { + return true; + } + } + return false; +} + +// +// Insert*() +// + +// Inserts the given key-value pair into the collection. Returns true if and +// only if the key from the given pair didn't previously exist. Otherwise, the +// value in the map is replaced with the value from the given pair. +template +bool InsertOrUpdate(Collection* const collection, + const typename Collection::value_type& vt) { + std::pair ret = collection->insert(vt); + if (!ret.second) { + // update + ret.first->second = vt.second; + return false; + } + return true; +} + +// Same as above, except that the key and value are passed separately. +template +bool InsertOrUpdate(Collection* const collection, + const typename Collection::value_type::first_type& key, + const typename Collection::value_type::second_type& value) { + return InsertOrUpdate( + collection, typename Collection::value_type(key, value)); +} + +// Inserts/updates all the key-value pairs from the range defined by the +// iterators "first" and "last" into the given collection. +template +void InsertOrUpdateMany(Collection* const collection, + InputIterator first, InputIterator last) { + for (; first != last; ++first) { + InsertOrUpdate(collection, *first); + } +} + +// Change the value associated with a particular key in a map or hash_map +// of the form map which owns the objects pointed to by the +// value pointers. If there was an existing value for the key, it is deleted. +// True indicates an insert took place, false indicates an update + delete. +template +bool InsertAndDeleteExisting( + Collection* const collection, + const typename Collection::value_type::first_type& key, + const typename Collection::value_type::second_type& value) { + std::pair ret = + collection->insert(typename Collection::value_type(key, value)); + if (!ret.second) { + delete ret.first->second; + ret.first->second = value; + return false; + } + return true; +} + +// Inserts the given key and value into the given collection if and only if the +// given key did NOT already exist in the collection. If the key previously +// existed in the collection, the value is not changed. Returns true if the +// key-value pair was inserted; returns false if the key was already present. +template +bool InsertIfNotPresent(Collection* const collection, + const typename Collection::value_type& vt) { + return collection->insert(vt).second; +} + +// Same as above except the key and value are passed separately. +template +bool InsertIfNotPresent( + Collection* const collection, + const typename Collection::value_type::first_type& key, + const typename Collection::value_type::second_type& value) { + return InsertIfNotPresent( + collection, typename Collection::value_type(key, value)); +} + +// Same as above except dies if the key already exists in the collection. +template +void InsertOrDie(Collection* const collection, + const typename Collection::value_type& value) { + GOOGLE_CHECK(InsertIfNotPresent(collection, value)) + << "duplicate value: " << value; +} + +// Same as above except doesn't log the value on error. +template +void InsertOrDieNoPrint(Collection* const collection, + const typename Collection::value_type& value) { + GOOGLE_CHECK(InsertIfNotPresent(collection, value)) << "duplicate value."; +} + +// Inserts the key-value pair into the collection. Dies if key was already +// present. +template +void InsertOrDie(Collection* const collection, + const typename Collection::value_type::first_type& key, + const typename Collection::value_type::second_type& data) { + GOOGLE_CHECK(InsertIfNotPresent(collection, key, data)) + << "duplicate key: " << key; +} + +// Same as above except doesn't log the key on error. +template +void InsertOrDieNoPrint( + Collection* const collection, + const typename Collection::value_type::first_type& key, + const typename Collection::value_type::second_type& data) { + GOOGLE_CHECK(InsertIfNotPresent(collection, key, data)) << "duplicate key."; +} + +// Inserts a new key and default-initialized value. Dies if the key was already +// present. Returns a reference to the value. Example usage: +// +// map m; +// SomeProto& proto = InsertKeyOrDie(&m, 3); +// proto.set_field("foo"); +template +typename Collection::value_type::second_type& InsertKeyOrDie( + Collection* const collection, + const typename Collection::value_type::first_type& key) { + typedef typename Collection::value_type value_type; + std::pair res = + collection->insert(value_type(key, typename value_type::second_type())); + GOOGLE_CHECK(res.second) << "duplicate key: " << key; + return res.first->second; +} + +// +// Lookup*() +// + +// Looks up a given key and value pair in a collection and inserts the key-value +// pair if it's not already present. Returns a reference to the value associated +// with the key. +template +typename Collection::value_type::second_type& +LookupOrInsert(Collection* const collection, + const typename Collection::value_type& vt) { + return collection->insert(vt).first->second; +} + +// Same as above except the key-value are passed separately. +template +typename Collection::value_type::second_type& +LookupOrInsert(Collection* const collection, + const typename Collection::value_type::first_type& key, + const typename Collection::value_type::second_type& value) { + return LookupOrInsert( + collection, typename Collection::value_type(key, value)); +} + +// Counts the number of equivalent elements in the given "sequence", and stores +// the results in "count_map" with element as the key and count as the value. +// +// Example: +// vector v = {"a", "b", "c", "a", "b"}; +// map m; +// AddTokenCounts(v, 1, &m); +// assert(m["a"] == 2); +// assert(m["b"] == 2); +// assert(m["c"] == 1); +template +void AddTokenCounts( + const Sequence& sequence, + const typename Collection::value_type::second_type& increment, + Collection* const count_map) { + for (typename Sequence::const_iterator it = sequence.begin(); + it != sequence.end(); ++it) { + typename Collection::value_type::second_type& value = + LookupOrInsert(count_map, *it, + typename Collection::value_type::second_type()); + value += increment; + } +} + +// Returns a reference to the value associated with key. If not found, a value +// is default constructed on the heap and added to the map. +// +// This function is useful for containers of the form map, where +// inserting a new key, value pair involves constructing a new heap-allocated +// Value, and storing a pointer to that in the collection. +template +typename Collection::value_type::second_type& +LookupOrInsertNew(Collection* const collection, + const typename Collection::value_type::first_type& key) { + typedef typename std::iterator_traits< + typename Collection::value_type::second_type>::value_type Element; + std::pair ret = + collection->insert(typename Collection::value_type( + key, + static_cast(nullptr))); + if (ret.second) { + ret.first->second = new Element(); + } + return ret.first->second; +} + +// Same as above but constructs the value using the single-argument constructor +// and the given "arg". +template +typename Collection::value_type::second_type& +LookupOrInsertNew(Collection* const collection, + const typename Collection::value_type::first_type& key, + const Arg& arg) { + typedef typename std::iterator_traits< + typename Collection::value_type::second_type>::value_type Element; + std::pair ret = + collection->insert(typename Collection::value_type( + key, + static_cast(nullptr))); + if (ret.second) { + ret.first->second = new Element(arg); + } + return ret.first->second; +} + +// Lookup of linked/shared pointers is used in two scenarios: +// +// Use LookupOrInsertNewLinkedPtr if the container owns the elements. +// In this case it is fine working with the raw pointer as long as it is +// guaranteed that no other thread can delete/update an accessed element. +// A mutex will need to lock the container operation as well as the use +// of the returned elements. Finding an element may be performed using +// FindLinkedPtr*(). +// +// Use LookupOrInsertNewSharedPtr if the container does not own the elements +// for their whole lifetime. This is typically the case when a reader allows +// parallel updates to the container. In this case a Mutex only needs to lock +// container operations, but all element operations must be performed on the +// shared pointer. Finding an element must be performed using FindPtr*() and +// cannot be done with FindLinkedPtr*() even though it compiles. + +// Lookup a key in a map or hash_map whose values are linked_ptrs. If it is +// missing, set collection[key].reset(new Value::element_type) and return that. +// Value::element_type must be default constructable. +template +typename Collection::value_type::second_type::element_type* +LookupOrInsertNewLinkedPtr( + Collection* const collection, + const typename Collection::value_type::first_type& key) { + typedef typename Collection::value_type::second_type Value; + std::pair ret = + collection->insert(typename Collection::value_type(key, Value())); + if (ret.second) { + ret.first->second.reset(new typename Value::element_type); + } + return ret.first->second.get(); +} + +// A variant of LookupOrInsertNewLinkedPtr where the value is constructed using +// a single-parameter constructor. Note: the constructor argument is computed +// even if it will not be used, so only values cheap to compute should be passed +// here. On the other hand it does not matter how expensive the construction of +// the actual stored value is, as that only occurs if necessary. +template +typename Collection::value_type::second_type::element_type* +LookupOrInsertNewLinkedPtr( + Collection* const collection, + const typename Collection::value_type::first_type& key, + const Arg& arg) { + typedef typename Collection::value_type::second_type Value; + std::pair ret = + collection->insert(typename Collection::value_type(key, Value())); + if (ret.second) { + ret.first->second.reset(new typename Value::element_type(arg)); + } + return ret.first->second.get(); +} + +// Lookup a key in a map or hash_map whose values are shared_ptrs. If it is +// missing, set collection[key].reset(new Value::element_type). Unlike +// LookupOrInsertNewLinkedPtr, this function returns the shared_ptr instead of +// the raw pointer. Value::element_type must be default constructable. +template +typename Collection::value_type::second_type& +LookupOrInsertNewSharedPtr( + Collection* const collection, + const typename Collection::value_type::first_type& key) { + typedef typename Collection::value_type::second_type SharedPtr; + typedef typename Collection::value_type::second_type::element_type Element; + std::pair ret = + collection->insert(typename Collection::value_type(key, SharedPtr())); + if (ret.second) { + ret.first->second.reset(new Element()); + } + return ret.first->second; +} + +// A variant of LookupOrInsertNewSharedPtr where the value is constructed using +// a single-parameter constructor. Note: the constructor argument is computed +// even if it will not be used, so only values cheap to compute should be passed +// here. On the other hand it does not matter how expensive the construction of +// the actual stored value is, as that only occurs if necessary. +template +typename Collection::value_type::second_type& +LookupOrInsertNewSharedPtr( + Collection* const collection, + const typename Collection::value_type::first_type& key, + const Arg& arg) { + typedef typename Collection::value_type::second_type SharedPtr; + typedef typename Collection::value_type::second_type::element_type Element; + std::pair ret = + collection->insert(typename Collection::value_type(key, SharedPtr())); + if (ret.second) { + ret.first->second.reset(new Element(arg)); + } + return ret.first->second; +} + +// +// Misc Utility Functions +// + +// Updates the value associated with the given key. If the key was not already +// present, then the key-value pair are inserted and "previous" is unchanged. If +// the key was already present, the value is updated and "*previous" will +// contain a copy of the old value. +// +// InsertOrReturnExisting has complementary behavior that returns the +// address of an already existing value, rather than updating it. +template +bool UpdateReturnCopy(Collection* const collection, + const typename Collection::value_type::first_type& key, + const typename Collection::value_type::second_type& value, + typename Collection::value_type::second_type* previous) { + std::pair ret = + collection->insert(typename Collection::value_type(key, value)); + if (!ret.second) { + // update + if (previous) { + *previous = ret.first->second; + } + ret.first->second = value; + return true; + } + return false; +} + +// Same as above except that the key and value are passed as a pair. +template +bool UpdateReturnCopy(Collection* const collection, + const typename Collection::value_type& vt, + typename Collection::value_type::second_type* previous) { + std::pair ret = collection->insert(vt); + if (!ret.second) { + // update + if (previous) { + *previous = ret.first->second; + } + ret.first->second = vt.second; + return true; + } + return false; +} + +// Tries to insert the given key-value pair into the collection. Returns nullptr if +// the insert succeeds. Otherwise, returns a pointer to the existing value. +// +// This complements UpdateReturnCopy in that it allows to update only after +// verifying the old value and still insert quickly without having to look up +// twice. Unlike UpdateReturnCopy this also does not come with the issue of an +// undefined previous* in case new data was inserted. +template +typename Collection::value_type::second_type* InsertOrReturnExisting( + Collection* const collection, const typename Collection::value_type& vt) { + std::pair ret = collection->insert(vt); + if (ret.second) { + return nullptr; // Inserted, no existing previous value. + } else { + return &ret.first->second; // Return address of already existing value. + } +} + +// Same as above, except for explicit key and data. +template +typename Collection::value_type::second_type* InsertOrReturnExisting( + Collection* const collection, + const typename Collection::value_type::first_type& key, + const typename Collection::value_type::second_type& data) { + return InsertOrReturnExisting(collection, + typename Collection::value_type(key, data)); +} + +// Erases the collection item identified by the given key, and returns the value +// associated with that key. It is assumed that the value (i.e., the +// mapped_type) is a pointer. Returns nullptr if the key was not found in the +// collection. +// +// Examples: +// map my_map; +// +// One line cleanup: +// delete EraseKeyReturnValuePtr(&my_map, "abc"); +// +// Use returned value: +// std::unique_ptr value_ptr( +// EraseKeyReturnValuePtr(&my_map, "abc")); +// if (value_ptr.get()) +// value_ptr->DoSomething(); +// +template +typename Collection::value_type::second_type EraseKeyReturnValuePtr( + Collection* const collection, + const typename Collection::value_type::first_type& key) { + typename Collection::iterator it = collection->find(key); + if (it == collection->end()) { + return nullptr; + } + typename Collection::value_type::second_type v = it->second; + collection->erase(it); + return v; +} + +// Inserts all the keys from map_container into key_container, which must +// support insert(MapContainer::key_type). +// +// Note: any initial contents of the key_container are not cleared. +template +void InsertKeysFromMap(const MapContainer& map_container, + KeyContainer* key_container) { + GOOGLE_CHECK(key_container != nullptr); + for (typename MapContainer::const_iterator it = map_container.begin(); + it != map_container.end(); ++it) { + key_container->insert(it->first); + } +} + +// Appends all the keys from map_container into key_container, which must +// support push_back(MapContainer::key_type). +// +// Note: any initial contents of the key_container are not cleared. +template +void AppendKeysFromMap(const MapContainer& map_container, + KeyContainer* key_container) { + GOOGLE_CHECK(key_container != nullptr); + for (typename MapContainer::const_iterator it = map_container.begin(); + it != map_container.end(); ++it) { + key_container->push_back(it->first); + } +} + +// A more specialized overload of AppendKeysFromMap to optimize reallocations +// for the common case in which we're appending keys to a vector and hence can +// (and sometimes should) call reserve() first. +// +// (It would be possible to play SFINAE games to call reserve() for any +// container that supports it, but this seems to get us 99% of what we need +// without the complexity of a SFINAE-based solution.) +template +void AppendKeysFromMap(const MapContainer& map_container, + std::vector* key_container) { + GOOGLE_CHECK(key_container != nullptr); + // We now have the opportunity to call reserve(). Calling reserve() every + // time is a bad idea for some use cases: libstdc++'s implementation of + // vector<>::reserve() resizes the vector's backing store to exactly the + // given size (unless it's already at least that big). Because of this, + // the use case that involves appending a lot of small maps (total size + // N) one by one to a vector would be O(N^2). But never calling reserve() + // loses the opportunity to improve the use case of adding from a large + // map to an empty vector (this improves performance by up to 33%). A + // number of heuristics are possible; see the discussion in + // cl/34081696. Here we use the simplest one. + if (key_container->empty()) { + key_container->reserve(map_container.size()); + } + for (typename MapContainer::const_iterator it = map_container.begin(); + it != map_container.end(); ++it) { + key_container->push_back(it->first); + } +} + +// Inserts all the values from map_container into value_container, which must +// support push_back(MapContainer::mapped_type). +// +// Note: any initial contents of the value_container are not cleared. +template +void AppendValuesFromMap(const MapContainer& map_container, + ValueContainer* value_container) { + GOOGLE_CHECK(value_container != nullptr); + for (typename MapContainer::const_iterator it = map_container.begin(); + it != map_container.end(); ++it) { + value_container->push_back(it->second); + } +} + +// A more specialized overload of AppendValuesFromMap to optimize reallocations +// for the common case in which we're appending values to a vector and hence +// can (and sometimes should) call reserve() first. +// +// (It would be possible to play SFINAE games to call reserve() for any +// container that supports it, but this seems to get us 99% of what we need +// without the complexity of a SFINAE-based solution.) +template +void AppendValuesFromMap(const MapContainer& map_container, + std::vector* value_container) { + GOOGLE_CHECK(value_container != nullptr); + // See AppendKeysFromMap for why this is done. + if (value_container->empty()) { + value_container->reserve(map_container.size()); + } + for (typename MapContainer::const_iterator it = map_container.begin(); + it != map_container.end(); ++it) { + value_container->push_back(it->second); + } +} + +} // namespace protobuf +} // namespace google + +#endif // GOOGLE_PROTOBUF_STUBS_MAP_UTIL_H__ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/mathutil.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/mathutil.h new file mode 100644 index 0000000..1d16bce --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/mathutil.h @@ -0,0 +1,162 @@ +// 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_STUBS_MATHUTIL_H_ +#define GOOGLE_PROTOBUF_STUBS_MATHUTIL_H_ + +#include +#include +#include + +#include +#include + +namespace google { +namespace protobuf { +namespace internal { + +// Like std::make_unsigned_t except floating point types map to themselves. +template +using MakeUnsignedT = + typename std::conditional::value, std::make_unsigned, + std::common_type>::type::type; + +// Like std::isnan() except a template function that is defined for all numeric +// types. +template ::value, int>::type = 0> +bool IsNan(T /*val*/) { + return false; +} + +template ::value, + int>::type = 0> +bool IsNan(T val) { + return std::isnan(val); +} + +template +bool AlmostEquals(T a, T b) { + return a == b; +} +template<> +inline bool AlmostEquals(float a, float b) { + return fabs(a - b) < 32 * FLT_EPSILON; +} + +template<> +inline bool AlmostEquals(double a, double b) { + return fabs(a - b) < 32 * DBL_EPSILON; +} + +} // namespace internal + +class MathUtil { + public: + template + static T Sign(T value) { + if (value == T(0) || internal::IsNan(value)) { + return value; + } + return value > T(0) ? 1 : -1; + } + + template + static bool AlmostEquals(T a, T b) { + return internal::AlmostEquals(a, b); + } + + // Largest of two values. + // Works correctly for special floating point values. + // Note: 0.0 and -0.0 are not differentiated by Max (Max(0.0, -0.0) is -0.0), + // which should be OK because, although they (can) have different + // bit representation, they are observably the same when examined + // with arithmetic and (in)equality operators. + template + static T Max(const T x, const T y) { + return internal::IsNan(x) || x > y ? x : y; + } + + // Absolute value of x + // Works correctly for unsigned types and + // for special floating point values. + // Note: 0.0 and -0.0 are not differentiated by Abs (Abs(0.0) is -0.0), + // which should be OK: see the comment for Max above. + template + static T Abs(const T x) { + return x > T(0) ? x : -x; + } + + // Absolute value of the difference between two numbers. + // Works correctly for signed types and special floating point values. + template + static typename internal::MakeUnsignedT AbsDiff(const T x, const T y) { + // Carries out arithmetic as unsigned to avoid overflow. + typedef typename internal::MakeUnsignedT R; + return x > y ? R(x) - R(y) : R(y) - R(x); + } + + // If two (usually floating point) numbers are within a certain + // fraction of their magnitude or within a certain absolute margin of error. + // This is the same as the following but faster: + // WithinFraction(x, y, fraction) || WithinMargin(x, y, margin) + // E.g. WithinFraction(0.0, 1e-10, 1e-5) is false but + // WithinFractionOrMargin(0.0, 1e-10, 1e-5, 1e-5) is true. + template + static bool WithinFractionOrMargin(const T x, const T y, + const T fraction, const T margin); +}; + +template +bool MathUtil::WithinFractionOrMargin(const T x, const T y, + const T fraction, const T margin) { + // Not just "0 <= fraction" to fool the compiler for unsigned types. + GOOGLE_DCHECK((T(0) < fraction || T(0) == fraction) && + fraction < T(1) && + margin >= T(0)); + + // Template specialization will convert the if() condition to a constant, + // which will cause the compiler to generate code for either the "if" part + // or the "then" part. In this way we avoid a compiler warning + // about a potential integer overflow in crosstool v12 (gcc 4.3.1). + if (std::numeric_limits::is_integer) { + return x == y; + } else { + if (!std::isfinite(x) || !std::isfinite(y)) { + return false; + } + T relative_margin = static_cast(fraction * Max(Abs(x), Abs(y))); + return AbsDiff(x, y) <= Max(margin, relative_margin); + } +} + +} // namespace protobuf +} // namespace google + +#endif // GOOGLE_PROTOBUF_STUBS_MATHUTIL_H_ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/status_macros.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/status_macros.h new file mode 100644 index 0000000..407ff4c --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/status_macros.h @@ -0,0 +1,89 @@ +// 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. + +// From: util/task/contrib/status_macros/status_macros.h + +#ifndef GOOGLE_PROTOBUF_STUBS_STATUS_MACROS_H_ +#define GOOGLE_PROTOBUF_STUBS_STATUS_MACROS_H_ + +#include +#include +#include + +namespace google { +namespace protobuf { +namespace util { + +// Run a command that returns a util::Status. If the called code returns an +// error status, return that status up out of this method too. +// +// Example: +// RETURN_IF_ERROR(DoThings(4)); +#define RETURN_IF_ERROR(expr) \ + do { \ + /* Using _status below to avoid capture problems if expr is "status". */ \ + const PROTOBUF_NAMESPACE_ID::util::Status _status = (expr); \ + if (PROTOBUF_PREDICT_FALSE(!_status.ok())) return _status; \ + } while (0) + +// Internal helper for concatenating macro values. +#define STATUS_MACROS_CONCAT_NAME_INNER(x, y) x##y +#define STATUS_MACROS_CONCAT_NAME(x, y) STATUS_MACROS_CONCAT_NAME_INNER(x, y) + +template +Status DoAssignOrReturn(T& lhs, StatusOr result) { + if (result.ok()) { + lhs = result.value(); + } + return result.status(); +} + +#define ASSIGN_OR_RETURN_IMPL(status, lhs, rexpr) \ + Status status = DoAssignOrReturn(lhs, (rexpr)); \ + if (PROTOBUF_PREDICT_FALSE(!status.ok())) return status; + +// Executes an expression that returns a util::StatusOr, extracting its value +// into the variable defined by lhs (or returning on error). +// +// Example: Assigning to an existing value +// ValueType value; +// ASSIGN_OR_RETURN(value, MaybeGetValue(arg)); +// +// WARNING: ASSIGN_OR_RETURN expands into multiple statements; it cannot be used +// in a single statement (e.g. as the body of an if statement without {})! +#define ASSIGN_OR_RETURN(lhs, rexpr) \ + ASSIGN_OR_RETURN_IMPL( \ + STATUS_MACROS_CONCAT_NAME(_status_or_value, __COUNTER__), lhs, rexpr); + +} // namespace util +} // namespace protobuf +} // namespace google + +#endif // GOOGLE_PROTOBUF_STUBS_STATUS_H_ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/status_test.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/status_test.cc new file mode 100644 index 0000000..9e9edf7 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/status_test.cc @@ -0,0 +1,278 @@ +// 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. +#include + +#include + +#include +#include + +namespace google { +namespace protobuf { +namespace { + +TEST(Status, Constructor) { + EXPECT_EQ(util::StatusCode::kOk, + util::Status(util::StatusCode::kOk, "").code()); + EXPECT_EQ(util::StatusCode::kCancelled, + util::Status(util::StatusCode::kCancelled, "").code()); + EXPECT_EQ(util::StatusCode::kUnknown, + util::Status(util::StatusCode::kUnknown, "").code()); + EXPECT_EQ(util::StatusCode::kInvalidArgument, + util::Status(util::StatusCode::kInvalidArgument, "").code()); + EXPECT_EQ(util::StatusCode::kDeadlineExceeded, + util::Status(util::StatusCode::kDeadlineExceeded, "").code()); + EXPECT_EQ(util::StatusCode::kNotFound, + util::Status(util::StatusCode::kNotFound, "").code()); + EXPECT_EQ(util::StatusCode::kAlreadyExists, + util::Status(util::StatusCode::kAlreadyExists, "").code()); + EXPECT_EQ(util::StatusCode::kPermissionDenied, + util::Status(util::StatusCode::kPermissionDenied, "").code()); + EXPECT_EQ(util::StatusCode::kUnauthenticated, + util::Status(util::StatusCode::kUnauthenticated, "").code()); + EXPECT_EQ(util::StatusCode::kResourceExhausted, + util::Status(util::StatusCode::kResourceExhausted, "").code()); + EXPECT_EQ(util::StatusCode::kFailedPrecondition, + util::Status(util::StatusCode::kFailedPrecondition, "").code()); + EXPECT_EQ(util::StatusCode::kAborted, + util::Status(util::StatusCode::kAborted, "").code()); + EXPECT_EQ(util::StatusCode::kOutOfRange, + util::Status(util::StatusCode::kOutOfRange, "").code()); + EXPECT_EQ(util::StatusCode::kUnimplemented, + util::Status(util::StatusCode::kUnimplemented, "").code()); + EXPECT_EQ(util::StatusCode::kInternal, + util::Status(util::StatusCode::kInternal, "").code()); + EXPECT_EQ(util::StatusCode::kUnavailable, + util::Status(util::StatusCode::kUnavailable, "").code()); + EXPECT_EQ(util::StatusCode::kDataLoss, + util::Status(util::StatusCode::kDataLoss, "").code()); +} + +TEST(Status, ConstructorZero) { + util::Status status(util::StatusCode::kOk, "msg"); + EXPECT_TRUE(status.ok()); + EXPECT_EQ("OK", status.ToString()); + EXPECT_EQ(util::OkStatus(), status); +} + +TEST(Status, ConvenienceConstructors) { + EXPECT_EQ(util::StatusCode::kOk, util::OkStatus().code()); + EXPECT_EQ("", util::OkStatus().message()); + + EXPECT_EQ(util::StatusCode::kCancelled, util::CancelledError("").code()); + EXPECT_EQ("", util::CancelledError("").message()); + EXPECT_EQ("foo", util::CancelledError("foo").message()); + EXPECT_EQ("bar", util::CancelledError("bar").message()); + + EXPECT_EQ(util::StatusCode::kUnknown, util::UnknownError("").code()); + EXPECT_EQ("", util::UnknownError("").message()); + EXPECT_EQ("foo", util::UnknownError("foo").message()); + EXPECT_EQ("bar", util::UnknownError("bar").message()); + + EXPECT_EQ(util::StatusCode::kInvalidArgument, + util::InvalidArgumentError("").code()); + EXPECT_EQ("", util::InvalidArgumentError("").message()); + EXPECT_EQ("foo", util::InvalidArgumentError("foo").message()); + EXPECT_EQ("bar", util::InvalidArgumentError("bar").message()); + + EXPECT_EQ(util::StatusCode::kDeadlineExceeded, + util::DeadlineExceededError("").code()); + EXPECT_EQ("", util::DeadlineExceededError("").message()); + EXPECT_EQ("foo", util::DeadlineExceededError("foo").message()); + EXPECT_EQ("bar", util::DeadlineExceededError("bar").message()); + + EXPECT_EQ(util::StatusCode::kNotFound, util::NotFoundError("").code()); + EXPECT_EQ("", util::NotFoundError("").message()); + EXPECT_EQ("foo", util::NotFoundError("foo").message()); + EXPECT_EQ("bar", util::NotFoundError("bar").message()); + + EXPECT_EQ(util::StatusCode::kAlreadyExists, + util::AlreadyExistsError("").code()); + EXPECT_EQ("", util::AlreadyExistsError("").message()); + EXPECT_EQ("foo", util::AlreadyExistsError("foo").message()); + EXPECT_EQ("bar", util::AlreadyExistsError("bar").message()); + + EXPECT_EQ(util::StatusCode::kPermissionDenied, + util::PermissionDeniedError("").code()); + EXPECT_EQ("", util::PermissionDeniedError("").message()); + EXPECT_EQ("foo", util::PermissionDeniedError("foo").message()); + EXPECT_EQ("bar", util::PermissionDeniedError("bar").message()); + + EXPECT_EQ(util::StatusCode::kUnauthenticated, + util::UnauthenticatedError("").code()); + EXPECT_EQ("", util::UnauthenticatedError("").message()); + EXPECT_EQ("foo", util::UnauthenticatedError("foo").message()); + EXPECT_EQ("bar", util::UnauthenticatedError("bar").message()); + + EXPECT_EQ(util::StatusCode::kResourceExhausted, + util::ResourceExhaustedError("").code()); + EXPECT_EQ("", util::ResourceExhaustedError("").message()); + EXPECT_EQ("foo", util::ResourceExhaustedError("foo").message()); + EXPECT_EQ("bar", util::ResourceExhaustedError("bar").message()); + + EXPECT_EQ(util::StatusCode::kFailedPrecondition, + util::FailedPreconditionError("").code()); + EXPECT_EQ("", util::FailedPreconditionError("").message()); + EXPECT_EQ("foo", util::FailedPreconditionError("foo").message()); + EXPECT_EQ("bar", util::FailedPreconditionError("bar").message()); + + EXPECT_EQ(util::StatusCode::kAborted, util::AbortedError("").code()); + EXPECT_EQ("", util::AbortedError("").message()); + EXPECT_EQ("foo", util::AbortedError("foo").message()); + EXPECT_EQ("bar", util::AbortedError("bar").message()); + + EXPECT_EQ(util::StatusCode::kOutOfRange, util::OutOfRangeError("").code()); + EXPECT_EQ("", util::OutOfRangeError("").message()); + EXPECT_EQ("foo", util::OutOfRangeError("foo").message()); + EXPECT_EQ("bar", util::OutOfRangeError("bar").message()); + + EXPECT_EQ(util::StatusCode::kUnimplemented, + util::UnimplementedError("").code()); + EXPECT_EQ("", util::UnimplementedError("").message()); + EXPECT_EQ("foo", util::UnimplementedError("foo").message()); + EXPECT_EQ("bar", util::UnimplementedError("bar").message()); + + EXPECT_EQ(util::StatusCode::kInternal, util::InternalError("").code()); + EXPECT_EQ("", util::InternalError("").message()); + EXPECT_EQ("foo", util::InternalError("foo").message()); + EXPECT_EQ("bar", util::InternalError("bar").message()); + + EXPECT_EQ(util::StatusCode::kUnavailable, util::UnavailableError("").code()); + EXPECT_EQ("", util::UnavailableError("").message()); + EXPECT_EQ("foo", util::UnavailableError("foo").message()); + EXPECT_EQ("bar", util::UnavailableError("bar").message()); + + EXPECT_EQ(util::StatusCode::kDataLoss, util::DataLossError("").code()); + EXPECT_EQ("", util::DataLossError("").message()); + EXPECT_EQ("foo", util::DataLossError("foo").message()); + EXPECT_EQ("bar", util::DataLossError("bar").message()); +} + +TEST(Status, ConvenienceTests) { + EXPECT_TRUE(util::OkStatus().ok()); + EXPECT_TRUE(util::IsCancelled(util::CancelledError(""))); + EXPECT_TRUE(util::IsUnknown(util::UnknownError(""))); + EXPECT_TRUE(util::IsInvalidArgument(util::InvalidArgumentError(""))); + EXPECT_TRUE(util::IsDeadlineExceeded(util::DeadlineExceededError(""))); + EXPECT_TRUE(util::IsNotFound(util::NotFoundError(""))); + EXPECT_TRUE(util::IsAlreadyExists(util::AlreadyExistsError(""))); + EXPECT_TRUE(util::IsPermissionDenied(util::PermissionDeniedError(""))); + EXPECT_TRUE(util::IsUnauthenticated(util::UnauthenticatedError(""))); + EXPECT_TRUE(util::IsResourceExhausted(util::ResourceExhaustedError(""))); + EXPECT_TRUE(util::IsFailedPrecondition(util::FailedPreconditionError(""))); + EXPECT_TRUE(util::IsAborted(util::AbortedError(""))); + EXPECT_TRUE(util::IsOutOfRange(util::OutOfRangeError(""))); + EXPECT_TRUE(util::IsUnimplemented(util::UnimplementedError(""))); + EXPECT_TRUE(util::IsInternal(util::InternalError(""))); + EXPECT_TRUE(util::IsUnavailable(util::UnavailableError(""))); + EXPECT_TRUE(util::IsDataLoss(util::DataLossError(""))); +} + +TEST(Status, Empty) { + util::Status status; + EXPECT_TRUE(status.ok()); + EXPECT_EQ(util::OkStatus(), status); + EXPECT_EQ(util::StatusCode::kOk, status.code()); + EXPECT_EQ("OK", status.ToString()); +} + +TEST(Status, CheckOK) { + util::Status status; + GOOGLE_CHECK_OK(status); + GOOGLE_CHECK_OK(status) << "Failed"; + GOOGLE_DCHECK_OK(status) << "Failed"; +} + +TEST(Status, ErrorMessage) { + util::Status status = util::InvalidArgumentError(""); + EXPECT_FALSE(status.ok()); + EXPECT_EQ("", status.message().ToString()); + EXPECT_EQ("INVALID_ARGUMENT", status.ToString()); + status = util::InvalidArgumentError("msg"); + EXPECT_FALSE(status.ok()); + EXPECT_EQ("msg", status.message().ToString()); + EXPECT_EQ("INVALID_ARGUMENT:msg", status.ToString()); + status = util::Status(util::StatusCode::kOk, "msg"); + EXPECT_TRUE(status.ok()); + EXPECT_EQ("", status.message().ToString()); + EXPECT_EQ("OK", status.ToString()); +} + +TEST(Status, Copy) { + util::Status a = util::UnknownError("message"); + util::Status b(a); + ASSERT_EQ(a.ToString(), b.ToString()); +} + +TEST(Status, Assign) { + util::Status a = util::UnknownError("message"); + util::Status b; + b = a; + ASSERT_EQ(a.ToString(), b.ToString()); +} + +TEST(Status, AssignEmpty) { + util::Status a = util::UnknownError("message"); + util::Status b; + a = b; + ASSERT_EQ(std::string("OK"), a.ToString()); + ASSERT_TRUE(b.ok()); + ASSERT_TRUE(a.ok()); +} + +TEST(Status, EqualsOK) { ASSERT_EQ(util::OkStatus(), util::Status()); } + +TEST(Status, EqualsSame) { + const util::Status a = util::CancelledError("message"); + const util::Status b = util::CancelledError("message"); + ASSERT_EQ(a, b); +} + +TEST(Status, EqualsCopy) { + const util::Status a = util::CancelledError("message"); + const util::Status b = a; + ASSERT_EQ(a, b); +} + +TEST(Status, EqualsDifferentCode) { + const util::Status a = util::CancelledError("message"); + const util::Status b = util::UnknownError("message"); + ASSERT_NE(a, b); +} + +TEST(Status, EqualsDifferentMessage) { + const util::Status a = util::CancelledError("message"); + const util::Status b = util::CancelledError("another"); + ASSERT_NE(a, b); +} + +} // namespace +} // namespace protobuf +} // namespace google diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/template_util.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/template_util.h new file mode 100644 index 0000000..feef904 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/stubs/template_util.h @@ -0,0 +1,138 @@ +// Copyright 2005 Google Inc. +// All rights reserved. +// +// 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: lar@google.com (Laramie Leavitt) +// +// Template metaprogramming utility functions. +// +// This code is compiled directly on many platforms, including client +// platforms like Windows, Mac, and embedded systems. Before making +// any changes here, make sure that you're not breaking any platforms. +// +// +// The names chosen here reflect those used in tr1 and the boost::mpl +// library, there are similar operations used in the Loki library as +// well. I prefer the boost names for 2 reasons: +// 1. I think that portions of the Boost libraries are more likely to +// be included in the c++ standard. +// 2. It is not impossible that some of the boost libraries will be +// included in our own build in the future. +// Both of these outcomes means that we may be able to directly replace +// some of these with boost equivalents. +// +#ifndef GOOGLE_PROTOBUF_TEMPLATE_UTIL_H_ +#define GOOGLE_PROTOBUF_TEMPLATE_UTIL_H_ + +namespace google { +namespace protobuf { +namespace internal { + +// Types small_ and big_ are guaranteed such that sizeof(small_) < +// sizeof(big_) +typedef char small_; + +struct big_ { + char dummy[2]; +}; + +// Identity metafunction. +template +struct identity_ { + typedef T type; +}; + +// integral_constant, defined in tr1, is a wrapper for an integer +// value. We don't really need this generality; we could get away +// with hardcoding the integer type to bool. We use the fully +// general integer_constant for compatibility with tr1. + +template +struct integral_constant { + static const T value = v; + typedef T value_type; + typedef integral_constant type; +}; + +template const T integral_constant::value; + + +// Abbreviations: true_type and false_type are structs that represent boolean +// true and false values. Also define the boost::mpl versions of those names, +// true_ and false_. +typedef integral_constant true_type; +typedef integral_constant false_type; +typedef true_type true_; +typedef false_type false_; + +// if_ is a templatized conditional statement. +// if_ is a compile time evaluation of cond. +// if_<>::type contains A if cond is true, B otherwise. +template +struct if_{ + typedef A type; +}; + +template +struct if_ { + typedef B type; +}; + + +// type_equals_ is a template type comparator, similar to Loki IsSameType. +// type_equals_::value is true iff "A" is the same type as "B". +// +// New code should prefer base::is_same, defined in base/type_traits.h. +// It is functionally identical, but is_same is the standard spelling. +template +struct type_equals_ : public false_ { +}; + +template +struct type_equals_ : public true_ { +}; + +// and_ is a template && operator. +// and_::value evaluates "A::value && B::value". +template +struct and_ : public integral_constant { +}; + +// or_ is a template || operator. +// or_::value evaluates "A::value || B::value". +template +struct or_ : public integral_constant { +}; + + +} // namespace internal +} // namespace protobuf +} // namespace google + +#endif // GOOGLE_PROTOBUF_TEMPLATE_UTIL_H_ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/testing/file.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/testing/file.cc new file mode 100644 index 0000000..7b62887 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/testing/file.cc @@ -0,0 +1,215 @@ +// 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) +// emulates google3/file/base/file.cc + +#include +#include +#include +#include +#ifdef _MSC_VER +#define WIN32_LEAN_AND_MEAN // yeah, right +#include // Find*File(). :( +// #include +#else +#include +#include +#endif +#include + +#include +#include + +namespace google { +namespace protobuf { + +#ifdef _WIN32 +// Windows doesn't have symbolic links. +#define lstat stat +// DO NOT include , instead create functions in io_win32.{h,cc} and import +// them like we do below. +#endif + +#ifdef _WIN32 +using google::protobuf::io::win32::access; +using google::protobuf::io::win32::chdir; +using google::protobuf::io::win32::fopen; +using google::protobuf::io::win32::mkdir; +using google::protobuf::io::win32::stat; +#endif + +bool File::Exists(const std::string& name) { + return access(name.c_str(), F_OK) == 0; +} + +bool File::ReadFileToString(const std::string& name, std::string* output, + bool text_mode) { + char buffer[1024]; + FILE* file = fopen(name.c_str(), text_mode ? "rt" : "rb"); + if (file == NULL) return false; + + while (true) { + size_t n = fread(buffer, 1, sizeof(buffer), file); + if (n <= 0) break; + output->append(buffer, n); + } + + int error = ferror(file); + if (fclose(file) != 0) return false; + return error == 0; +} + +void File::ReadFileToStringOrDie(const std::string& name, std::string* output) { + GOOGLE_CHECK(ReadFileToString(name, output)) << "Could not read: " << name; +} + +bool File::WriteStringToFile(const std::string& contents, + const std::string& name) { + FILE* file = fopen(name.c_str(), "wb"); + if (file == NULL) { + GOOGLE_LOG(ERROR) << "fopen(" << name << ", \"wb\"): " << strerror(errno); + return false; + } + + if (fwrite(contents.data(), 1, contents.size(), file) != contents.size()) { + GOOGLE_LOG(ERROR) << "fwrite(" << name << "): " << strerror(errno); + fclose(file); + return false; + } + + if (fclose(file) != 0) { + return false; + } + return true; +} + +void File::WriteStringToFileOrDie(const std::string& contents, + const std::string& name) { + FILE* file = fopen(name.c_str(), "wb"); + GOOGLE_CHECK(file != NULL) + << "fopen(" << name << ", \"wb\"): " << strerror(errno); + GOOGLE_CHECK_EQ(fwrite(contents.data(), 1, contents.size(), file), + contents.size()) + << "fwrite(" << name << "): " << strerror(errno); + GOOGLE_CHECK(fclose(file) == 0) + << "fclose(" << name << "): " << strerror(errno); +} + +bool File::CreateDir(const std::string& name, int mode) { + if (!name.empty()) { + GOOGLE_CHECK_OK(name[name.size() - 1] != '.'); + } + return mkdir(name.c_str(), mode) == 0; +} + +bool File::RecursivelyCreateDir(const std::string& path, int mode) { + if (CreateDir(path, mode)) return true; + + if (Exists(path)) return false; + + // Try creating the parent. + std::string::size_type slashpos = path.find_last_of('/'); + if (slashpos == std::string::npos) { + // No parent given. + return false; + } + + return RecursivelyCreateDir(path.substr(0, slashpos), mode) && + CreateDir(path, mode); +} + +void File::DeleteRecursively(const std::string& name, void* dummy1, + void* dummy2) { + if (name.empty()) return; + + // We don't care too much about error checking here since this is only used + // in tests to delete temporary directories that are under /tmp anyway. + +#ifdef _MSC_VER + // This interface is so weird. + WIN32_FIND_DATAA find_data; + HANDLE find_handle = FindFirstFileA((name + "/*").c_str(), &find_data); + if (find_handle == INVALID_HANDLE_VALUE) { + // Just delete it, whatever it is. + DeleteFileA(name.c_str()); + RemoveDirectoryA(name.c_str()); + return; + } + + do { + std::string entry_name = find_data.cFileName; + if (entry_name != "." && entry_name != "..") { + std::string path = name + "/" + entry_name; + if (find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { + DeleteRecursively(path, NULL, NULL); + RemoveDirectoryA(path.c_str()); + } else { + DeleteFileA(path.c_str()); + } + } + } while(FindNextFileA(find_handle, &find_data)); + FindClose(find_handle); + + RemoveDirectoryA(name.c_str()); +#else + // Use opendir()! Yay! + // lstat = Don't follow symbolic links. + struct stat stats; + if (lstat(name.c_str(), &stats) != 0) return; + + if (S_ISDIR(stats.st_mode)) { + DIR* dir = opendir(name.c_str()); + if (dir != NULL) { + while (true) { + struct dirent* entry = readdir(dir); + if (entry == NULL) break; + std::string entry_name = entry->d_name; + if (entry_name != "." && entry_name != "..") { + DeleteRecursively(name + "/" + entry_name, NULL, NULL); + } + } + } + + closedir(dir); + rmdir(name.c_str()); + + } else if (S_ISREG(stats.st_mode)) { + remove(name.c_str()); + } +#endif +} + +bool File::ChangeWorkingDirectory(const std::string& new_working_directory) { + return chdir(new_working_directory.c_str()) == 0; +} + +} // namespace protobuf +} // namespace google diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/testing/googletest.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/testing/googletest.h new file mode 100644 index 0000000..6a0c694 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/testing/googletest.h @@ -0,0 +1,104 @@ +// 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) +// emulates google3/testing/base/public/googletest.h + +#ifndef GOOGLE_PROTOBUF_GOOGLETEST_H__ +#define GOOGLE_PROTOBUF_GOOGLETEST_H__ + +#include +#include +#include +#include +#include +// Disable death tests if we use exceptions in CHECK(). +#if !PROTOBUF_USE_EXCEPTIONS && defined(GTEST_HAS_DEATH_TEST) && \ + !GTEST_OS_WINDOWS +#define PROTOBUF_HAS_DEATH_TEST +#endif + +namespace google { +namespace protobuf { + +// When running unittests, get the directory containing the source code. +std::string TestSourceDir(); + +// When running unittests, get a directory where temporary files may be +// placed. +std::string TestTempDir(); + +// Capture all text written to stdout or stderr. +void CaptureTestStdout(); +void CaptureTestStderr(); + +// Stop capturing stdout or stderr and return the text captured. +std::string GetCapturedTestStdout(); +std::string GetCapturedTestStderr(); + +// For use with ScopedMemoryLog::GetMessages(). Inside Google the LogLevel +// constants don't have the LOGLEVEL_ prefix, so the code that used +// ScopedMemoryLog refers to LOGLEVEL_ERROR as just ERROR. +#undef ERROR // defend against promiscuous windows.h +static const LogLevel ERROR = LOGLEVEL_ERROR; +static const LogLevel WARNING = LOGLEVEL_WARNING; + +// Receives copies of all LOG(ERROR) messages while in scope. Sample usage: +// { +// ScopedMemoryLog log; // constructor registers object as a log sink +// SomeRoutineThatMayLogMessages(); +// const vector& warnings = log.GetMessages(ERROR); +// } // destructor unregisters object as a log sink +// This is a dummy implementation which covers only what is used by protocol +// buffer unit tests. +class ScopedMemoryLog { + public: + ScopedMemoryLog(); + virtual ~ScopedMemoryLog(); + + // Fetches all messages with the given severity level. + const std::vector& GetMessages(LogLevel error); + + private: + std::map > messages_; + LogHandler* old_handler_; + + static void HandleLog(LogLevel level, const char* filename, int line, + const std::string& message); + + static ScopedMemoryLog* active_log_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ScopedMemoryLog); +}; + +} // namespace protobuf +} // namespace google + +#endif // GOOGLE_PROTOBUF_GOOGLETEST_H__ diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/testing/zcgunzip.cc b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/testing/zcgunzip.cc new file mode 100644 index 0000000..68f8172 --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/testing/zcgunzip.cc @@ -0,0 +1,84 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2009 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: brianolson@google.com (Brian Olson) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. +// +// Test program to verify that GzipInputStream is compatible with command line +// gunzip or java.util.zip.GzipInputStream +// +// Reads gzip stream on standard input and writes decompressed data to standard +// output. + +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#ifndef STDIN_FILENO +#define STDIN_FILENO 0 +#endif +#ifndef STDOUT_FILENO +#define STDOUT_FILENO 1 +#endif +#endif + +#include +#include + +using google::protobuf::io::FileInputStream; +using google::protobuf::io::GzipInputStream; + +int main(int argc, const char** argv) { + FileInputStream fin(STDIN_FILENO); + GzipInputStream in(&fin); + + while (true) { + const void* inptr; + int inlen; + bool ok; + ok = in.Next(&inptr, &inlen); + if (!ok) { + break; + } + if (inlen > 0) { + int err = write(STDOUT_FILENO, inptr, inlen); + if (err != inlen) { + fprintf(stderr, "write unexpectedly returned %d.\n", err); + return 1; + } + } + } + + return 0; +} diff --git a/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/type.pb.h b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/type.pb.h new file mode 100644 index 0000000..cf5943c --- /dev/null +++ b/tools/go-generator/cmd/generator/_protobuf/src/google/protobuf/type.pb.h @@ -0,0 +1,2581 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/type.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2ftype_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2ftype_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3019000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3019004 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include +#include +#include +#include +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2ftype_2eproto PROTOBUF_EXPORT +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2ftype_2eproto { + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[5] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; + static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; + static const uint32_t offsets[]; +}; +PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2ftype_2eproto; +PROTOBUF_NAMESPACE_OPEN +class Enum; +struct EnumDefaultTypeInternal; +PROTOBUF_EXPORT extern EnumDefaultTypeInternal _Enum_default_instance_; +class EnumValue; +struct EnumValueDefaultTypeInternal; +PROTOBUF_EXPORT extern EnumValueDefaultTypeInternal _EnumValue_default_instance_; +class Field; +struct FieldDefaultTypeInternal; +PROTOBUF_EXPORT extern FieldDefaultTypeInternal _Field_default_instance_; +class Option; +struct OptionDefaultTypeInternal; +PROTOBUF_EXPORT extern OptionDefaultTypeInternal _Option_default_instance_; +class Type; +struct TypeDefaultTypeInternal; +PROTOBUF_EXPORT extern TypeDefaultTypeInternal _Type_default_instance_; +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Enum* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Enum>(Arena*); +template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::EnumValue* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::EnumValue>(Arena*); +template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Field* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Field>(Arena*); +template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Option* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Option>(Arena*); +template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Type* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Type>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN + +enum Field_Kind : int { + Field_Kind_TYPE_UNKNOWN = 0, + Field_Kind_TYPE_DOUBLE = 1, + Field_Kind_TYPE_FLOAT = 2, + Field_Kind_TYPE_INT64 = 3, + Field_Kind_TYPE_UINT64 = 4, + Field_Kind_TYPE_INT32 = 5, + Field_Kind_TYPE_FIXED64 = 6, + Field_Kind_TYPE_FIXED32 = 7, + Field_Kind_TYPE_BOOL = 8, + Field_Kind_TYPE_STRING = 9, + Field_Kind_TYPE_GROUP = 10, + Field_Kind_TYPE_MESSAGE = 11, + Field_Kind_TYPE_BYTES = 12, + Field_Kind_TYPE_UINT32 = 13, + Field_Kind_TYPE_ENUM = 14, + Field_Kind_TYPE_SFIXED32 = 15, + Field_Kind_TYPE_SFIXED64 = 16, + Field_Kind_TYPE_SINT32 = 17, + Field_Kind_TYPE_SINT64 = 18, + Field_Kind_Field_Kind_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits::min(), + Field_Kind_Field_Kind_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits::max() +}; +PROTOBUF_EXPORT bool Field_Kind_IsValid(int value); +constexpr Field_Kind Field_Kind_Kind_MIN = Field_Kind_TYPE_UNKNOWN; +constexpr Field_Kind Field_Kind_Kind_MAX = Field_Kind_TYPE_SINT64; +constexpr int Field_Kind_Kind_ARRAYSIZE = Field_Kind_Kind_MAX + 1; + +PROTOBUF_EXPORT const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Field_Kind_descriptor(); +template +inline const std::string& Field_Kind_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function Field_Kind_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + Field_Kind_descriptor(), enum_t_value); +} +inline bool Field_Kind_Parse( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, Field_Kind* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( + Field_Kind_descriptor(), name, value); +} +enum Field_Cardinality : int { + Field_Cardinality_CARDINALITY_UNKNOWN = 0, + Field_Cardinality_CARDINALITY_OPTIONAL = 1, + Field_Cardinality_CARDINALITY_REQUIRED = 2, + Field_Cardinality_CARDINALITY_REPEATED = 3, + Field_Cardinality_Field_Cardinality_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits::min(), + Field_Cardinality_Field_Cardinality_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits::max() +}; +PROTOBUF_EXPORT bool Field_Cardinality_IsValid(int value); +constexpr Field_Cardinality Field_Cardinality_Cardinality_MIN = Field_Cardinality_CARDINALITY_UNKNOWN; +constexpr Field_Cardinality Field_Cardinality_Cardinality_MAX = Field_Cardinality_CARDINALITY_REPEATED; +constexpr int Field_Cardinality_Cardinality_ARRAYSIZE = Field_Cardinality_Cardinality_MAX + 1; + +PROTOBUF_EXPORT const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Field_Cardinality_descriptor(); +template +inline const std::string& Field_Cardinality_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function Field_Cardinality_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + Field_Cardinality_descriptor(), enum_t_value); +} +inline bool Field_Cardinality_Parse( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, Field_Cardinality* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( + Field_Cardinality_descriptor(), name, value); +} +enum Syntax : int { + SYNTAX_PROTO2 = 0, + SYNTAX_PROTO3 = 1, + Syntax_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits::min(), + Syntax_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits::max() +}; +PROTOBUF_EXPORT bool Syntax_IsValid(int value); +constexpr Syntax Syntax_MIN = SYNTAX_PROTO2; +constexpr Syntax Syntax_MAX = SYNTAX_PROTO3; +constexpr int Syntax_ARRAYSIZE = Syntax_MAX + 1; + +PROTOBUF_EXPORT const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Syntax_descriptor(); +template +inline const std::string& Syntax_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function Syntax_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + Syntax_descriptor(), enum_t_value); +} +inline bool Syntax_Parse( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, Syntax* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( + Syntax_descriptor(), name, value); +} +// =================================================================== + +class PROTOBUF_EXPORT Type final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Type) */ { + public: + inline Type() : Type(nullptr) {} + ~Type() override; + explicit constexpr Type(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + Type(const Type& from); + Type(Type&& from) noexcept + : Type() { + *this = ::std::move(from); + } + + inline Type& operator=(const Type& from) { + CopyFrom(from); + return *this; + } + inline Type& operator=(Type&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const Type& default_instance() { + return *internal_default_instance(); + } + static inline const Type* internal_default_instance() { + return reinterpret_cast( + &_Type_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(Type& a, Type& b) { + a.Swap(&b); + } + inline void Swap(Type* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(Type* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + Type* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const Type& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom(const Type& from); + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + + private: + void SharedCtor(); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(Type* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.Type"; + } + protected: + explicit Type(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kFieldsFieldNumber = 2, + kOneofsFieldNumber = 3, + kOptionsFieldNumber = 4, + kNameFieldNumber = 1, + kSourceContextFieldNumber = 5, + kSyntaxFieldNumber = 6, + }; + // repeated .google.protobuf.Field fields = 2; + int fields_size() const; + private: + int _internal_fields_size() const; + public: + void clear_fields(); + ::PROTOBUF_NAMESPACE_ID::Field* mutable_fields(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Field >* + mutable_fields(); + private: + const ::PROTOBUF_NAMESPACE_ID::Field& _internal_fields(int index) const; + ::PROTOBUF_NAMESPACE_ID::Field* _internal_add_fields(); + public: + const ::PROTOBUF_NAMESPACE_ID::Field& fields(int index) const; + ::PROTOBUF_NAMESPACE_ID::Field* add_fields(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Field >& + fields() const; + + // repeated string oneofs = 3; + int oneofs_size() const; + private: + int _internal_oneofs_size() const; + public: + void clear_oneofs(); + const std::string& oneofs(int index) const; + std::string* mutable_oneofs(int index); + void set_oneofs(int index, const std::string& value); + void set_oneofs(int index, std::string&& value); + void set_oneofs(int index, const char* value); + void set_oneofs(int index, const char* value, size_t size); + std::string* add_oneofs(); + void add_oneofs(const std::string& value); + void add_oneofs(std::string&& value); + void add_oneofs(const char* value); + void add_oneofs(const char* value, size_t size); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& oneofs() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* mutable_oneofs(); + private: + const std::string& _internal_oneofs(int index) const; + std::string* _internal_add_oneofs(); + public: + + // repeated .google.protobuf.Option options = 4; + int options_size() const; + private: + int _internal_options_size() const; + public: + void clear_options(); + ::PROTOBUF_NAMESPACE_ID::Option* mutable_options(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >* + mutable_options(); + private: + const ::PROTOBUF_NAMESPACE_ID::Option& _internal_options(int index) const; + ::PROTOBUF_NAMESPACE_ID::Option* _internal_add_options(); + public: + const ::PROTOBUF_NAMESPACE_ID::Option& options(int index) const; + ::PROTOBUF_NAMESPACE_ID::Option* add_options(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >& + options() const; + + // string name = 1; + void clear_name(); + const std::string& name() const; + template + void set_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_name(); + PROTOBUF_NODISCARD std::string* release_name(); + void set_allocated_name(std::string* name); + private: + const std::string& _internal_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_name(const std::string& value); + std::string* _internal_mutable_name(); + public: + + // .google.protobuf.SourceContext source_context = 5; + bool has_source_context() const; + private: + bool _internal_has_source_context() const; + public: + void clear_source_context(); + const ::PROTOBUF_NAMESPACE_ID::SourceContext& source_context() const; + PROTOBUF_NODISCARD ::PROTOBUF_NAMESPACE_ID::SourceContext* release_source_context(); + ::PROTOBUF_NAMESPACE_ID::SourceContext* mutable_source_context(); + void set_allocated_source_context(::PROTOBUF_NAMESPACE_ID::SourceContext* source_context); + private: + const ::PROTOBUF_NAMESPACE_ID::SourceContext& _internal_source_context() const; + ::PROTOBUF_NAMESPACE_ID::SourceContext* _internal_mutable_source_context(); + public: + void unsafe_arena_set_allocated_source_context( + ::PROTOBUF_NAMESPACE_ID::SourceContext* source_context); + ::PROTOBUF_NAMESPACE_ID::SourceContext* unsafe_arena_release_source_context(); + + // .google.protobuf.Syntax syntax = 6; + void clear_syntax(); + ::PROTOBUF_NAMESPACE_ID::Syntax syntax() const; + void set_syntax(::PROTOBUF_NAMESPACE_ID::Syntax value); + private: + ::PROTOBUF_NAMESPACE_ID::Syntax _internal_syntax() const; + void _internal_set_syntax(::PROTOBUF_NAMESPACE_ID::Syntax value); + public: + + // @@protoc_insertion_point(class_scope:google.protobuf.Type) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Field > fields_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField oneofs_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option > options_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::SourceContext* source_context_; + int syntax_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + friend struct ::TableStruct_google_2fprotobuf_2ftype_2eproto; +}; +// ------------------------------------------------------------------- + +class PROTOBUF_EXPORT Field final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Field) */ { + public: + inline Field() : Field(nullptr) {} + ~Field() override; + explicit constexpr Field(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + Field(const Field& from); + Field(Field&& from) noexcept + : Field() { + *this = ::std::move(from); + } + + inline Field& operator=(const Field& from) { + CopyFrom(from); + return *this; + } + inline Field& operator=(Field&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const Field& default_instance() { + return *internal_default_instance(); + } + static inline const Field* internal_default_instance() { + return reinterpret_cast( + &_Field_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(Field& a, Field& b) { + a.Swap(&b); + } + inline void Swap(Field* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(Field* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + Field* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const Field& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom(const Field& from); + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + + private: + void SharedCtor(); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(Field* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.Field"; + } + protected: + explicit Field(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + typedef Field_Kind Kind; + static constexpr Kind TYPE_UNKNOWN = + Field_Kind_TYPE_UNKNOWN; + static constexpr Kind TYPE_DOUBLE = + Field_Kind_TYPE_DOUBLE; + static constexpr Kind TYPE_FLOAT = + Field_Kind_TYPE_FLOAT; + static constexpr Kind TYPE_INT64 = + Field_Kind_TYPE_INT64; + static constexpr Kind TYPE_UINT64 = + Field_Kind_TYPE_UINT64; + static constexpr Kind TYPE_INT32 = + Field_Kind_TYPE_INT32; + static constexpr Kind TYPE_FIXED64 = + Field_Kind_TYPE_FIXED64; + static constexpr Kind TYPE_FIXED32 = + Field_Kind_TYPE_FIXED32; + static constexpr Kind TYPE_BOOL = + Field_Kind_TYPE_BOOL; + static constexpr Kind TYPE_STRING = + Field_Kind_TYPE_STRING; + static constexpr Kind TYPE_GROUP = + Field_Kind_TYPE_GROUP; + static constexpr Kind TYPE_MESSAGE = + Field_Kind_TYPE_MESSAGE; + static constexpr Kind TYPE_BYTES = + Field_Kind_TYPE_BYTES; + static constexpr Kind TYPE_UINT32 = + Field_Kind_TYPE_UINT32; + static constexpr Kind TYPE_ENUM = + Field_Kind_TYPE_ENUM; + static constexpr Kind TYPE_SFIXED32 = + Field_Kind_TYPE_SFIXED32; + static constexpr Kind TYPE_SFIXED64 = + Field_Kind_TYPE_SFIXED64; + static constexpr Kind TYPE_SINT32 = + Field_Kind_TYPE_SINT32; + static constexpr Kind TYPE_SINT64 = + Field_Kind_TYPE_SINT64; + static inline bool Kind_IsValid(int value) { + return Field_Kind_IsValid(value); + } + static constexpr Kind Kind_MIN = + Field_Kind_Kind_MIN; + static constexpr Kind Kind_MAX = + Field_Kind_Kind_MAX; + static constexpr int Kind_ARRAYSIZE = + Field_Kind_Kind_ARRAYSIZE; + static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* + Kind_descriptor() { + return Field_Kind_descriptor(); + } + template + static inline const std::string& Kind_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function Kind_Name."); + return Field_Kind_Name(enum_t_value); + } + static inline bool Kind_Parse(::PROTOBUF_NAMESPACE_ID::ConstStringParam name, + Kind* value) { + return Field_Kind_Parse(name, value); + } + + typedef Field_Cardinality Cardinality; + static constexpr Cardinality CARDINALITY_UNKNOWN = + Field_Cardinality_CARDINALITY_UNKNOWN; + static constexpr Cardinality CARDINALITY_OPTIONAL = + Field_Cardinality_CARDINALITY_OPTIONAL; + static constexpr Cardinality CARDINALITY_REQUIRED = + Field_Cardinality_CARDINALITY_REQUIRED; + static constexpr Cardinality CARDINALITY_REPEATED = + Field_Cardinality_CARDINALITY_REPEATED; + static inline bool Cardinality_IsValid(int value) { + return Field_Cardinality_IsValid(value); + } + static constexpr Cardinality Cardinality_MIN = + Field_Cardinality_Cardinality_MIN; + static constexpr Cardinality Cardinality_MAX = + Field_Cardinality_Cardinality_MAX; + static constexpr int Cardinality_ARRAYSIZE = + Field_Cardinality_Cardinality_ARRAYSIZE; + static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* + Cardinality_descriptor() { + return Field_Cardinality_descriptor(); + } + template + static inline const std::string& Cardinality_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function Cardinality_Name."); + return Field_Cardinality_Name(enum_t_value); + } + static inline bool Cardinality_Parse(::PROTOBUF_NAMESPACE_ID::ConstStringParam name, + Cardinality* value) { + return Field_Cardinality_Parse(name, value); + } + + // accessors ------------------------------------------------------- + + enum : int { + kOptionsFieldNumber = 9, + kNameFieldNumber = 4, + kTypeUrlFieldNumber = 6, + kJsonNameFieldNumber = 10, + kDefaultValueFieldNumber = 11, + kKindFieldNumber = 1, + kCardinalityFieldNumber = 2, + kNumberFieldNumber = 3, + kOneofIndexFieldNumber = 7, + kPackedFieldNumber = 8, + }; + // repeated .google.protobuf.Option options = 9; + int options_size() const; + private: + int _internal_options_size() const; + public: + void clear_options(); + ::PROTOBUF_NAMESPACE_ID::Option* mutable_options(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >* + mutable_options(); + private: + const ::PROTOBUF_NAMESPACE_ID::Option& _internal_options(int index) const; + ::PROTOBUF_NAMESPACE_ID::Option* _internal_add_options(); + public: + const ::PROTOBUF_NAMESPACE_ID::Option& options(int index) const; + ::PROTOBUF_NAMESPACE_ID::Option* add_options(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >& + options() const; + + // string name = 4; + void clear_name(); + const std::string& name() const; + template + void set_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_name(); + PROTOBUF_NODISCARD std::string* release_name(); + void set_allocated_name(std::string* name); + private: + const std::string& _internal_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_name(const std::string& value); + std::string* _internal_mutable_name(); + public: + + // string type_url = 6; + void clear_type_url(); + const std::string& type_url() const; + template + void set_type_url(ArgT0&& arg0, ArgT... args); + std::string* mutable_type_url(); + PROTOBUF_NODISCARD std::string* release_type_url(); + void set_allocated_type_url(std::string* type_url); + private: + const std::string& _internal_type_url() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_type_url(const std::string& value); + std::string* _internal_mutable_type_url(); + public: + + // string json_name = 10; + void clear_json_name(); + const std::string& json_name() const; + template + void set_json_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_json_name(); + PROTOBUF_NODISCARD std::string* release_json_name(); + void set_allocated_json_name(std::string* json_name); + private: + const std::string& _internal_json_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_json_name(const std::string& value); + std::string* _internal_mutable_json_name(); + public: + + // string default_value = 11; + void clear_default_value(); + const std::string& default_value() const; + template + void set_default_value(ArgT0&& arg0, ArgT... args); + std::string* mutable_default_value(); + PROTOBUF_NODISCARD std::string* release_default_value(); + void set_allocated_default_value(std::string* default_value); + private: + const std::string& _internal_default_value() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_default_value(const std::string& value); + std::string* _internal_mutable_default_value(); + public: + + // .google.protobuf.Field.Kind kind = 1; + void clear_kind(); + ::PROTOBUF_NAMESPACE_ID::Field_Kind kind() const; + void set_kind(::PROTOBUF_NAMESPACE_ID::Field_Kind value); + private: + ::PROTOBUF_NAMESPACE_ID::Field_Kind _internal_kind() const; + void _internal_set_kind(::PROTOBUF_NAMESPACE_ID::Field_Kind value); + public: + + // .google.protobuf.Field.Cardinality cardinality = 2; + void clear_cardinality(); + ::PROTOBUF_NAMESPACE_ID::Field_Cardinality cardinality() const; + void set_cardinality(::PROTOBUF_NAMESPACE_ID::Field_Cardinality value); + private: + ::PROTOBUF_NAMESPACE_ID::Field_Cardinality _internal_cardinality() const; + void _internal_set_cardinality(::PROTOBUF_NAMESPACE_ID::Field_Cardinality value); + public: + + // int32 number = 3; + void clear_number(); + int32_t number() const; + void set_number(int32_t value); + private: + int32_t _internal_number() const; + void _internal_set_number(int32_t value); + public: + + // int32 oneof_index = 7; + void clear_oneof_index(); + int32_t oneof_index() const; + void set_oneof_index(int32_t value); + private: + int32_t _internal_oneof_index() const; + void _internal_set_oneof_index(int32_t value); + public: + + // bool packed = 8; + void clear_packed(); + bool packed() const; + void set_packed(bool value); + private: + bool _internal_packed() const; + void _internal_set_packed(bool value); + public: + + // @@protoc_insertion_point(class_scope:google.protobuf.Field) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option > options_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr type_url_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr json_name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr default_value_; + int kind_; + int cardinality_; + int32_t number_; + int32_t oneof_index_; + bool packed_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + friend struct ::TableStruct_google_2fprotobuf_2ftype_2eproto; +}; +// ------------------------------------------------------------------- + +class PROTOBUF_EXPORT Enum final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Enum) */ { + public: + inline Enum() : Enum(nullptr) {} + ~Enum() override; + explicit constexpr Enum(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + Enum(const Enum& from); + Enum(Enum&& from) noexcept + : Enum() { + *this = ::std::move(from); + } + + inline Enum& operator=(const Enum& from) { + CopyFrom(from); + return *this; + } + inline Enum& operator=(Enum&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const Enum& default_instance() { + return *internal_default_instance(); + } + static inline const Enum* internal_default_instance() { + return reinterpret_cast( + &_Enum_default_instance_); + } + static constexpr int kIndexInFileMessages = + 2; + + friend void swap(Enum& a, Enum& b) { + a.Swap(&b); + } + inline void Swap(Enum* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(Enum* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + Enum* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const Enum& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom(const Enum& from); + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + + private: + void SharedCtor(); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(Enum* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.Enum"; + } + protected: + explicit Enum(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kEnumvalueFieldNumber = 2, + kOptionsFieldNumber = 3, + kNameFieldNumber = 1, + kSourceContextFieldNumber = 4, + kSyntaxFieldNumber = 5, + }; + // repeated .google.protobuf.EnumValue enumvalue = 2; + int enumvalue_size() const; + private: + int _internal_enumvalue_size() const; + public: + void clear_enumvalue(); + ::PROTOBUF_NAMESPACE_ID::EnumValue* mutable_enumvalue(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::EnumValue >* + mutable_enumvalue(); + private: + const ::PROTOBUF_NAMESPACE_ID::EnumValue& _internal_enumvalue(int index) const; + ::PROTOBUF_NAMESPACE_ID::EnumValue* _internal_add_enumvalue(); + public: + const ::PROTOBUF_NAMESPACE_ID::EnumValue& enumvalue(int index) const; + ::PROTOBUF_NAMESPACE_ID::EnumValue* add_enumvalue(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::EnumValue >& + enumvalue() const; + + // repeated .google.protobuf.Option options = 3; + int options_size() const; + private: + int _internal_options_size() const; + public: + void clear_options(); + ::PROTOBUF_NAMESPACE_ID::Option* mutable_options(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >* + mutable_options(); + private: + const ::PROTOBUF_NAMESPACE_ID::Option& _internal_options(int index) const; + ::PROTOBUF_NAMESPACE_ID::Option* _internal_add_options(); + public: + const ::PROTOBUF_NAMESPACE_ID::Option& options(int index) const; + ::PROTOBUF_NAMESPACE_ID::Option* add_options(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >& + options() const; + + // string name = 1; + void clear_name(); + const std::string& name() const; + template + void set_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_name(); + PROTOBUF_NODISCARD std::string* release_name(); + void set_allocated_name(std::string* name); + private: + const std::string& _internal_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_name(const std::string& value); + std::string* _internal_mutable_name(); + public: + + // .google.protobuf.SourceContext source_context = 4; + bool has_source_context() const; + private: + bool _internal_has_source_context() const; + public: + void clear_source_context(); + const ::PROTOBUF_NAMESPACE_ID::SourceContext& source_context() const; + PROTOBUF_NODISCARD ::PROTOBUF_NAMESPACE_ID::SourceContext* release_source_context(); + ::PROTOBUF_NAMESPACE_ID::SourceContext* mutable_source_context(); + void set_allocated_source_context(::PROTOBUF_NAMESPACE_ID::SourceContext* source_context); + private: + const ::PROTOBUF_NAMESPACE_ID::SourceContext& _internal_source_context() const; + ::PROTOBUF_NAMESPACE_ID::SourceContext* _internal_mutable_source_context(); + public: + void unsafe_arena_set_allocated_source_context( + ::PROTOBUF_NAMESPACE_ID::SourceContext* source_context); + ::PROTOBUF_NAMESPACE_ID::SourceContext* unsafe_arena_release_source_context(); + + // .google.protobuf.Syntax syntax = 5; + void clear_syntax(); + ::PROTOBUF_NAMESPACE_ID::Syntax syntax() const; + void set_syntax(::PROTOBUF_NAMESPACE_ID::Syntax value); + private: + ::PROTOBUF_NAMESPACE_ID::Syntax _internal_syntax() const; + void _internal_set_syntax(::PROTOBUF_NAMESPACE_ID::Syntax value); + public: + + // @@protoc_insertion_point(class_scope:google.protobuf.Enum) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::EnumValue > enumvalue_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option > options_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::SourceContext* source_context_; + int syntax_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + friend struct ::TableStruct_google_2fprotobuf_2ftype_2eproto; +}; +// ------------------------------------------------------------------- + +class PROTOBUF_EXPORT EnumValue final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumValue) */ { + public: + inline EnumValue() : EnumValue(nullptr) {} + ~EnumValue() override; + explicit constexpr EnumValue(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + EnumValue(const EnumValue& from); + EnumValue(EnumValue&& from) noexcept + : EnumValue() { + *this = ::std::move(from); + } + + inline EnumValue& operator=(const EnumValue& from) { + CopyFrom(from); + return *this; + } + inline EnumValue& operator=(EnumValue&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const EnumValue& default_instance() { + return *internal_default_instance(); + } + static inline const EnumValue* internal_default_instance() { + return reinterpret_cast( + &_EnumValue_default_instance_); + } + static constexpr int kIndexInFileMessages = + 3; + + friend void swap(EnumValue& a, EnumValue& b) { + a.Swap(&b); + } + inline void Swap(EnumValue* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(EnumValue* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + EnumValue* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const EnumValue& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom(const EnumValue& from); + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + + private: + void SharedCtor(); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(EnumValue* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.EnumValue"; + } + protected: + explicit EnumValue(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kOptionsFieldNumber = 3, + kNameFieldNumber = 1, + kNumberFieldNumber = 2, + }; + // repeated .google.protobuf.Option options = 3; + int options_size() const; + private: + int _internal_options_size() const; + public: + void clear_options(); + ::PROTOBUF_NAMESPACE_ID::Option* mutable_options(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >* + mutable_options(); + private: + const ::PROTOBUF_NAMESPACE_ID::Option& _internal_options(int index) const; + ::PROTOBUF_NAMESPACE_ID::Option* _internal_add_options(); + public: + const ::PROTOBUF_NAMESPACE_ID::Option& options(int index) const; + ::PROTOBUF_NAMESPACE_ID::Option* add_options(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >& + options() const; + + // string name = 1; + void clear_name(); + const std::string& name() const; + template + void set_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_name(); + PROTOBUF_NODISCARD std::string* release_name(); + void set_allocated_name(std::string* name); + private: + const std::string& _internal_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_name(const std::string& value); + std::string* _internal_mutable_name(); + public: + + // int32 number = 2; + void clear_number(); + int32_t number() const; + void set_number(int32_t value); + private: + int32_t _internal_number() const; + void _internal_set_number(int32_t value); + public: + + // @@protoc_insertion_point(class_scope:google.protobuf.EnumValue) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option > options_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + int32_t number_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + friend struct ::TableStruct_google_2fprotobuf_2ftype_2eproto; +}; +// ------------------------------------------------------------------- + +class PROTOBUF_EXPORT Option final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Option) */ { + public: + inline Option() : Option(nullptr) {} + ~Option() override; + explicit constexpr Option(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + Option(const Option& from); + Option(Option&& from) noexcept + : Option() { + *this = ::std::move(from); + } + + inline Option& operator=(const Option& from) { + CopyFrom(from); + return *this; + } + inline Option& operator=(Option&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const Option& default_instance() { + return *internal_default_instance(); + } + static inline const Option* internal_default_instance() { + return reinterpret_cast( + &_Option_default_instance_); + } + static constexpr int kIndexInFileMessages = + 4; + + friend void swap(Option& a, Option& b) { + a.Swap(&b); + } + inline void Swap(Option* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(Option* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + Option* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage